Skip to content

Commit f651275

Browse files
maria-rckseyeveil
andcommitted
fix(server): name rejected certificates when linking peers
Co-authored-by: Nik <[email protected]>
1 parent 3d78e91 commit f651275

4 files changed

Lines changed: 165 additions & 8 deletions

File tree

‎apps/server/src/peer/PeerLinks.test.ts‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
// @effect-diagnostics-next-line nodeBuiltinImport:off - The HTTPS test server needs certificate bytes.
2+
import * as NodeFS from "node:fs";
3+
// @effect-diagnostics-next-line nodeBuiltinImport:off - A peer with a certificate this machine does not trust.
4+
import * as NodeHttps from "node:https";
15
import { NodeHttpServer } from "@effect/platform-node";
26
import { type ExecutionEnvironmentDescriptor, OrchestratorMcpFailure } from "@t3tools/contracts";
37
import { expect, it } from "@effect/vitest";
@@ -644,3 +648,70 @@ it.effect("linking a picked machine that answers nowhere names it and links noth
644648
}),
645649
).pipe(Effect.provide(NodeHttpServer.layerTest)),
646650
);
651+
652+
/** An https listener whose certificate this machine does not trust. */
653+
const serveUntrusted = Layer.build(
654+
Layer.fresh(
655+
NodeHttpServer.layerServer(
656+
() =>
657+
NodeHttps.createServer({
658+
key: NodeFS.readFileSync(new URL("./fixtures/localhost-key.pem", import.meta.url)),
659+
cert: NodeFS.readFileSync(new URL("./fixtures/localhost-cert.pem", import.meta.url)),
660+
}),
661+
{ port: 0, host: "127.0.0.1" },
662+
),
663+
),
664+
).pipe(
665+
Effect.map((server) => {
666+
const address = Context.get(server, HttpServer.HttpServer).address;
667+
if (address._tag === "UnixPathAddress") throw new Error("expected a TCP address");
668+
return `https://127.0.0.1:${address.port}`;
669+
}),
670+
);
671+
672+
it.effect("names an untrusted certificate instead of calling the peer something else", () =>
673+
Effect.scoped(
674+
Effect.gen(function* () {
675+
const untrusted = yield* serveUntrusted;
676+
const a = yield* makeA(laptop);
677+
const failed = yield* a.links
678+
.link({ url: untrusted, pairingCode: "unused", access: "auto" })
679+
.pipe(Effect.flip);
680+
expect(failed.reason).toBe("unreachable");
681+
expect(failed.message).toContain("certificate this machine rejected");
682+
expect(failed.message).toContain("DEPTH_ZERO_SELF_SIGNED_CERT");
683+
expect(yield* a.links.list).toEqual([]);
684+
685+
// A stored link tries its next address past an untrusted one.
686+
const b = yield* serveB(box);
687+
const pairing = yield* b.auth.issuePairingCredential();
688+
yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
689+
yield* a.sql`
690+
UPDATE peer_environment_links
691+
SET urls_json = ${JSON.stringify([untrusted, b.url])}
692+
WHERE environment_id = ${box.environmentId}
693+
`;
694+
expect((yield* a.links.resolve(box.environmentId)).url).toBe(b.url);
695+
expect((yield* a.links.list).map((link) => link.status)).toEqual(["reachable"]);
696+
}),
697+
).pipe(Effect.provide(NodeHttpServer.layerTest)),
698+
);
699+
700+
it("reads Node's TLS verification code from anywhere in a cause chain", () => {
701+
for (const code of [
702+
"DEPTH_ZERO_SELF_SIGNED_CERT",
703+
"UNABLE_TO_VERIFY_LEAF_SIGNATURE",
704+
"CERT_HAS_EXPIRED",
705+
"ERR_TLS_CERT_ALTNAME_INVALID",
706+
"HOSTNAME_MISMATCH",
707+
"INVALID_CA",
708+
"INVALID_PURPOSE",
709+
"PATH_LENGTH_EXCEEDED",
710+
]) {
711+
expect(PeerLinks.certificateErrorCode({ code })).toBe(code);
712+
}
713+
const wrapped = { message: "fetch failed", cause: { cause: { code: "INVALID_CA" } } };
714+
expect(PeerLinks.certificateErrorCode(wrapped)).toBe("INVALID_CA");
715+
expect(PeerLinks.certificateErrorCode({ cause: { code: "ECONNREFUSED" } })).toBeUndefined();
716+
expect(PeerLinks.certificateErrorCode(new Error("timed out"))).toBeUndefined();
717+
});

