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

PeerLinks.test.ts

947 lines38.5 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 DateTime from "effect/DateTime";
10import * as Deferred from "effect/Deferred";
11import * as Duration from "effect/Duration";
12import * as Effect from "effect/Effect";
13import * as Fiber from "effect/Fiber";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16import * as Queue from "effect/Queue";
17import * as Ref from "effect/Ref";
18import * as Schema from "effect/Schema";
19import * as HttpRouter from "effect/http/HttpRouter";
20import * as SqlClient from "effect/sql/SqlClient";
21import * as TestClock from "effect/testing/TestClock";
22import { Tool, Toolkit } from "effect/ai";
23import {
24 FetchHttpClient,
25 HttpClient,
26 HttpServer,
27 HttpServerRequest,
28 HttpServerResponse,
29} from "effect/http";
30​
31import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
32import * as McpHttpServer from "../mcp/McpHttpServer.ts";
33import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
34import * as McpToolAccess from "../mcp/McpToolAccess.ts";
35import * as PeerLinks from "./PeerLinks.ts";
36import * as ServerSettings from "../serverSettings.ts";
37import {
38 descriptorOf,
39 layerLinkingEnvironment,
40 servePeer,
41 type ServedPeer,
42} from "./PeerLinks.testkit.ts";
43import * as PeerMcpClient from "./PeerMcpClient.ts";
44​
45import { layerReaderDatabase, traceSqlRouting } from "../persistence/testkit/SqliteRouting.ts";
46​
47/** What B's probe saw: the calling client and the modes it may start work with. */
48const Probe = Schema.Struct({ caller: Schema.String, modes: Schema.String });
49​
50const ProbeToolkit = Toolkit.make(
51 Tool.make("probe", {
52 description: "Reports the calling client and the modes it may start work with.",
53 success: Probe,
54 failure: OrchestratorMcpFailure,
55 failureMode: "return",
56 dependencies: [McpInvocationContext.McpInvocationContext],
57 }),
58 Tool.make("refuse", {
59 description: "Always refuses.",
60 success: Probe,
61 failure: OrchestratorMcpFailure,
62 failureMode: "return",
63 }),
64);
65​
66const probeHandlers = McpToolAccess.toLayer(ProbeToolkit, {
67 probe: McpToolAccess.reads(() =>
68 McpInvocationContext.McpInvocationContext.pipe(
69 Effect.map((scope) => {
70 const modes = McpInvocationContext.clientModeCeiling(scope.client);
71 return {
72 caller: scope.client?.label ?? "none",
73 modes: `${modes.runtimeMode}/${modes.interactionMode}`,
74 };
75 }),
76 ),
77 ),
78 refuse: McpToolAccess.reads(() =>
79 Effect.fail(
80 new OrchestratorMcpFailure({ code: "thread_not_found", message: "No such thread." }),
81 ),
82 ),
83});
84​
85const serveB = (descriptor: ExecutionEnvironmentDescriptor) =>
86 servePeer(descriptor, McpHttpServer.toolkitRegistration(ProbeToolkit, probeHandlers));
87​
88/** Environment A, which links to B. */
89const makeA = (
90 descriptor: ExecutionEnvironmentDescriptor,
91 secrets?: typeof ServerSecretStore.layer,
92) =>
93 layerLinkingEnvironment(descriptor, secrets).pipe(
94 Layer.build,
95 Effect.map((context) => ({
96 links: Context.get(context, PeerLinks.PeerLinks),
97 peer: Context.get(context, PeerMcpClient.PeerMcpClient),
98 sql: Context.get(context, SqlClient.SqlClient),
99 settings: Context.get(context, ServerSettings.ServerSettingsService),
100 })),
101 );
102​
103const laptop = descriptorOf("environment-laptop", "Laptop");
104const box = descriptorOf("environment-box", "Box");
105const probe = (
106 a: Effect.Success<ReturnType<typeof makeA>>,
107 limits: PeerMcpClient.PeerCallLimits = { runtimeMode: "full-access", interactionMode: "default" },
108 tool = "probe",
109) =>
110 a.peer.call({
111 environmentId: box.environmentId,
112 tool,
113 arguments: {},
114 limits,
115 success: Probe,
116 });
117​
118const linkedSessions = (b: ServedPeer) => b.linkedSessions;
119​
120/** Another environment on a socket of its own, answering as `descriptor`. */
121const serveApart = (descriptor: ExecutionEnvironmentDescriptor) =>
122 Layer.build(Layer.fresh(NodeHttpServer.layerTest)).pipe(
123 Effect.flatMap((server) => serveB(descriptor).pipe(Effect.provideContext(server))),
124 );
125​
126it.effect("routes peer reads to readers and sees uncommitted link updates", () =>
127 Effect.gen(function* () {
128 const context = yield* layerLinkingEnvironment(
129 laptop,
130 ServerSecretStore.layer,
131 layerReaderDatabase,
132 ).pipe(Layer.build);
133 const links = Context.get(context, PeerLinks.PeerLinks);
134 const sql = Context.get(context, SqlClient.SqlClient);
135 yield* sql`
136 INSERT INTO peer_environment_links (
137 environment_id, secret_name, label, urls_json, access, linked_at, expires_at, fenced
138 ) VALUES (
139 ${box.environmentId}, 'test-secret', 'Box', '[]', 'auto',
140 '2026-01-01T00:00:00.000Z', '2026-01-02T00:00:00.000Z', 1
141 )
142 `;
143 const { queries, trace } = traceSqlRouting();
144 yield* links.list.pipe(trace);
145 expect(Option.getOrThrow(yield* links.get(box.environmentId).pipe(trace)).label).toBe("Box");
146 const reads = queries.filter(({ query }) =>
147 query.includes("SELECT * FROM peer_environment_links"),
148 );
149 expect(reads).toHaveLength(2);
150 expect(reads.map((row) => row.connection)).toEqual(["reader", "reader"]);
151 yield* sql.withTransaction(
152 Effect.gen(function* () {
153 yield* sql`UPDATE peer_environment_links SET label = 'Uncommitted box'`;
154 expect(Option.getOrThrow(yield* links.get(box.environmentId)).label).toBe(
155 "Uncommitted box",
156 );
157 expect((yield* links.list)[0]?.label).toBe("Uncommitted box");
158 }),
159 );
160 expect(yield* links.unlink(box.environmentId)).toEqual({ removed: true, endedThere: false });
161 expect(yield* links.list).toEqual([]);
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 access: "auto",
179 purpose: "peer-link",
180 });
181 const linked = yield* a.links.link({
182 url: b.url,
183 pairingCode: pairing.credential,
184 access: "auto",
185 });
186 expect(linked).toMatchObject({
187 environmentId: box.environmentId,
188 label: "Box",
189 urls: [b.url],
190 access: "auto",
191 });
192 // B lists the link under A's name, where it can be revoked.
193 expect((yield* linkedSessions(b)).map((session) => session.client.label)).toEqual([
194 "T3 Code · Laptop",
195 ]);
196 expect(
197 (yield* a.links.list).map(({ environmentId, status }) => [environmentId, status]),
198 ).toEqual([[box.environmentId, "reachable"]]);
199​
200 // The caller's limits narrow the link's access; they never widen it.
201 expect(
202 yield* probe(a, { runtimeMode: "approval-required", interactionMode: "plan" }),
203 ).toEqual({ caller: "T3 Code · Laptop", modes: "approval-required/plan" });
204 expect(yield* probe(a)).toEqual({ caller: "T3 Code · Laptop", modes: "auto/default" });
205​
206 // A refusal keeps the peer's reason.
207 const notFound = yield* probe(a, undefined, "refuse").pipe(Effect.flip);
208 expect(notFound).toMatchObject({ code: "thread_not_found", message: "No such thread." });
209​
210 // Unlinking ends the session on B too, instead of leaving a live credential behind.
211 expect(yield* a.links.unlink(box.environmentId)).toEqual({ removed: true, endedThere: true });
212 expect(yield* linkedSessions(b)).toEqual([]);
213​
214 // An address that now answers as another environment never receives the token.
215 const other = yield* serveApart(descriptorOf("environment-other", "Other"));
216 const relink = yield* b.auth.issuePairingCredential({ access: "auto", purpose: "peer-link" });
217 yield* a.links.link({ url: b.url, pairingCode: relink.credential, access: "auto" });
218 yield* a.sql`UPDATE peer_environment_links SET urls_json = ${JSON.stringify([other.url])}`;
219 expect(yield* a.links.unlink(box.environmentId)).toEqual({
220 removed: true,
221 endedThere: false,
222 });
223 }),
224 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
225);
226​
227it.effect(
228 "each machine's Linked environments beta gates links, and a link waits while it is off",
229 () =>
230 Effect.scoped(
231 Effect.gen(function* () {
232 const b = yield* serveB(box);
233 const a = yield* makeA(laptop);
234 const pairing = yield* b.auth.issuePairingCredential();
235 const link = a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
236​
237 yield* a.settings.updateSettings({ linkedEnvironmentsEnabled: false });
238 expect(yield* link.pipe(Effect.flip)).toMatchObject({
239 reason: "disabled",
240 message: PeerLinks.LINKED_ENVIRONMENTS_OFF,
241 });
242 expect(yield* Ref.get(b.bearers)).toEqual([]);
243​
244 yield* a.settings.updateSettings({ linkedEnvironmentsEnabled: true });
245 yield* b.settings.updateSettings({ linkedEnvironmentsEnabled: false });
246 const refusedThere = yield* link.pipe(Effect.flip);
247 expect(refusedThere.reason).toBe("pairing_rejected");
248 expect(refusedThere.message).toContain("Linked environments is off on that machine");
249 expect(yield* linkedSessions(b)).toEqual([]);
250​
251 yield* b.settings.updateSettings({ linkedEnvironmentsEnabled: true });
252 yield* link;
253 yield* b.settings.updateSettings({ linkedEnvironmentsEnabled: false });
254 // Not final, so a task already running there picks up again once it is back on.
255 const waiting = yield* probe(a).pipe(Effect.flip);
256 expect(waiting.code).toBe("orchestration_error");
257 expect(waiting.message).toContain("has Linked environments turned off");
258 yield* b.settings.updateSettings({ linkedEnvironmentsEnabled: true });
259 expect(yield* probe(a)).toEqual({ caller: "T3 Code · Laptop", modes: "auto/default" });
260 }),
261 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
262);
263​
264it.effect("a link whose row cannot be stored keeps none of its token", () =>
265 Effect.scoped(
266 Effect.gen(function* () {
267 const b = yield* serveB(box);
268 const held = yield* Ref.make<ReadonlySet<string>>(new Set());
269 const noted = Layer.effect(
270 ServerSecretStore.ServerSecretStore,
271 Effect.map(ServerSecretStore.make, (store) =>
272 ServerSecretStore.ServerSecretStore.of({
273 ...store,
274 set: (name, value) =>
275 store
276 .set(name, value)
277 .pipe(Effect.andThen(Ref.update(held, (names) => new Set([...names, name])))),
278 remove: (name) =>
279 store
280 .remove(name)
281 .pipe(
282 Effect.andThen(
283 Ref.update(held, (names) => new Set([...names].filter((at) => at !== name))),
284 ),
285 ),
286 }),
287 ),
288 );
289 const a = yield* makeA(laptop, noted);
290 yield* a.sql`
291 CREATE TRIGGER refuse_link BEFORE INSERT ON peer_environment_links
292 BEGIN SELECT RAISE(ABORT, 'database or disk is full'); END
293 `;
294 const pairing = yield* b.auth.issuePairingCredential();
295 const failed = yield* a.links
296 .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
297 .pipe(Effect.flip);
298 expect(failed.reason).toBe("storage");
299 expect(yield* Ref.get(held)).toEqual(new Set());
300 }),
301 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
302);
303​
304it.effect("two links racing to one peer leave the stored access matching the token", () =>
305 Effect.scoped(
306 Effect.gen(function* () {
307 const b = yield* serveB(box);
308 const a = yield* makeA(laptop);
309 const [first, second] = yield* Effect.all(
310 [b.auth.issuePairingCredential(), b.auth.issuePairingCredential()],
311 { concurrency: 2 },
312 );
313 yield* Effect.all(
314 [
315 a.links.link({ url: b.url, pairingCode: first.credential, access: "read-only" }),
316 a.links.link({ url: b.url, pairingCode: second.credential, access: "full-access" }),
317 ],
318 { concurrency: 2 },
319 );
320 const [stored] = yield* a.links.list;
321 // The token sent is the one issued with the access the row records.
322 const { modes } = yield* probe(a);
323 expect(modes).toBe(
324 stored!.access === "read-only" ? "approval-required/default" : "full-access/default",
325 );
326 }),
327 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
328);
329​
330/** A bare HTTP server on a socket of its own, answering with `handle`. */
331const serveRaw = <E, R>(
332 handle: (
333 request: HttpServerRequest.HttpServerRequest,
334 ) => Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>,
335) =>
336 Layer.build(Layer.fresh(NodeHttpServer.layerTest)).pipe(
337 Effect.flatMap((server) =>
338 Effect.gen(function* () {
339 yield* HttpServer.serve(Effect.flatMap(HttpServerRequest.HttpServerRequest, handle)).pipe(
340 Layer.build,
341 );
342 const address = (yield* HttpServer.HttpServer).address;
343 if (address._tag === "UnixPathAddress") return yield* Effect.die("expected a TCP address");
344 return `http://127.0.0.1:${address.port}`;
345 }).pipe(Effect.provideContext(server)),
346 ),
347 );
348​
349it.effect("never follows a peer's redirect with the pairing code", () =>
350 Effect.scoped(
351 Effect.gen(function* () {
352 const b = yield* serveB(box);
353 const received = yield* Ref.make<ReadonlyArray<string>>([]);
354 const elsewhere = yield* serveRaw((request) =>
355 Ref.update(received, (seen) => [...seen, `${request.method} ${request.url}`]).pipe(
356 Effect.as(HttpServerResponse.empty({ status: 404 })),
357 ),
358 );
359 // Answers as B, then sends every linking request on to another address.
360 const front = yield* serveRaw((request) =>
361 request.url.startsWith("/.well-known/t3/environment")
362 ? HttpClient.get(`${b.url}${request.url}`).pipe(
363 Effect.flatMap((response) => response.text),
364 Effect.map((body) =>
365 HttpServerResponse.text(body, { contentType: "application/json" }),
366 ),
367 Effect.provide(FetchHttpClient.layer),
368 Effect.orDie,
369 )
370 : Effect.succeed(
371 HttpServerResponse.empty({
372 status: 307,
373 headers: { location: `${elsewhere}${request.url}` },
374 }),
375 ),
376 );
377 const a = yield* makeA(laptop);
378 const pairing = yield* b.auth.issuePairingCredential();
379 yield* a.links
380 .link({ url: front, pairingCode: pairing.credential, access: "auto" })
381 .pipe(Effect.flip);
382 expect(yield* Ref.get(received)).toEqual([]);
383 expect(yield* a.links.list).toEqual([]);
384 }),
385 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
386);
387​
388it.effect("never sends a link's token to an address that stops answering as that peer", () =>
389 Effect.scoped(
390 Effect.gen(function* () {
391 const b = yield* serveB(box);
392 const a = yield* makeA(laptop);
393 const pairing = yield* b.auth.issuePairingCredential();
394 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
395 yield* probe(a);
396 expect((yield* Ref.get(b.bearers)).length).toBeGreaterThan(0);
397​
398 // The address now answers as another environment, as a reused LAN address would.
399 yield* Ref.set(b.descriptor, descriptorOf("environment-impostor", "Impostor"));
400 yield* Ref.set(b.bearers, []);
401 const failed = yield* probe(a).pipe(Effect.flip);
402 expect(failed.message).toContain("Box did not answer");
403 expect(yield* Ref.get(b.bearers)).toEqual([]);
404 expect((yield* a.links.list).map((link) => link.status)).toEqual(["unreachable"]);
405 }),
406 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
407);
408​
409it.effect("lists a peer asleep at every address as unreachable within one probe budget", () =>
410 Effect.scoped(
411 Effect.gen(function* () {
412 const b = yield* serveB(box);
413 // Another address of the same machine, asleep too.
414 const wake = yield* Deferred.make<void>();
415 const elsewhere = yield* serveRaw(() =>
416 Deferred.await(wake).pipe(Effect.as(HttpServerResponse.empty({ status: 503 }))),
417 );
418 yield* Effect.addFinalizer(() => Deferred.succeed(wake, undefined));
419 const a = yield* makeA(laptop);
420 const pairing = yield* b.auth.issuePairingCredential();
421 yield* a.links.link({
422 url: b.url,
423 alternateUrls: [elsewhere],
424 pairingCode: pairing.credential,
425 access: "auto",
426 });
427​
428 yield* Ref.set(b.asleep, true);
429 const listing = yield* a.links.list.pipe(Effect.forkScoped);
430 yield* Queue.take(b.unanswered);
431 yield* TestClock.adjust(Duration.seconds(3));
432 const listed = yield* Fiber.join(listing);
433 expect(listed.map((link) => link.status)).toEqual(["unreachable"]);
434 }),
435 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
436);
437​
438it.effect("lists a peer as reachable at another address while its first one sleeps", () =>
439 Effect.scoped(
440 Effect.gen(function* () {
441 const b = yield* serveB(box);
442 const described = yield* HttpClient.get(`${b.url}/.well-known/t3/environment`).pipe(
443 Effect.flatMap((response) => response.text),
444 Effect.provide(FetchHttpClient.layer),
445 );
446 // Another address of the same machine that answers.
447 const elsewhere = yield* serveRaw(() =>
448 Effect.succeed(HttpServerResponse.text(described, { contentType: "application/json" })),
449 );
450 const a = yield* makeA(laptop);
451 const pairing = yield* b.auth.issuePairingCredential();
452 yield* a.links.link({
453 url: b.url,
454 alternateUrls: [elsewhere],
455 pairingCode: pairing.credential,
456 access: "auto",
457 });
458​
459 yield* Ref.set(b.asleep, true);
460 expect((yield* a.links.list).map((link) => link.status)).toEqual(["reachable"]);
461 }),
462 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
463);
464​
465it.effect("resolves a link at its answering address without waiting out a sleeping first", () =>
466 Effect.scoped(
467 Effect.gen(function* () {
468 const b = yield* serveB(box);
469 const described = yield* HttpClient.get(`${b.url}/.well-known/t3/environment`).pipe(
470 Effect.flatMap((response) => response.text),
471 Effect.provide(FetchHttpClient.layer),
472 );
473 const elsewhere = yield* serveRaw(() =>
474 Effect.succeed(HttpServerResponse.text(described, { contentType: "application/json" })),
475 );
476 const a = yield* makeA(laptop);
477 const pairing = yield* b.auth.issuePairingCredential();
478 yield* a.links.link({
479 url: b.url,
480 alternateUrls: [elsewhere],
481 pairingCode: pairing.credential,
482 access: "auto",
483 });
484​
485 yield* Ref.set(b.asleep, true);
486 const first = yield* a.links.resolve(box.environmentId).pipe(Effect.forkScoped);
487 yield* Queue.take(b.unanswered);
488 yield* TestClock.adjust(Duration.seconds(3));
489 expect((yield* Fiber.join(first)).url).toBe(elsewhere);
490​
491 // The clock no longer moves: a resolve that probes the sleeping address first never returns.
492 expect((yield* a.links.resolve(box.environmentId)).url).toBe(elsewhere);
493 }),
494 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
495);
496​
497it.effect("cancelling a descriptor probe aborts its request and leaves later resolves fresh", () =>
498 Effect.scoped(
499 Effect.gen(function* () {
500 const hold = yield* Ref.make(false);
501 const requests = yield* Ref.make(0);
502 const entered = yield* Deferred.make<void>();
503 const interrupted = yield* Deferred.make<void>();
504 const holdDescriptor = HttpRouter.middleware(
505 (httpEffect) =>
506 Effect.gen(function* () {
507 const request = yield* HttpServerRequest.HttpServerRequest;
508 if (request.url.startsWith("/.well-known/t3/environment")) {
509 yield* Ref.update(requests, (count) => count + 1);
510 if (yield* Ref.get(hold)) {
511 return yield* Deferred.succeed(entered, undefined).pipe(
512 Effect.andThen(Effect.never),
513 Effect.onInterrupt(() =>
514 Deferred.succeed(interrupted, undefined).pipe(Effect.asVoid),
515 ),
516 Effect.interruptible,
517 );
518 }
519 }
520 return yield* httpEffect;
521 }),
522 { global: true },
523 );
524 const b = yield* servePeer(
525 box,
526 Layer.merge(McpHttpServer.toolkitRegistration(ProbeToolkit, probeHandlers), holdDescriptor),
527 );
528 const a = yield* makeA(laptop);
529 const pairing = yield* b.auth.issuePairingCredential();
530 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
531 yield* Ref.set(b.bearers, []);
532 yield* Ref.set(requests, 0);
533 yield* Ref.set(hold, true);
534​
535 const resolving = yield* a.links.resolve(box.environmentId).pipe(Effect.forkScoped);
536 yield* Deferred.await(entered);
537 yield* Fiber.interrupt(resolving);
538 yield* Deferred.await(interrupted);
539​
540 yield* Ref.set(hold, false);
541 expect((yield* a.links.resolve(box.environmentId)).url).toBe(b.url);
542 expect(yield* Ref.get(requests)).toBe(2);
543 expect(yield* Ref.get(b.bearers)).toEqual([]);
544 }),
545 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
546);
547​
548it.live("one dropped descriptor request does not list a live peer as unreachable", () =>
549 Effect.scoped(
550 Effect.gen(function* () {
551 const dropNext = yield* Ref.make(false);
552 const dropOnce = HttpRouter.middleware(
553 (httpEffect) =>
554 Effect.gen(function* () {
555 const request = yield* HttpServerRequest.HttpServerRequest;
556 if (
557 request.url.startsWith("/.well-known/t3/environment") &&
558 (yield* Ref.getAndSet(dropNext, false))
559 ) {
560 return HttpServerResponse.empty({ status: 503 });
561 }
562 return yield* httpEffect;
563 }),
564 { global: true },
565 );
566 const b = yield* servePeer(
567 box,
568 Layer.merge(McpHttpServer.toolkitRegistration(ProbeToolkit, probeHandlers), dropOnce),
569 );
570 const a = yield* makeA(laptop);
571 const pairing = yield* b.auth.issuePairingCredential();
572 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
573​
574 yield* Ref.set(dropNext, true);
575 expect((yield* a.links.list).map((link) => link.status)).toEqual(["reachable"]);
576 }),
577 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
578);
579​
580it.effect("reads one stored link without asking the peer", () =>
581 Effect.scoped(
582 Effect.gen(function* () {
583 const b = yield* serveB(box);
584 const a = yield* makeA(laptop);
585 const pairing = yield* b.auth.issuePairingCredential();
586 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
587 yield* Ref.set(b.probes, 0);
588​
589 const stored = yield* a.links.get(box.environmentId);
590 expect(Option.map(stored, (link) => link.label)).toEqual(Option.some("Box"));
591 expect(Option.isNone(yield* a.links.get(laptop.environmentId))).toBe(true);
592 expect(yield* a.links.names).toEqual([{ environmentId: box.environmentId, label: "Box" }]);
593 expect(yield* Ref.get(b.probes)).toBe(0);
594​
595 // An older answer that lands after a newer one never moves the expiry back.
596 const expiresAt = Option.getOrThrow(stored).expiresAt;
597 const later = DateTime.add(expiresAt, { days: 20 });
598 yield* a.links.recordExpiry(box.environmentId, later);
599 yield* a.links.recordExpiry(box.environmentId, DateTime.add(expiresAt, { days: 10 }));
600 expect(
601 Option.map(yield* a.links.get(box.environmentId), (link) =>
602 DateTime.formatIso(link.expiresAt),
603 ),
604 ).toEqual(Option.some(DateTime.formatIso(later)));
605 }),
606 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
607);
608​
609it.effect("a linked peer that is renamed shows its new name", () =>
610 Effect.scoped(
611 Effect.gen(function* () {
612 const b = yield* serveB(box);
613 const a = yield* makeA(laptop);
614 const pairing = yield* b.auth.issuePairingCredential();
615 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
616​
617 yield* Ref.set(b.descriptor, descriptorOf(box.environmentId, "Box Mini"));
618 expect((yield* a.links.resolve(box.environmentId)).link.label).toBe("Box Mini");
619 const stored = yield* a.links.get(box.environmentId);
620 expect(Option.map(stored, (link) => link.label)).toEqual(Option.some("Box Mini"));
621​
622 yield* Ref.set(b.descriptor, descriptorOf(box.environmentId, "Box Studio"));
623 expect((yield* a.links.list).map((link) => link.label)).toEqual(["Box Studio"]);
624 const storedAfterList = yield* a.links.get(box.environmentId);
625 expect(Option.map(storedAfterList, (link) => link.label)).toEqual(Option.some("Box Studio"));
626 }),
627 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
628);
629​
630it.effect(
631 "a link forgotten while it resolves says it is not linked, not that it lost its credential",
632 () =>
633 Effect.scoped(
634 Effect.gen(function* () {
635 const b = yield* serveB(box);
636 const beforeGet = yield* Ref.make<Effect.Effect<void>>(Effect.void);
637 const racing = Layer.effect(
638 ServerSecretStore.ServerSecretStore,
639 Effect.map(ServerSecretStore.make, (store) =>
640 ServerSecretStore.ServerSecretStore.of({
641 ...store,
642 get: (name) =>
643 Ref.getAndSet(beforeGet, Effect.void).pipe(
644 Effect.flatten,
645 Effect.andThen(store.get(name)),
646 ),
647 }),
648 ),
649 );
650 const a = yield* makeA(laptop, racing);
651 const pairing = yield* b.auth.issuePairingCredential();
652 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
653​
654 yield* Ref.set(beforeGet, Effect.orDie(Effect.asVoid(a.links.unlink(box.environmentId))));
655 const forgotten = yield* probe(a).pipe(Effect.flip);
656 expect(forgotten.message).toContain("not linked to");
657 }),
658 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
659);
660​
661it.effect("tells the agent to link again once the peer revokes the link or it expires", () =>
662 Effect.scoped(
663 Effect.gen(function* () {
664 const b = yield* serveB(box);
665 const a = yield* makeA(laptop);
666 const pairing = yield* b.auth.issuePairingCredential();
667 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
668 yield* probe(a);
669​
670 const [session] = yield* linkedSessions(b);
671 yield* b.auth.revokeSession(session!.sessionId);
672 const revoked = yield* probe(a).pipe(Effect.flip);
673 expect(revoked.code).toBe("capability_denied");
674 expect(revoked.message).toContain("revoked there");
675​
676 yield* a.links.link({
677 url: b.url,
678 pairingCode: (yield* b.auth.issuePairingCredential()).credential,
679 access: "auto",
680 });
681 // A link made with a peer that later answers without the fence, as
682 // one made before the fence or a peer moved back to such a version.
683 yield* Ref.set(b.descriptor, descriptorOf("environment-box", "Box", { linkFence: false }));
684 yield* Ref.set(b.bearers, []);
685 const unfenced = yield* probe(a).pipe(Effect.flip);
686 expect(unfenced.code).toBe("capability_denied");
687 expect(unfenced.message).toContain("cannot keep a linked agent's limits");
688 expect(yield* Ref.get(b.bearers)).toEqual([]);
689 yield* Ref.set(b.descriptor, box);
690​
691 // A link stored before links were marked: its session there is not a
692 // link's, so the peer would not fence its work even though it can.
693 yield* a.sql`UPDATE peer_environment_links SET fenced = 0`;
694 // Linking again is its only way back, as for an expired link.
695 expect((yield* a.links.list).map((link) => link.status)).toEqual(["expired"]);
696 const legacy = yield* probe(a).pipe(Effect.flip);
697 expect(legacy.code).toBe("capability_denied");
698 expect(legacy.message).toContain("Link it again");
699 expect(yield* Ref.get(b.bearers)).toEqual([]);
700 yield* a.links.link({
701 url: b.url,
702 pairingCode: (yield* b.auth.issuePairingCredential()).credential,
703 access: "auto",
704 });
705 yield* probe(a);
706​
707 yield* TestClock.adjust(Duration.days(31));
708 expect((yield* a.links.list).map((link) => link.status)).toEqual(["expired"]);
709 expect(yield* a.links.names).toEqual([]);
710 yield* Ref.set(b.bearers, []);
711 const expired = yield* probe(a).pipe(Effect.flip);
712 expect(expired.code).toBe("capability_denied");
713 expect(expired.message).toContain("expired");
714 expect(yield* Ref.get(b.bearers)).toEqual([]);
715 }),
716 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
717);
718​
719it.effect(
720 "refuses to link itself, plain http off this machine and the tailnet, or a peer that cannot hold a linked agent to its limits",
721 () =>
722 Effect.scoped(
723 Effect.gen(function* () {
724 const b = yield* serveB(
725 descriptorOf("environment-box", "Box", { mcpModeLimitHeader: false }),
726 );
727 const a = yield* makeA(laptop);
728 const pairing = yield* b.auth.issuePairingCredential();
729 const older = yield* a.links
730 .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
731 .pipe(Effect.flip);
732 expect(older.reason).toBe("incompatible");
733 // Nor one whose link's work could reach the user's own threads there.
734 yield* Ref.set(b.descriptor, descriptorOf("environment-box", "Box", { linkFence: false }));
735 const unfenced = yield* a.links
736 .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
737 .pipe(Effect.flip);
738 expect(unfenced.reason).toBe("incompatible");
739​
740 // Plain http to a LAN address would carry the code and token in clear.
741 const lan = yield* a.links
742 .link({
743 url: "http://192.168.1.20:3773",
744 pairingCode: pairing.credential,
745 access: "auto",
746 })
747 .pipe(Effect.flip);
748 expect(lan.message).toContain("plain http");
749 const lanAlternate = yield* a.links
750 .link({
751 url: b.url,
752 alternateUrls: ["http://192.168.1.20:3773"],
753 pairingCode: pairing.credential,
754 access: "auto",
755 })
756 .pipe(Effect.flip);
757 expect(lanAlternate.message).toContain("plain http");
758​
759 yield* Ref.set(b.descriptor, laptop);
760 const self = yield* a.links
761 .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
762 .pipe(Effect.flip);
763 expect(self.reason).toBe("self");
764 // Neither attempt spent the pairing code on a session.
765 expect(yield* linkedSessions(b)).toEqual([]);
766 }),
767 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
768);
769​
770it.effect(
771 "linking a picked machine skips an address that answers as another, and never signs in there",
772 () =>
773 Effect.scoped(
774 Effect.gen(function* () {
775 const impostor = yield* serveApart(descriptorOf("environment-impostor", "Impostor"));
776 const b = yield* serveB(box);
777 const a = yield* makeA(laptop);
778 const pairing = yield* b.auth.issuePairingCredential();
779 const linked = yield* a.links.link({
780 url: impostor.url,
781 alternateUrls: [b.url],
782 pairingCode: pairing.credential,
783 access: "auto",
784 expectedEnvironmentId: box.environmentId,
785 });
786 expect(linked).toMatchObject({ environmentId: box.environmentId, urls: [b.url] });
787 // A picked machine is never linked at this machine's own loopback.
788 const own = yield* a.links
789 .link({
790 url: b.url.replace("127.0.0.1", "localhost"),
791 pairingCode: pairing.credential,
792 access: "auto",
793 expectedEnvironmentId: box.environmentId,
794 })
795 .pipe(Effect.flip);
796 expect(own.message).toContain("is this machine");
797 yield* probe(a);
798 expect(yield* linkedSessions(impostor)).toEqual([]);
799 expect(yield* Ref.get(impostor.bearers)).toEqual([]);
800 expect((yield* linkedSessions(b)).length).toBe(1);
801​
802 // An address alone that answers as the linked box never takes over its link.
803 yield* Ref.set(impostor.descriptor, box);
804 const second = yield* impostor.auth.issuePairingCredential();
805 const taken = yield* a.links
806 .link({ url: impostor.url, pairingCode: second.credential, access: "auto" })
807 .pipe(Effect.flip);
808 expect(taken.message).toContain("already linked");
809 expect(yield* linkedSessions(impostor)).toEqual([]);
810 expect(Option.getOrUndefined(yield* a.links.get(box.environmentId))?.urls).toEqual([b.url]);
811 // The address the link already has still renews it.
812 const renewal = yield* b.auth.issuePairingCredential();
813 expect(
814 yield* a.links.link({ url: b.url, pairingCode: renewal.credential, access: "auto" }),
815 ).toMatchObject({ urls: [b.url] });
816 }),
817 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
818);
819​
820it.effect("linking a picked machine that answers nowhere names it and links nothing", () =>
821 Effect.scoped(
822 Effect.gen(function* () {
823 const impostor = yield* serveApart(descriptorOf("environment-impostor", "Impostor"));
824 const a = yield* makeA(laptop);
825 const failed = yield* a.links
826 .link({
827 url: impostor.url,
828 alternateUrls: ["http://192.168.1.20:3773"],
829 pairingCode: "unused",
830 access: "auto",
831 expectedEnvironmentId: box.environmentId,
832 expectedLabel: "Box",
833 })
834 .pipe(Effect.flip);
835 expect(failed.reason).toBe("unreachable");
836 expect(failed.answeredAs).toBe("Impostor");
837 expect(failed.message).toBe(
838 `This environment could not reach Box: ${new URL(impostor.url).origin} answered as another environment, Impostor. http://192.168.1.20:3773 is plain http, which would send the link's credentials unencrypted. Use its https address, or its Tailscale address.`,
839 );
840 expect(yield* a.links.list).toEqual([]);
841 expect(yield* linkedSessions(impostor)).toEqual([]);
842​
843 // Every address refused: the message says why.
844 const refused = yield* a.links
845 .link({
846 url: "http://192.168.1.20:3773",
847 pairingCode: "unused",
848 access: "auto",
849 expectedEnvironmentId: box.environmentId,
850 expectedLabel: "Box",
851 })
852 .pipe(Effect.flip);
853 expect(refused.message).toContain("could not reach Box");
854 expect(refused.message).toContain("plain http");
855 }),
856 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
857);
858​
859it.live("linking an address with nothing listening says so, unlike one that is not T3 Code", () =>
860 Effect.scoped(
861 Effect.gen(function* () {
862 const closed = yield* Effect.scoped(
863 serveRaw(() => Effect.succeed(HttpServerResponse.empty({ status: 404 }))),
864 );
865 const notT3 = yield* serveRaw(() =>
866 Effect.succeed(
867 HttpServerResponse.text("<h1>Not Found</h1>", { status: 404, contentType: "text/html" }),
868 ),
869 );
870 const a = yield* makeA(laptop);
871 const linking = (url: string) =>
872 a.links.link({ url, pairingCode: "unused", access: "auto" }).pipe(Effect.flip);
873 expect((yield* linking(closed)).message).toBe(`${closed} did not answer (ECONNREFUSED).`);
874 expect((yield* linking(notT3)).message).toBe(
875 `${notT3} answered, but not as a T3 Code environment this version understands.`,
876 );
877 expect(yield* a.links.list).toEqual([]);
878 }),
879 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
880);
881​
882/** An https listener whose certificate this machine does not trust. */
883const serveUntrusted = Layer.build(
884 Layer.fresh(
885 NodeHttpServer.layerServer(
886 () =>
887 NodeHttps.createServer({
888 key: NodeFS.readFileSync(new URL("./fixtures/localhost-key.pem", import.meta.url)),
889 cert: NodeFS.readFileSync(new URL("./fixtures/localhost-cert.pem", import.meta.url)),
890 }),
891 { port: 0, host: "127.0.0.1" },
892 ),
893 ),
894).pipe(
895 Effect.map((server) => {
896 const address = Context.get(server, HttpServer.HttpServer).address;
897 if (address._tag === "UnixPathAddress") throw new Error("expected a TCP address");
898 return `https://127.0.0.1:${address.port}`;
899 }),
900);
901​
902it.effect("names an untrusted certificate instead of calling the peer something else", () =>
903 Effect.scoped(
904 Effect.gen(function* () {
905 const untrusted = yield* serveUntrusted;
906 const a = yield* makeA(laptop);
907 const failed = yield* a.links
908 .link({ url: untrusted, pairingCode: "unused", access: "auto" })
909 .pipe(Effect.flip);
910 expect(failed.reason).toBe("unreachable");
911 expect(failed.message).toContain("certificate this machine rejected");
912 expect(failed.message).toContain("DEPTH_ZERO_SELF_SIGNED_CERT");
913 expect(yield* a.links.list).toEqual([]);
914​
915 // A stored link tries its next address past an untrusted one.
916 const b = yield* serveB(box);
917 const pairing = yield* b.auth.issuePairingCredential();
918 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
919 yield* a.sql`
920 UPDATE peer_environment_links
921 SET urls_json = ${JSON.stringify([untrusted, b.url])}
922 WHERE environment_id = ${box.environmentId}
923 `;
924 expect((yield* a.links.resolve(box.environmentId)).url).toBe(b.url);
925 expect((yield* a.links.list).map((link) => link.status)).toEqual(["reachable"]);
926 }),
927 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
928);
929​
930it("reads Node's TLS verification code from anywhere in a cause chain", () => {
931 for (const code of [
932 "DEPTH_ZERO_SELF_SIGNED_CERT",
933 "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
934 "CERT_HAS_EXPIRED",
935 "ERR_TLS_CERT_ALTNAME_INVALID",
936 "HOSTNAME_MISMATCH",
937 "INVALID_CA",
938 "INVALID_PURPOSE",
939 "PATH_LENGTH_EXCEEDED",
940 ]) {
941 expect(PeerLinks.certificateErrorCode({ code })).toBe(code);
942 }
943 const wrapped = { message: "fetch failed", cause: { cause: { code: "INVALID_CA" } } };
944 expect(PeerLinks.certificateErrorCode(wrapped)).toBe("INVALID_CA");
945 expect(PeerLinks.certificateErrorCode({ cause: { code: "ECONNREFUSED" } })).toBeUndefined();
946 expect(PeerLinks.certificateErrorCode(new Error("timed out"))).toBeUndefined();
947});