Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PeerLinks.test.ts

717 lines28.7 KB

1// @effect-diagnostics-next-line nodeBuiltinImport:off - The HTTPS test server needs certificate bytes.
2import * as NodeFS from "node:fs";
3// @effect-diagnostics-next-line nodeBuiltinImport:off - A peer with a certificate this machine does not trust.
4import * as NodeHttps from "node:https";
5import { NodeHttpServer } from "@effect/platform-node";
6import { type ExecutionEnvironmentDescriptor, OrchestratorMcpFailure } from "@t3tools/contracts";
7import { expect, it } from "@effect/vitest";
8import * as Context from "effect/Context";
9import * as Deferred from "effect/Deferred";
10import * as Duration from "effect/Duration";
11import * as Effect from "effect/Effect";
12import * as Fiber from "effect/Fiber";
13import * as Layer from "effect/Layer";
14import * as Option from "effect/Option";
15import * as Ref from "effect/Ref";
16import * as Schema from "effect/Schema";
17import * as HttpRouter from "effect/http/HttpRouter";
18import * as SqlClient from "effect/sql/SqlClient";
19import * as TestClock from "effect/testing/TestClock";
20import { Tool, Toolkit } from "effect/ai";
21import {
22 FetchHttpClient,
23 HttpClient,
24 HttpServer,
25 HttpServerRequest,
26 HttpServerResponse,
27} from "effect/http";
28​
29import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
30import * as McpHttpServer from "../mcp/McpHttpServer.ts";
31import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
32import * as McpToolAccess from "../mcp/McpToolAccess.ts";
33import * as PeerLinks from "./PeerLinks.ts";
34import * as ServerSettings from "../serverSettings.ts";
35import {
36 descriptorOf,
37 layerLinkingEnvironment,
38 servePeer,
39 type ServedPeer,
40} from "./PeerLinks.testkit.ts";
41import * as PeerMcpClient from "./PeerMcpClient.ts";
42​
43import { layerReaderDatabase, traceSqlRouting } from "../persistence/testkit/SqliteRouting.ts";
44​
45/** What B's probe saw: the calling client and the modes it may start work with. */
46const Probe = Schema.Struct({ caller: Schema.String, modes: Schema.String });
47​
48const ProbeToolkit = Toolkit.make(
49 Tool.make("probe", {
50 description: "Reports the calling client and the modes it may start work with.",
51 success: Probe,
52 failure: OrchestratorMcpFailure,
53 failureMode: "return",
54 dependencies: [McpInvocationContext.McpInvocationContext],
55 }),
56 Tool.make("refuse", {
57 description: "Always refuses.",
58 success: Probe,
59 failure: OrchestratorMcpFailure,
60 failureMode: "return",
61 }),
62);
63​
64const probeHandlers = McpToolAccess.toLayer(ProbeToolkit, {
65 probe: McpToolAccess.reads(() =>
66 McpInvocationContext.McpInvocationContext.pipe(
67 Effect.map((scope) => {
68 const modes = McpInvocationContext.clientModeCeiling(scope.client);
69 return {
70 caller: scope.client?.label ?? "none",
71 modes: `${modes.runtimeMode}/${modes.interactionMode}`,
72 };
73 }),
74 ),
75 ),
76 refuse: McpToolAccess.reads(() =>
77 Effect.fail(
78 new OrchestratorMcpFailure({ code: "thread_not_found", message: "No such thread." }),
79 ),
80 ),
81});
82​
83const serveB = (descriptor: ExecutionEnvironmentDescriptor) =>
84 servePeer(descriptor, McpHttpServer.toolkitRegistration(ProbeToolkit, probeHandlers));
85​
86/** Environment A, which links to B. */
87const makeA = (
88 descriptor: ExecutionEnvironmentDescriptor,
89 secrets?: typeof ServerSecretStore.layer,
90) =>
91 layerLinkingEnvironment(descriptor, secrets).pipe(
92 Layer.build,
93 Effect.map((context) => ({
94 links: Context.get(context, PeerLinks.PeerLinks),
95 peer: Context.get(context, PeerMcpClient.PeerMcpClient),
96 sql: Context.get(context, SqlClient.SqlClient),
97 settings: Context.get(context, ServerSettings.ServerSettingsService),
98 })),
99 );
100​
101const laptop = descriptorOf("environment-laptop", "Laptop");
102const box = descriptorOf("environment-box", "Box");
103const probe = (
104 a: Effect.Success<ReturnType<typeof makeA>>,
105 limits: PeerMcpClient.PeerCallLimits = { runtimeMode: "full-access", interactionMode: "default" },
106 tool = "probe",
107) =>
108 a.peer.call({
109 environmentId: box.environmentId,
110 tool,
111 arguments: {},
112 limits,
113 success: Probe,
114 });
115​
116const linkedSessions = (b: ServedPeer) => b.linkedSessions;
117​
118/** Another environment on a socket of its own, answering as `descriptor`. */
119const serveApart = (descriptor: ExecutionEnvironmentDescriptor) =>
120 Layer.build(Layer.fresh(NodeHttpServer.layerTest)).pipe(
121 Effect.flatMap((server) => serveB(descriptor).pipe(Effect.provideContext(server))),
122 );
123​
124it.effect("routes peer reads to readers and sees uncommitted link updates", () =>
125 Effect.scoped(
126 Effect.gen(function* () {
127 const context = yield* layerLinkingEnvironment(
128 laptop,
129 ServerSecretStore.layer,
130 layerReaderDatabase,
131 ).pipe(Layer.build);
132 const links = Context.get(context, PeerLinks.PeerLinks);
133 const sql = Context.get(context, SqlClient.SqlClient);
134 yield* sql`
135 INSERT INTO peer_environment_links (
136 environment_id, secret_name, label, urls_json, access, linked_at, expires_at, fenced
137 ) VALUES (
138 ${box.environmentId}, 'test-secret', 'Box', '[]', 'auto',
139 '2026-01-01T00:00:00.000Z', '2026-01-02T00:00:00.000Z', 1
140 )
141 `;
142 const { queries, trace } = traceSqlRouting();
143 yield* links.list.pipe(trace);
144 expect(Option.getOrThrow(yield* links.get(box.environmentId).pipe(trace)).label).toBe("Box");
145 const reads = queries.filter(({ query }) =>
146 query.includes("SELECT * FROM peer_environment_links"),
147 );
148 expect(reads).toHaveLength(2);
149 expect(reads.map((row) => row.connection)).toEqual(["reader", "reader"]);
150 yield* sql.withTransaction(
151 Effect.gen(function* () {
152 yield* sql`UPDATE peer_environment_links SET label = 'Uncommitted box'`;
153 expect(Option.getOrThrow(yield* links.get(box.environmentId)).label).toBe(
154 "Uncommitted box",
155 );
156 expect((yield* links.list)[0]?.label).toBe("Uncommitted box");
157 }),
158 );
159 expect(yield* links.unlink(box.environmentId)).toBe(true);
160 expect(yield* links.list).toEqual([]);
161 }),
162 ),
163);
164​
165it.effect("links with a pairing code, and the peer holds its agents to the limits they carry", () =>
166 Effect.scoped(
167 Effect.gen(function* () {
168 const b = yield* serveB(box);
169 const a = yield* makeA(laptop);
170​
171 const refused = yield* a.links
172 .link({ url: b.url, pairingCode: "not-a-code", access: "auto" })
173 .pipe(Effect.flip);
174 expect(refused.reason).toBe("pairing_rejected");
175 expect(yield* linkedSessions(b)).toEqual([]);
176​
177 const pairing = yield* b.auth.issuePairingCredential();
178 const linked = yield* a.links.link({
179 url: b.url,
180 pairingCode: pairing.credential,
181 access: "auto",
182 });
183 expect(linked).toMatchObject({
184 environmentId: box.environmentId,
185 label: "Box",
186 urls: [b.url],
187 access: "auto",
188 });
189 // B lists the link under A's name, where it can be revoked.
190 expect((yield* linkedSessions(b)).map((session) => session.client.label)).toEqual([
191 "T3 Code · Laptop",
192 ]);
193 expect(
194 (yield* a.links.list).map(({ environmentId, status }) => [environmentId, status]),
195 ).toEqual([[box.environmentId, "reachable"]]);
196​
197 // The caller's limits narrow the link's access; they never widen it.
198 expect(
199 yield* probe(a, { runtimeMode: "approval-required", interactionMode: "plan" }),
200 ).toEqual({ caller: "T3 Code · Laptop", modes: "approval-required/plan" });
201 expect(yield* probe(a)).toEqual({ caller: "T3 Code · Laptop", modes: "auto/default" });
202​
203 // A refusal keeps the peer's reason.
204 const notFound = yield* probe(a, undefined, "refuse").pipe(Effect.flip);
205 expect(notFound).toMatchObject({ code: "thread_not_found", message: "No such thread." });
206 }),
207 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
208);
209​
210it.effect(
211 "each machine's Linked environments beta gates links, and a link waits while it is off",
212 () =>
213 Effect.scoped(
214 Effect.gen(function* () {
215 const b = yield* serveB(box);
216 const a = yield* makeA(laptop);
217 const pairing = yield* b.auth.issuePairingCredential();
218 const link = a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
219​
220 yield* a.settings.updateSettings({ linkedEnvironmentsEnabled: false });
221 expect(yield* link.pipe(Effect.flip)).toMatchObject({
222 reason: "disabled",
223 message: PeerLinks.LINKED_ENVIRONMENTS_OFF,
224 });
225 expect(yield* Ref.get(b.bearers)).toEqual([]);
226​
227 yield* a.settings.updateSettings({ linkedEnvironmentsEnabled: true });
228 yield* b.settings.updateSettings({ linkedEnvironmentsEnabled: false });
229 const refusedThere = yield* link.pipe(Effect.flip);
230 expect(refusedThere.reason).toBe("pairing_rejected");
231 expect(refusedThere.message).toContain("Linked environments is off on that machine");
232 expect(yield* linkedSessions(b)).toEqual([]);
233​
234 yield* b.settings.updateSettings({ linkedEnvironmentsEnabled: true });
235 yield* link;
236 yield* b.settings.updateSettings({ linkedEnvironmentsEnabled: false });
237 // Not final, so a task already running there picks up again once it is back on.
238 const waiting = yield* probe(a).pipe(Effect.flip);
239 expect(waiting.code).toBe("orchestration_error");
240 expect(waiting.message).toContain("has Linked environments turned off");
241 yield* b.settings.updateSettings({ linkedEnvironmentsEnabled: true });
242 expect(yield* probe(a)).toEqual({ caller: "T3 Code · Laptop", modes: "auto/default" });
243 }),
244 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
245);
246​
247it.effect("a link whose row cannot be stored keeps none of its token", () =>
248 Effect.scoped(
249 Effect.gen(function* () {
250 const b = yield* serveB(box);
251 const held = yield* Ref.make<ReadonlySet<string>>(new Set());
252 const noted = Layer.effect(
253 ServerSecretStore.ServerSecretStore,
254 Effect.map(ServerSecretStore.make, (store) =>
255 ServerSecretStore.ServerSecretStore.of({
256 ...store,
257 set: (name, value) =>
258 store
259 .set(name, value)
260 .pipe(Effect.andThen(Ref.update(held, (names) => new Set([...names, name])))),
261 remove: (name) =>
262 store
263 .remove(name)
264 .pipe(
265 Effect.andThen(
266 Ref.update(held, (names) => new Set([...names].filter((at) => at !== name))),
267 ),
268 ),
269 }),
270 ),
271 );
272 const a = yield* makeA(laptop, noted);
273 yield* a.sql`
274 CREATE TRIGGER refuse_link BEFORE INSERT ON peer_environment_links
275 BEGIN SELECT RAISE(ABORT, 'database or disk is full'); END
276 `;
277 const pairing = yield* b.auth.issuePairingCredential();
278 const failed = yield* a.links
279 .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
280 .pipe(Effect.flip);
281 expect(failed.reason).toBe("storage");
282 expect(yield* Ref.get(held)).toEqual(new Set());
283 }),
284 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
285);
286​
287it.effect("two links racing to one peer leave the stored access matching the token", () =>
288 Effect.scoped(
289 Effect.gen(function* () {
290 const b = yield* serveB(box);
291 const a = yield* makeA(laptop);
292 const [first, second] = yield* Effect.all(
293 [b.auth.issuePairingCredential(), b.auth.issuePairingCredential()],
294 { concurrency: 2 },
295 );
296 yield* Effect.all(
297 [
298 a.links.link({ url: b.url, pairingCode: first.credential, access: "read-only" }),
299 a.links.link({ url: b.url, pairingCode: second.credential, access: "full-access" }),
300 ],
301 { concurrency: 2 },
302 );
303 const [stored] = yield* a.links.list;
304 // The token sent is the one issued with the access the row records.
305 const { modes } = yield* probe(a);
306 expect(modes).toBe(
307 stored!.access === "read-only" ? "approval-required/default" : "full-access/default",
308 );
309 }),
310 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
311);
312​
313/** A bare HTTP server on a socket of its own, answering with `handle`. */
314const serveRaw = <E, R>(
315 handle: (
316 request: HttpServerRequest.HttpServerRequest,
317 ) => Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>,
318) =>
319 Layer.build(Layer.fresh(NodeHttpServer.layerTest)).pipe(
320 Effect.flatMap((server) =>
321 Effect.gen(function* () {
322 yield* HttpServer.serve(Effect.flatMap(HttpServerRequest.HttpServerRequest, handle)).pipe(
323 Layer.build,
324 );
325 const address = (yield* HttpServer.HttpServer).address;
326 if (address._tag === "UnixPathAddress") return yield* Effect.die("expected a TCP address");
327 return `http://127.0.0.1:${address.port}`;
328 }).pipe(Effect.provideContext(server)),
329 ),
330 );
331​
332it.effect("never follows a peer's redirect with the pairing code", () =>
333 Effect.scoped(
334 Effect.gen(function* () {
335 const b = yield* serveB(box);
336 const received = yield* Ref.make<ReadonlyArray<string>>([]);
337 const elsewhere = yield* serveRaw((request) =>
338 Ref.update(received, (seen) => [...seen, `${request.method} ${request.url}`]).pipe(
339 Effect.as(HttpServerResponse.empty({ status: 404 })),
340 ),
341 );
342 // Answers as B, then sends every linking request on to another address.
343 const front = yield* serveRaw((request) =>
344 request.url.startsWith("/.well-known/t3/environment")
345 ? HttpClient.get(`${b.url}${request.url}`).pipe(
346 Effect.flatMap((response) => response.text),
347 Effect.map((body) =>
348 HttpServerResponse.text(body, { contentType: "application/json" }),
349 ),
350 Effect.provide(FetchHttpClient.layer),
351 Effect.orDie,
352 )
353 : Effect.succeed(
354 HttpServerResponse.empty({
355 status: 307,
356 headers: { location: `${elsewhere}${request.url}` },
357 }),
358 ),
359 );
360 const a = yield* makeA(laptop);
361 const pairing = yield* b.auth.issuePairingCredential();
362 yield* a.links
363 .link({ url: front, pairingCode: pairing.credential, access: "auto" })
364 .pipe(Effect.flip);
365 expect(yield* Ref.get(received)).toEqual([]);
366 expect(yield* a.links.list).toEqual([]);
367 }),
368 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
369);
370​
371it.effect("never sends a link's token to an address that stops answering as that peer", () =>
372 Effect.scoped(
373 Effect.gen(function* () {
374 const b = yield* serveB(box);
375 const a = yield* makeA(laptop);
376 const pairing = yield* b.auth.issuePairingCredential();
377 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
378 yield* probe(a);
379 expect((yield* Ref.get(b.bearers)).length).toBeGreaterThan(0);
380​
381 // The address now answers as another environment, as a reused LAN address would.
382 yield* Ref.set(b.descriptor, descriptorOf("environment-impostor", "Impostor"));
383 yield* Ref.set(b.bearers, []);
384 const failed = yield* probe(a).pipe(Effect.flip);
385 expect(failed.message).toContain("Box did not answer");
386 expect(yield* Ref.get(b.bearers)).toEqual([]);
387 expect((yield* a.links.list).map((link) => link.status)).toEqual(["unreachable"]);
388 }),
389 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
390);
391​
392it.effect("cancelling a descriptor probe aborts its request and leaves later resolves fresh", () =>
393 Effect.scoped(
394 Effect.gen(function* () {
395 const hold = yield* Ref.make(false);
396 const requests = yield* Ref.make(0);
397 const entered = yield* Deferred.make<void>();
398 const interrupted = yield* Deferred.make<void>();
399 const holdDescriptor = HttpRouter.middleware(
400 (httpEffect) =>
401 Effect.gen(function* () {
402 const request = yield* HttpServerRequest.HttpServerRequest;
403 if (request.url.startsWith("/.well-known/t3/environment")) {
404 yield* Ref.update(requests, (count) => count + 1);
405 if (yield* Ref.get(hold)) {
406 return yield* Deferred.succeed(entered, undefined).pipe(
407 Effect.andThen(Effect.never),
408 Effect.onInterrupt(() =>
409 Deferred.succeed(interrupted, undefined).pipe(Effect.asVoid),
410 ),
411 Effect.interruptible,
412 );
413 }
414 }
415 return yield* httpEffect;
416 }),
417 { global: true },
418 );
419 const b = yield* servePeer(
420 box,
421 Layer.merge(McpHttpServer.toolkitRegistration(ProbeToolkit, probeHandlers), holdDescriptor),
422 );
423 const a = yield* makeA(laptop);
424 const pairing = yield* b.auth.issuePairingCredential();
425 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
426 yield* Ref.set(b.bearers, []);
427 yield* Ref.set(requests, 0);
428 yield* Ref.set(hold, true);
429​
430 const resolving = yield* a.links.resolve(box.environmentId).pipe(Effect.forkScoped);
431 yield* Deferred.await(entered);
432 yield* Fiber.interrupt(resolving);
433 yield* Deferred.await(interrupted);
434​
435 yield* Ref.set(hold, false);
436 expect((yield* a.links.resolve(box.environmentId)).url).toBe(b.url);
437 expect(yield* Ref.get(requests)).toBe(2);
438 expect(yield* Ref.get(b.bearers)).toEqual([]);
439 }),
440 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
441);
442​
443it.effect("reads one stored link without asking the peer", () =>
444 Effect.scoped(
445 Effect.gen(function* () {
446 const b = yield* serveB(box);
447 const a = yield* makeA(laptop);
448 const pairing = yield* b.auth.issuePairingCredential();
449 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
450 yield* Ref.set(b.probes, 0);
451​
452 const stored = yield* a.links.get(box.environmentId);
453 expect(Option.map(stored, (link) => link.label)).toEqual(Option.some("Box"));
454 expect(Option.isNone(yield* a.links.get(laptop.environmentId))).toBe(true);
455 expect(yield* Ref.get(b.probes)).toBe(0);
456 }),
457 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
458);
459​
460it.effect("a linked peer that is renamed shows its new name", () =>
461 Effect.scoped(
462 Effect.gen(function* () {
463 const b = yield* serveB(box);
464 const a = yield* makeA(laptop);
465 const pairing = yield* b.auth.issuePairingCredential();
466 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
467​
468 yield* Ref.set(b.descriptor, descriptorOf(box.environmentId, "Box Mini"));
469 expect((yield* a.links.resolve(box.environmentId)).link.label).toBe("Box Mini");
470 const stored = yield* a.links.get(box.environmentId);
471 expect(Option.map(stored, (link) => link.label)).toEqual(Option.some("Box Mini"));
472​
473 yield* Ref.set(b.descriptor, descriptorOf(box.environmentId, "Box Studio"));
474 expect((yield* a.links.list).map((link) => link.label)).toEqual(["Box Studio"]);
475 const storedAfterList = yield* a.links.get(box.environmentId);
476 expect(Option.map(storedAfterList, (link) => link.label)).toEqual(Option.some("Box Studio"));
477 }),
478 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
479);
480​
481it.effect("tells the agent to link again once the peer revokes the link or it expires", () =>
482 Effect.scoped(
483 Effect.gen(function* () {
484 const b = yield* serveB(box);
485 const a = yield* makeA(laptop);
486 const pairing = yield* b.auth.issuePairingCredential();
487 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
488 yield* probe(a);
489​
490 const [session] = yield* linkedSessions(b);
491 yield* b.auth.revokeSession(session!.sessionId);
492 const revoked = yield* probe(a).pipe(Effect.flip);
493 expect(revoked.code).toBe("capability_denied");
494 expect(revoked.message).toContain("revoked there");
495​
496 yield* a.links.link({
497 url: b.url,
498 pairingCode: (yield* b.auth.issuePairingCredential()).credential,
499 access: "auto",
500 });
501 // A link made with a peer that later answers without the fence, as
502 // one made before the fence or a peer moved back to such a version.
503 yield* Ref.set(b.descriptor, descriptorOf("environment-box", "Box", { linkFence: false }));
504 yield* Ref.set(b.bearers, []);
505 const unfenced = yield* probe(a).pipe(Effect.flip);
506 expect(unfenced.code).toBe("capability_denied");
507 expect(unfenced.message).toContain("cannot keep a linked agent's limits");
508 expect(yield* Ref.get(b.bearers)).toEqual([]);
509 yield* Ref.set(b.descriptor, box);
510​
511 // A link stored before links were marked: its session there is not a
512 // link's, so the peer would not fence its work even though it can.
513 yield* a.sql`UPDATE peer_environment_links SET fenced = 0`;
514 // Linking again is its only way back, as for an expired link.
515 expect((yield* a.links.list).map((link) => link.status)).toEqual(["expired"]);
516 const legacy = yield* probe(a).pipe(Effect.flip);
517 expect(legacy.code).toBe("capability_denied");
518 expect(legacy.message).toContain("Link it again");
519 expect(yield* Ref.get(b.bearers)).toEqual([]);
520 yield* a.links.link({
521 url: b.url,
522 pairingCode: (yield* b.auth.issuePairingCredential()).credential,
523 access: "auto",
524 });
525 yield* probe(a);
526​
527 yield* TestClock.adjust(Duration.days(31));
528 expect((yield* a.links.list).map((link) => link.status)).toEqual(["expired"]);
529 yield* Ref.set(b.bearers, []);
530 const expired = yield* probe(a).pipe(Effect.flip);
531 expect(expired.code).toBe("capability_denied");
532 expect(expired.message).toContain("expired");
533 expect(yield* Ref.get(b.bearers)).toEqual([]);
534 }),
535 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
536);
537​
538it.effect(
539 "refuses to link itself, plain http off this machine and the tailnet, or a peer that cannot hold a linked agent to its limits",
540 () =>
541 Effect.scoped(
542 Effect.gen(function* () {
543 const b = yield* serveB(
544 descriptorOf("environment-box", "Box", { mcpModeLimitHeader: false }),
545 );
546 const a = yield* makeA(laptop);
547 const pairing = yield* b.auth.issuePairingCredential();
548 const older = yield* a.links
549 .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
550 .pipe(Effect.flip);
551 expect(older.reason).toBe("incompatible");
552 // Nor one whose link's work could reach the user's own threads there.
553 yield* Ref.set(b.descriptor, descriptorOf("environment-box", "Box", { linkFence: false }));
554 const unfenced = yield* a.links
555 .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
556 .pipe(Effect.flip);
557 expect(unfenced.reason).toBe("incompatible");
558​
559 // Plain http to a LAN address would carry the code and token in clear.
560 const lan = yield* a.links
561 .link({
562 url: "http://192.168.1.20:3773",
563 pairingCode: pairing.credential,
564 access: "auto",
565 })
566 .pipe(Effect.flip);
567 expect(lan.message).toContain("plain http");
568 const lanAlternate = yield* a.links
569 .link({
570 url: b.url,
571 alternateUrls: ["http://192.168.1.20:3773"],
572 pairingCode: pairing.credential,
573 access: "auto",
574 })
575 .pipe(Effect.flip);
576 expect(lanAlternate.message).toContain("plain http");
577​
578 yield* Ref.set(b.descriptor, laptop);
579 const self = yield* a.links
580 .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
581 .pipe(Effect.flip);
582 expect(self.reason).toBe("self");
583 // Neither attempt spent the pairing code on a session.
584 expect(yield* linkedSessions(b)).toEqual([]);
585 }),
586 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
587);
588​
589it.effect(
590 "linking a picked machine skips an address that answers as another, and never signs in there",
591 () =>
592 Effect.scoped(
593 Effect.gen(function* () {
594 const impostor = yield* serveApart(descriptorOf("environment-impostor", "Impostor"));
595 const b = yield* serveB(box);
596 const a = yield* makeA(laptop);
597 const pairing = yield* b.auth.issuePairingCredential();
598 const linked = yield* a.links.link({
599 url: impostor.url,
600 alternateUrls: [b.url],
601 pairingCode: pairing.credential,
602 access: "auto",
603 expectedEnvironmentId: box.environmentId,
604 });
605 expect(linked).toMatchObject({ environmentId: box.environmentId, urls: [b.url] });
606 yield* probe(a);
607 expect(yield* linkedSessions(impostor)).toEqual([]);
608 expect(yield* Ref.get(impostor.bearers)).toEqual([]);
609 expect((yield* linkedSessions(b)).length).toBe(1);
610 }),
611 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
612);
613​
614it.effect("linking a picked machine that answers nowhere names it and links nothing", () =>
615 Effect.scoped(
616 Effect.gen(function* () {
617 const impostor = yield* serveApart(descriptorOf("environment-impostor", "Impostor"));
618 const a = yield* makeA(laptop);
619 const failed = yield* a.links
620 .link({
621 url: impostor.url,
622 alternateUrls: ["http://192.168.1.20:3773"],
623 pairingCode: "unused",
624 access: "auto",
625 expectedEnvironmentId: box.environmentId,
626 expectedLabel: "Box",
627 })
628 .pipe(Effect.flip);
629 expect(failed.reason).toBe("unreachable");
630 expect(failed.message).toBe(
631 `This environment could not reach Box at ${impostor.url}, http://192.168.1.20:3773.`,
632 );
633 expect(yield* a.links.list).toEqual([]);
634 expect(yield* linkedSessions(impostor)).toEqual([]);
635​
636 // Every address refused: the message says why.
637 const refused = yield* a.links
638 .link({
639 url: "http://192.168.1.20:3773",
640 pairingCode: "unused",
641 access: "auto",
642 expectedEnvironmentId: box.environmentId,
643 expectedLabel: "Box",
644 })
645 .pipe(Effect.flip);
646 expect(refused.message).toContain("could not reach Box");
647 expect(refused.message).toContain("plain http");
648 }),
649 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
650);
651​
652/** An https listener whose certificate this machine does not trust. */
653const 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​
672it.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​
700it("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});