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

PeerLinks.test.ts

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