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

PeerLinks.test.ts

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