Open History to see the last commit
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("a peer that answers the listing again no longer lists the call that missed it", () =>
410 Effect.scoped(
411 Effect.gen(function* () {
412 const b = yield* serveB(box);
413 const a = yield* makeA(laptop);
414 const pairing = yield* b.auth.issuePairingCredential();
415 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
416 yield* probe(a);
417
418 // One linked call while the peer is away, as a laptop asleep with its lid closed.
419 yield* Ref.set(b.descriptor, descriptorOf("environment-impostor", "Impostor"));
420 const missed = yield* probe(a).pipe(Effect.flip);
421 expect(missed.message).toContain("Box did not answer");
422
423 yield* Ref.set(b.descriptor, box);
424 const [listed] = yield* a.links.list;
425 expect(listed?.status).toBe("reachable");
426 expect(listed?.lastError).toBeNull();
427 }),
428 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
429);
430
431it.effect("lists a peer asleep at every address as unreachable within one probe budget", () =>
432 Effect.scoped(
433 Effect.gen(function* () {
434 const b = yield* serveB(box);
435 // Another address of the same machine, asleep too.
436 const wake = yield* Deferred.make<void>();
437 const elsewhere = yield* serveRaw(() =>
438 Deferred.await(wake).pipe(Effect.as(HttpServerResponse.empty({ status: 503 }))),
439 );
440 yield* Effect.addFinalizer(() => Deferred.succeed(wake, undefined));
441 const a = yield* makeA(laptop);
442 const pairing = yield* b.auth.issuePairingCredential();
443 yield* a.links.link({
444 url: b.url,
445 alternateUrls: [elsewhere],
446 pairingCode: pairing.credential,
447 access: "auto",
448 });
449
450 yield* Ref.set(b.asleep, true);
451 const listing = yield* a.links.list.pipe(Effect.forkScoped);
452 yield* Queue.take(b.unanswered);
453 yield* TestClock.adjust(Duration.seconds(3));
454 const listed = yield* Fiber.join(listing);
455 expect(listed.map((link) => link.status)).toEqual(["unreachable"]);
456 }),
457 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
458);
459
460it.effect("lists a peer as reachable at another address while its first one sleeps", () =>
461 Effect.scoped(
462 Effect.gen(function* () {
463 const b = yield* serveB(box);
464 const described = yield* HttpClient.get(`${b.url}/.well-known/t3/environment`).pipe(
465 Effect.flatMap((response) => response.text),
466 Effect.provide(FetchHttpClient.layer),
467 );
468 // Another address of the same machine that answers.
469 const elsewhere = yield* serveRaw(() =>
470 Effect.succeed(HttpServerResponse.text(described, { contentType: "application/json" })),
471 );
472 const a = yield* makeA(laptop);
473 const pairing = yield* b.auth.issuePairingCredential();
474 yield* a.links.link({
475 url: b.url,
476 alternateUrls: [elsewhere],
477 pairingCode: pairing.credential,
478 access: "auto",
479 });
480
481 yield* Ref.set(b.asleep, true);
482 expect((yield* a.links.list).map((link) => link.status)).toEqual(["reachable"]);
483 }),
484 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
485);
486
487it.effect("resolves a link at its answering address without waiting out a sleeping first", () =>
488 Effect.scoped(
489 Effect.gen(function* () {
490 const b = yield* serveB(box);
491 const described = yield* HttpClient.get(`${b.url}/.well-known/t3/environment`).pipe(
492 Effect.flatMap((response) => response.text),
493 Effect.provide(FetchHttpClient.layer),
494 );
495 const elsewhere = yield* serveRaw(() =>
496 Effect.succeed(HttpServerResponse.text(described, { contentType: "application/json" })),
497 );
498 const a = yield* makeA(laptop);
499 const pairing = yield* b.auth.issuePairingCredential();
500 yield* a.links.link({
501 url: b.url,
502 alternateUrls: [elsewhere],
503 pairingCode: pairing.credential,
504 access: "auto",
505 });
506
507 yield* Ref.set(b.asleep, true);
508 const first = yield* a.links.resolve(box.environmentId).pipe(Effect.forkScoped);
509 yield* Queue.take(b.unanswered);
510 yield* TestClock.adjust(Duration.seconds(3));
511 expect((yield* Fiber.join(first)).url).toBe(elsewhere);
512
513 // The clock no longer moves: a resolve that probes the sleeping address first never returns.
514 expect((yield* a.links.resolve(box.environmentId)).url).toBe(elsewhere);
515 }),
516 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
517);
518
519it.effect("cancelling a descriptor probe aborts its request and leaves later resolves fresh", () =>
520 Effect.scoped(
521 Effect.gen(function* () {
522 const hold = yield* Ref.make(false);
523 const requests = yield* Ref.make(0);
524 const entered = yield* Deferred.make<void>();
525 const interrupted = yield* Deferred.make<void>();
526 const holdDescriptor = HttpRouter.middleware(
527 (httpEffect) =>
528 Effect.gen(function* () {
529 const request = yield* HttpServerRequest.HttpServerRequest;
530 if (request.url.startsWith("/.well-known/t3/environment")) {
531 yield* Ref.update(requests, (count) => count + 1);
532 if (yield* Ref.get(hold)) {
533 return yield* Deferred.succeed(entered, undefined).pipe(
534 Effect.andThen(Effect.never),
535 Effect.onInterrupt(() =>
536 Deferred.succeed(interrupted, undefined).pipe(Effect.asVoid),
537 ),
538 Effect.interruptible,
539 );
540 }
541 }
542 return yield* httpEffect;
543 }),
544 { global: true },
545 );
546 const b = yield* servePeer(
547 box,
548 Layer.merge(McpHttpServer.toolkitRegistration(ProbeToolkit, probeHandlers), holdDescriptor),
549 );
550 const a = yield* makeA(laptop);
551 const pairing = yield* b.auth.issuePairingCredential();
552 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
553 yield* Ref.set(b.bearers, []);
554 yield* Ref.set(requests, 0);
555 yield* Ref.set(hold, true);
556
557 const resolving = yield* a.links.resolve(box.environmentId).pipe(Effect.forkScoped);
558 yield* Deferred.await(entered);
559 yield* Fiber.interrupt(resolving);
560 yield* Deferred.await(interrupted);
561
562 yield* Ref.set(hold, false);
563 expect((yield* a.links.resolve(box.environmentId)).url).toBe(b.url);
564 expect(yield* Ref.get(requests)).toBe(2);
565 expect(yield* Ref.get(b.bearers)).toEqual([]);
566 }),
567 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
568);
569
570it.live("one dropped descriptor request does not list a live peer as unreachable", () =>
571 Effect.scoped(
572 Effect.gen(function* () {
573 const dropNext = yield* Ref.make(false);
574 const dropOnce = HttpRouter.middleware(
575 (httpEffect) =>
576 Effect.gen(function* () {
577 const request = yield* HttpServerRequest.HttpServerRequest;
578 if (
579 request.url.startsWith("/.well-known/t3/environment") &&
580 (yield* Ref.getAndSet(dropNext, false))
581 ) {
582 return HttpServerResponse.empty({ status: 503 });
583 }
584 return yield* httpEffect;
585 }),
586 { global: true },
587 );
588 const b = yield* servePeer(
589 box,
590 Layer.merge(McpHttpServer.toolkitRegistration(ProbeToolkit, probeHandlers), dropOnce),
591 );
592 const a = yield* makeA(laptop);
593 const pairing = yield* b.auth.issuePairingCredential();
594 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
595
596 yield* Ref.set(dropNext, true);
597 expect((yield* a.links.list).map((link) => link.status)).toEqual(["reachable"]);
598 }),
599 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
600);
601
602it.effect("reads one stored link without asking the peer", () =>
603 Effect.scoped(
604 Effect.gen(function* () {
605 const b = yield* serveB(box);
606 const a = yield* makeA(laptop);
607 const pairing = yield* b.auth.issuePairingCredential();
608 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
609 yield* Ref.set(b.probes, 0);
610
611 const stored = yield* a.links.get(box.environmentId);
612 expect(Option.map(stored, (link) => link.label)).toEqual(Option.some("Box"));
613 expect(Option.isNone(yield* a.links.get(laptop.environmentId))).toBe(true);
614 expect(yield* a.links.names).toEqual([{ environmentId: box.environmentId, label: "Box" }]);
615 expect(yield* Ref.get(b.probes)).toBe(0);
616
617 // An older answer that lands after a newer one never moves the expiry back.
618 const expiresAt = Option.getOrThrow(stored).expiresAt;
619 const later = DateTime.add(expiresAt, { days: 20 });
620 yield* a.links.recordExpiry(box.environmentId, later);
621 yield* a.links.recordExpiry(box.environmentId, DateTime.add(expiresAt, { days: 10 }));
622 expect(
623 Option.map(yield* a.links.get(box.environmentId), (link) =>
624 DateTime.formatIso(link.expiresAt),
625 ),
626 ).toEqual(Option.some(DateTime.formatIso(later)));
627 }),
628 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
629);
630
631it.effect("a linked peer that is renamed shows its new name", () =>
632 Effect.scoped(
633 Effect.gen(function* () {
634 const b = yield* serveB(box);
635 const a = yield* makeA(laptop);
636 const pairing = yield* b.auth.issuePairingCredential();
637 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
638
639 yield* Ref.set(b.descriptor, descriptorOf(box.environmentId, "Box Mini"));
640 expect((yield* a.links.resolve(box.environmentId)).link.label).toBe("Box Mini");
641 const stored = yield* a.links.get(box.environmentId);
642 expect(Option.map(stored, (link) => link.label)).toEqual(Option.some("Box Mini"));
643
644 yield* Ref.set(b.descriptor, descriptorOf(box.environmentId, "Box Studio"));
645 expect((yield* a.links.list).map((link) => link.label)).toEqual(["Box Studio"]);
646 const storedAfterList = yield* a.links.get(box.environmentId);
647 expect(Option.map(storedAfterList, (link) => link.label)).toEqual(Option.some("Box Studio"));
648 }),
649 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
650);
651
652it.effect(
653 "a link forgotten while it resolves says it is not linked, not that it lost its credential",
654 () =>
655 Effect.scoped(
656 Effect.gen(function* () {
657 const b = yield* serveB(box);
658 const beforeGet = yield* Ref.make<Effect.Effect<void>>(Effect.void);
659 const racing = Layer.effect(
660 ServerSecretStore.ServerSecretStore,
661 Effect.map(ServerSecretStore.make, (store) =>
662 ServerSecretStore.ServerSecretStore.of({
663 ...store,
664 get: (name) =>
665 Ref.getAndSet(beforeGet, Effect.void).pipe(
666 Effect.flatten,
667 Effect.andThen(store.get(name)),
668 ),
669 }),
670 ),
671 );
672 const a = yield* makeA(laptop, racing);
673 const pairing = yield* b.auth.issuePairingCredential();
674 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
675
676 yield* Ref.set(beforeGet, Effect.orDie(Effect.asVoid(a.links.unlink(box.environmentId))));
677 const forgotten = yield* probe(a).pipe(Effect.flip);
678 expect(forgotten.message).toContain("not linked to");
679 }),
680 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
681);
682
683it.effect("tells the agent to link again once the peer revokes the link or it expires", () =>
684 Effect.scoped(
685 Effect.gen(function* () {
686 const b = yield* serveB(box);
687 const a = yield* makeA(laptop);
688 const pairing = yield* b.auth.issuePairingCredential();
689 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
690 yield* probe(a);
691
692 const [session] = yield* linkedSessions(b);
693 yield* b.auth.revokeSession(session!.sessionId);
694 const revoked = yield* probe(a).pipe(Effect.flip);
695 expect(revoked.code).toBe("capability_denied");
696 expect(revoked.message).toContain("revoked there");
697
698 yield* a.links.link({
699 url: b.url,
700 pairingCode: (yield* b.auth.issuePairingCredential()).credential,
701 access: "auto",
702 });
703 // A link made with a peer that later answers without the fence, as
704 // one made before the fence or a peer moved back to such a version.
705 yield* Ref.set(b.descriptor, descriptorOf("environment-box", "Box", { linkFence: false }));
706 yield* Ref.set(b.bearers, []);
707 const unfenced = yield* probe(a).pipe(Effect.flip);
708 expect(unfenced.code).toBe("capability_denied");
709 expect(unfenced.message).toContain("cannot keep a linked agent's limits");
710 expect(yield* Ref.get(b.bearers)).toEqual([]);
711 yield* Ref.set(b.descriptor, box);
712
713 // A link stored before links were marked: its session there is not a
714 // link's, so the peer would not fence its work even though it can.
715 yield* a.sql`UPDATE peer_environment_links SET fenced = 0`;
716 // Linking again is its only way back, as for an expired link.
717 expect((yield* a.links.list).map((link) => link.status)).toEqual(["expired"]);
718 const legacy = yield* probe(a).pipe(Effect.flip);
719 expect(legacy.code).toBe("capability_denied");
720 expect(legacy.message).toContain("Link it again");
721 expect(yield* Ref.get(b.bearers)).toEqual([]);
722 yield* a.links.link({
723 url: b.url,
724 pairingCode: (yield* b.auth.issuePairingCredential()).credential,
725 access: "auto",
726 });
727 yield* probe(a);
728
729 yield* TestClock.adjust(Duration.days(31));
730 expect((yield* a.links.list).map((link) => link.status)).toEqual(["expired"]);
731 expect(yield* a.links.names).toEqual([]);
732 yield* Ref.set(b.bearers, []);
733 const expired = yield* probe(a).pipe(Effect.flip);
734 expect(expired.code).toBe("capability_denied");
735 expect(expired.message).toContain("expired");
736 expect(yield* Ref.get(b.bearers)).toEqual([]);
737 }),
738 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
739);
740
741it.effect(
742 "refuses to link itself, plain http off this machine and the tailnet, or a peer that cannot hold a linked agent to its limits",
743 () =>
744 Effect.scoped(
745 Effect.gen(function* () {
746 const b = yield* serveB(
747 descriptorOf("environment-box", "Box", { mcpModeLimitHeader: false }),
748 );
749 const a = yield* makeA(laptop);
750 const pairing = yield* b.auth.issuePairingCredential();
751 const older = yield* a.links
752 .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
753 .pipe(Effect.flip);
754 expect(older.reason).toBe("incompatible");
755 // Nor one whose link's work could reach the user's own threads there.
756 yield* Ref.set(b.descriptor, descriptorOf("environment-box", "Box", { linkFence: false }));
757 const unfenced = yield* a.links
758 .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
759 .pipe(Effect.flip);
760 expect(unfenced.reason).toBe("incompatible");
761
762 // Plain http to a LAN address would carry the code and token in clear.
763 const lan = yield* a.links
764 .link({
765 url: "http://192.168.1.20:3773",
766 pairingCode: pairing.credential,
767 access: "auto",
768 })
769 .pipe(Effect.flip);
770 expect(lan.message).toContain("plain http");
771 const lanAlternate = yield* a.links
772 .link({
773 url: b.url,
774 alternateUrls: ["http://192.168.1.20:3773"],
775 pairingCode: pairing.credential,
776 access: "auto",
777 })
778 .pipe(Effect.flip);
779 expect(lanAlternate.message).toContain("plain http");
780
781 yield* Ref.set(b.descriptor, laptop);
782 const self = yield* a.links
783 .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
784 .pipe(Effect.flip);
785 expect(self.reason).toBe("self");
786 // Neither attempt spent the pairing code on a session.
787 expect(yield* linkedSessions(b)).toEqual([]);
788 }),
789 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
790);
791
792it.effect(
793 "linking a picked machine skips an address that answers as another, and never signs in there",
794 () =>
795 Effect.scoped(
796 Effect.gen(function* () {
797 const impostor = yield* serveApart(descriptorOf("environment-impostor", "Impostor"));
798 const b = yield* serveB(box);
799 const a = yield* makeA(laptop);
800 const pairing = yield* b.auth.issuePairingCredential();
801 const linked = yield* a.links.link({
802 url: impostor.url,
803 alternateUrls: [b.url],
804 pairingCode: pairing.credential,
805 access: "auto",
806 expectedEnvironmentId: box.environmentId,
807 });
808 expect(linked).toMatchObject({ environmentId: box.environmentId, urls: [b.url] });
809 // A picked machine is never linked at this machine's own loopback.
810 const own = yield* a.links
811 .link({
812 url: b.url.replace("127.0.0.1", "localhost"),
813 pairingCode: pairing.credential,
814 access: "auto",
815 expectedEnvironmentId: box.environmentId,
816 })
817 .pipe(Effect.flip);
818 expect(own.message).toContain("is this machine");
819 yield* probe(a);
820 expect(yield* linkedSessions(impostor)).toEqual([]);
821 expect(yield* Ref.get(impostor.bearers)).toEqual([]);
822 expect((yield* linkedSessions(b)).length).toBe(1);
823
824 // An address alone that answers as the linked box never takes over its link.
825 yield* Ref.set(impostor.descriptor, box);
826 const second = yield* impostor.auth.issuePairingCredential();
827 const taken = yield* a.links
828 .link({ url: impostor.url, pairingCode: second.credential, access: "auto" })
829 .pipe(Effect.flip);
830 expect(taken.message).toContain("already linked");
831 expect(yield* linkedSessions(impostor)).toEqual([]);
832 expect(Option.getOrUndefined(yield* a.links.get(box.environmentId))?.urls).toEqual([b.url]);
833 // The address the link already has still renews it.
834 const renewal = yield* b.auth.issuePairingCredential();
835 expect(
836 yield* a.links.link({ url: b.url, pairingCode: renewal.credential, access: "auto" }),
837 ).toMatchObject({ urls: [b.url] });
838 }),
839 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
840);
841
842it.effect("linking a picked machine that answers nowhere names it and links nothing", () =>
843 Effect.scoped(
844 Effect.gen(function* () {
845 const impostor = yield* serveApart(descriptorOf("environment-impostor", "Impostor"));
846 const a = yield* makeA(laptop);
847 const failed = yield* a.links
848 .link({
849 url: impostor.url,
850 alternateUrls: ["http://192.168.1.20:3773"],
851 pairingCode: "unused",
852 access: "auto",
853 expectedEnvironmentId: box.environmentId,
854 expectedLabel: "Box",
855 })
856 .pipe(Effect.flip);
857 expect(failed.reason).toBe("unreachable");
858 expect(failed.answeredAs).toBe("Impostor");
859 expect(failed.message).toBe(
860 `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.`,
861 );
862 expect(yield* a.links.list).toEqual([]);
863 expect(yield* linkedSessions(impostor)).toEqual([]);
864
865 // Every address refused: the message says why.
866 const refused = yield* a.links
867 .link({
868 url: "http://192.168.1.20:3773",
869 pairingCode: "unused",
870 access: "auto",
871 expectedEnvironmentId: box.environmentId,
872 expectedLabel: "Box",
873 })
874 .pipe(Effect.flip);
875 expect(refused.message).toContain("could not reach Box");
876 expect(refused.message).toContain("plain http");
877 }),
878 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
879);
880
881it.live("linking an address with nothing listening says so, unlike one that is not T3 Code", () =>
882 Effect.scoped(
883 Effect.gen(function* () {
884 // Any test worker can reuse a closed ephemeral port; port 2 is privileged and outside that range.
885 const closed = "http://127.0.0.1:2";
886 const notT3 = yield* serveRaw(() =>
887 Effect.succeed(
888 HttpServerResponse.text("<h1>Not Found</h1>", { status: 404, contentType: "text/html" }),
889 ),
890 );
891 const a = yield* makeA(laptop);
892 const linking = (url: string) =>
893 a.links.link({ url, pairingCode: "unused", access: "auto" }).pipe(Effect.flip);
894 expect((yield* linking(closed)).message).toBe(`${closed} did not answer (ECONNREFUSED).`);
895 expect((yield* linking(notT3)).message).toBe(
896 `${notT3} answered, but not as a T3 Code environment this version understands.`,
897 );
898 expect(yield* a.links.list).toEqual([]);
899 }),
900 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
901);
902
903/** An https listener whose certificate this machine does not trust. */
904const serveUntrusted = Layer.build(
905 Layer.fresh(
906 NodeHttpServer.layerServer(
907 () =>
908 NodeHttps.createServer({
909 key: NodeFS.readFileSync(new URL("./fixtures/localhost-key.pem", import.meta.url)),
910 cert: NodeFS.readFileSync(new URL("./fixtures/localhost-cert.pem", import.meta.url)),
911 }),
912 { port: 0, host: "127.0.0.1" },
913 ),
914 ),
915).pipe(
916 Effect.map((server) => {
917 const address = Context.get(server, HttpServer.HttpServer).address;
918 if (address._tag === "UnixPathAddress") throw new Error("expected a TCP address");
919 return `https://127.0.0.1:${address.port}`;
920 }),
921);
922
923it.effect("names an untrusted certificate instead of calling the peer something else", () =>
924 Effect.scoped(
925 Effect.gen(function* () {
926 const untrusted = yield* serveUntrusted;
927 const a = yield* makeA(laptop);
928 const failed = yield* a.links
929 .link({ url: untrusted, pairingCode: "unused", access: "auto" })
930 .pipe(Effect.flip);
931 expect(failed.reason).toBe("unreachable");
932 expect(failed.message).toContain("certificate this machine rejected");
933 expect(failed.message).toContain("DEPTH_ZERO_SELF_SIGNED_CERT");
934 expect(yield* a.links.list).toEqual([]);
935
936 // A stored link tries its next address past an untrusted one.
937 const b = yield* serveB(box);
938 const pairing = yield* b.auth.issuePairingCredential();
939 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
940 yield* a.sql`
941 UPDATE peer_environment_links
942 SET urls_json = ${JSON.stringify([untrusted, b.url])}
943 WHERE environment_id = ${box.environmentId}
944 `;
945 expect((yield* a.links.resolve(box.environmentId)).url).toBe(b.url);
946 expect((yield* a.links.list).map((link) => link.status)).toEqual(["reachable"]);
947 }),
948 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
949);
950
951it("reads Node's TLS verification code from anywhere in a cause chain", () => {
952 for (const code of [
953 "DEPTH_ZERO_SELF_SIGNED_CERT",
954 "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
955 "CERT_HAS_EXPIRED",
956 "ERR_TLS_CERT_ALTNAME_INVALID",
957 "HOSTNAME_MISMATCH",
958 "INVALID_CA",
959 "INVALID_PURPOSE",
960 "PATH_LENGTH_EXCEEDED",
961 ]) {
962 expect(PeerLinks.certificateErrorCode({ code })).toBe(code);
963 }
964 const wrapped = { message: "fetch failed", cause: { cause: { code: "INVALID_CA" } } };
965 expect(PeerLinks.certificateErrorCode(wrapped)).toBe("INVALID_CA");
966 expect(PeerLinks.certificateErrorCode({ cause: { code: "ECONNREFUSED" } })).toBeUndefined();
967 expect(PeerLinks.certificateErrorCode(new Error("timed out"))).toBeUndefined();
968});