‎apps/server/src/peer/PeerLinks.ts‎

Lines changed: 49 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
EnvironmentHttpApi,
66
EnvironmentId,
77
type ExecutionEnvironmentCapabilities,
8+
type ExecutionEnvironmentDescriptor,
89
MCP_PEER_LINK_SOFTWARE_ID,
910
type PeerLink,
1011
type PeerLinkCreateInput,
@@ -22,6 +23,7 @@ import * as Base64Url from "effect/encoding/Base64Url";
2223
import * as Hex from "effect/encoding/Hex";
2324
import * as Layer from "effect/Layer";
2425
import * as Option from "effect/Option";
26+
import * as Predicate from "effect/Predicate";
2527
import * as Redacted from "effect/Redacted";
2628
import * as Result from "effect/Result";
2729
import * as Schema from "effect/Schema";
@@ -50,6 +52,23 @@ const LINK_REDIRECT_URI = "http://127.0.0.1/t3code-peer-link";
5052
const probeTimeout = (origin: string) =>
5153
isLocalLoopbackHost(new URL(origin).hostname) ? Duration.seconds(3) : Duration.seconds(10);
5254

55+
/** Node's TLS verification code in a failed request's cause chain, if any. */
56+
export const certificateErrorCode = (error: unknown) => {
57+
let current = error;
58+
for (let depth = 0; depth < 6 && Predicate.isObject(current); depth++) {
59+
if (
60+
Predicate.hasProperty(current, "code") &&
61+
typeof current.code === "string" &&
62+
/CERT|SELF_SIGNED|UNABLE_TO_(GET|VERIFY)|INVALID_(CA|PURPOSE)|PATH_LENGTH_EXCEEDED|HOSTNAME_MISMATCH/.test(
63+
current.code,
64+
)
65+
)
66+
return current.code;
67+
current = Predicate.hasProperty(current, "cause") ? current.cause : undefined;
68+
}
69+
return undefined;
70+
};
71+
5372
/** A usable link: where to reach the peer and the token to send there. */
5473
export interface ResolvedPeerLink {
5574
readonly link: PeerLink;
@@ -197,14 +216,38 @@ const make = Effect.gen(function* () {
197216
Effect.provideService(HttpClient.HttpClient, peerHttpClient),
198217
);
199218

200-
/** The environment answering at `origin`, or nothing when it does not answer as T3 Code. */
219+
/**
220+
* The environment answering at `origin`, or nothing when it does not answer
221+
* as T3 Code. A certificate this machine rejects fails instead, since
222+
* the peer may well be there.
223+
*/
201224
const describe = (origin: string) =>
202225
clientFor(origin).pipe(
203226
Effect.flatMap((client) => client.metadata.descriptor()),
204227
Effect.timeout(probeTimeout(origin)),
205-
Effect.option,
228+
Effect.asSome,
229+
Effect.catch((error) => {
230+
const code = certificateErrorCode(error);
231+
return code === undefined
232+
? Effect.succeed(Option.none<ExecutionEnvironmentDescriptor>())
233+
: Effect.fail(
234+
new PeerLinkError({
235+
reason: "unreachable",
236+
message: `${origin} presented a certificate this machine rejected (${code}).`,
237+
}),
238+
);
239+
}),
206240
);
207241

242+
/** Whether `url` answers as `environmentId`, counting an untrusted certificate as no. */
243+
const answersAs = Effect.fn("PeerLinks.answersAs")(function* (
244+
url: string,
245+
environmentId: EnvironmentId,
246+
) {
247+
const found = yield* describe(url).pipe(Effect.orElseSucceed(() => Option.none()));
248+
return Option.filter(found, (peer) => peer.environmentId === environmentId);
249+
});
250+
208251
const toLink = Effect.fn("PeerLinks.toLink")(function* (row: PeerLinkRow) {
209252
return {
210253
environmentId: EnvironmentId.make(row.environment_id),
@@ -511,11 +554,9 @@ const make = Effect.gen(function* () {
511554
if (DateTime.isLessThanOrEqualTo(link.expiresAt, now)) return { ...link, status: "expired" };
512555
let label = link.label;
513556
const answered = yield* Effect.findFirst(link.urls, (url) =>
514-
describe(url).pipe(
557+
answersAs(url, link.environmentId).pipe(
515558
Effect.map((found) => {
516-
if (Option.isNone(found) || found.value.environmentId !== link.environmentId) {
517-
return false;
518-
}
559+
if (Option.isNone(found)) return false;
519560
label = found.value.label;
520561
return true;
521562
}),
@@ -584,9 +625,9 @@ const make = Effect.gen(function* () {
584625
let fenced = true;
585626
let label = link.label;
586627
const url = yield* Effect.findFirst(link.urls, (candidate) =>
587-
describe(candidate).pipe(
628+
answersAs(candidate, environmentId).pipe(
588629
Effect.map((found) => {
589-
if (Option.isNone(found) || found.value.environmentId !== environmentId) return false;
630+
if (Option.isNone(found)) return false;
590631
fenced = linkLimitsHold(found.value);
591632
label = found.value.label;
592633
return true;
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line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-----END CERTIFICATE-----
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
-----BEGIN PRIVATE KEY-----
2+
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDR3ScPPMS7o0rQ
3+
j280YvREnkOvHix2zmAlhIFYjQJs1OB7zCDUcS7SBXCGyhPAGfs0WrjUiU20HbwS
4+
8WJm85kGW/bc0GdvFapZGlw0bxMS4WyXvXLMW0RMXMBGzbQV4chM7ZUoCUhj/mtt
5+
hmLBgZYwiGjguh7aWyaNfxgcISpSX7nBrsK9mk/541Gm8gTRWmptTOOIwiKpkNVo
6+
n8TGcQ85XoIymwXorOqv9mgPhMoEODsXY2gAxY+vmULMZjKBGzSp4uJhETyn0zPY
7+
q4fFKGQwkxRyx6k1EJMyK+nUztdJY2TiwsQppiosnlFx+kPiBSWMV5N5OTmft6qN
8+
f0ajkHpXAgMBAAECggEBAMrmKBdhR0uqinCt3HQnn8afxQyP/ak3ylk7jNqSKmAS
9+
SJ8oMi1y6DOBstN+mC3IcMijVcOWpBuaC/W8jsi+h5pQW5INo5MQvUu8Yp0HLse4
10+
Toc+ULknHBdALV3HD2+AhWlq4iR9JRIYLsELhntT0GNH3y42hBHUwqdW03aO0h4k
11+
UHPDtXBA0qWEwLUxtDt6dMWblaBc679FVpQflmj1zjVvcir8hgU5jE8B52zXo0AW
12+
2QtrKZe0ND1TwCmAg61Ox2mZ1MUBFR6pLuKAwTpob6lFoN9OV1x5QETEN6Cz8/db
13+
sgEw9YbVLMY3Gpk379POTd8Bq+CG7ryjdXm6voJDhUECgYEA/wXcR1dv4FLG+i52
14+
utGL2Uc2B4iLzGkVpzm49mpI8yYr7pJ/PBNgkHLEwLzMp6Rybm5tbEWdK3EF+A+b
15+
mZ+KeO6rLcc6QityvkhXL3QfmVX0QFA0DDYRVMJw99fLJgVsR+5FU+angqD/zskp
16+
jKS+iH4CKk3DINbalsMPpHwUmnECgYEA0q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