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

PeerLinks.test.ts

883 lines35.5 KB

1// @effect-diagnostics-next-line nodeBuiltinImport:off - The HTTPS test server needs certificate bytes.
2import * as NodeFS from "node:fs";
3// @effect-diagnostics-next-line nodeBuiltinImport:off - A peer with a certificate this machine does not trust.
4import * as NodeHttps from "node:https";
5import { NodeHttpServer } from "@effect/platform-node";
6import { type ExecutionEnvironmentDescriptor, OrchestratorMcpFailure } from "@t3tools/contracts";
7import { expect, it } from "@effect/vitest";
8import * as Context from "effect/Context";
9import * as 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("cancelling a descriptor probe aborts its request and leaves later resolves fresh", () =>
448 Effect.scoped(
449 Effect.gen(function* () {
450 const hold = yield* Ref.make(false);
451 const requests = yield* Ref.make(0);
452 const entered = yield* Deferred.make<void>();
453 const interrupted = yield* Deferred.make<void>();
454 const holdDescriptor = HttpRouter.middleware(
455 (httpEffect) =>
456 Effect.gen(function* () {
457 const request = yield* HttpServerRequest.HttpServerRequest;
458 if (request.url.startsWith("/.well-known/t3/environment")) {
459 yield* Ref.update(requests, (count) => count + 1);
460 if (yield* Ref.get(hold)) {
461 return yield* Deferred.succeed(entered, undefined).pipe(
462 Effect.andThen(Effect.never),
463 Effect.onInterrupt(() =>
464 Deferred.succeed(interrupted, undefined).pipe(Effect.asVoid),
465 ),
466 Effect.interruptible,
467 );
468 }
469 }
470 return yield* httpEffect;
471 }),
472 { global: true },
473 );
474 const b = yield* servePeer(
475 box,
476 Layer.merge(McpHttpServer.toolkitRegistration(ProbeToolkit, probeHandlers), holdDescriptor),
477 );
478 const a = yield* makeA(laptop);
479 const pairing = yield* b.auth.issuePairingCredential();
480 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
481 yield* Ref.set(b.bearers, []);
482 yield* Ref.set(requests, 0);
483 yield* Ref.set(hold, true);
484​
485 const resolving = yield* a.links.resolve(box.environmentId).pipe(Effect.forkScoped);
486 yield* Deferred.await(entered);
487 yield* Fiber.interrupt(resolving);
488 yield* Deferred.await(interrupted);
489​
490 yield* Ref.set(hold, false);
491 expect((yield* a.links.resolve(box.environmentId)).url).toBe(b.url);
492 expect(yield* Ref.get(requests)).toBe(2);
493 expect(yield* Ref.get(b.bearers)).toEqual([]);
494 }),
495 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
496);
497​
498it.live("one dropped descriptor request does not list a live peer as unreachable", () =>
499 Effect.scoped(
500 Effect.gen(function* () {
501 const dropNext = yield* Ref.make(false);
502 const dropOnce = HttpRouter.middleware(
503 (httpEffect) =>
504 Effect.gen(function* () {
505 const request = yield* HttpServerRequest.HttpServerRequest;
506 if (
507 request.url.startsWith("/.well-known/t3/environment") &&
508 (yield* Ref.getAndSet(dropNext, false))
509 ) {
510 return HttpServerResponse.empty({ status: 503 });
511 }
512 return yield* httpEffect;
513 }),
514 { global: true },
515 );
516 const b = yield* servePeer(
517 box,
518 Layer.merge(McpHttpServer.toolkitRegistration(ProbeToolkit, probeHandlers), dropOnce),
519 );
520 const a = yield* makeA(laptop);
521 const pairing = yield* b.auth.issuePairingCredential();
522 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
523​
524 yield* Ref.set(dropNext, true);
525 expect((yield* a.links.list).map((link) => link.status)).toEqual(["reachable"]);
526 }),
527 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
528);
529​
530it.effect("reads one stored link without asking the peer", () =>
531 Effect.scoped(
532 Effect.gen(function* () {
533 const b = yield* serveB(box);
534 const a = yield* makeA(laptop);
535 const pairing = yield* b.auth.issuePairingCredential();
536 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
537 yield* Ref.set(b.probes, 0);
538​
539 const stored = yield* a.links.get(box.environmentId);
540 expect(Option.map(stored, (link) => link.label)).toEqual(Option.some("Box"));
541 expect(Option.isNone(yield* a.links.get(laptop.environmentId))).toBe(true);
542 expect(yield* Ref.get(b.probes)).toBe(0);
543 }),
544 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
545);
546​
547it.effect("a linked peer that is renamed shows its new name", () =>
548 Effect.scoped(
549 Effect.gen(function* () {
550 const b = yield* serveB(box);
551 const a = yield* makeA(laptop);
552 const pairing = yield* b.auth.issuePairingCredential();
553 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
554​
555 yield* Ref.set(b.descriptor, descriptorOf(box.environmentId, "Box Mini"));
556 expect((yield* a.links.resolve(box.environmentId)).link.label).toBe("Box Mini");
557 const stored = yield* a.links.get(box.environmentId);
558 expect(Option.map(stored, (link) => link.label)).toEqual(Option.some("Box Mini"));
559​
560 yield* Ref.set(b.descriptor, descriptorOf(box.environmentId, "Box Studio"));
561 expect((yield* a.links.list).map((link) => link.label)).toEqual(["Box Studio"]);
562 const storedAfterList = yield* a.links.get(box.environmentId);
563 expect(Option.map(storedAfterList, (link) => link.label)).toEqual(Option.some("Box Studio"));
564 }),
565 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
566);
567​
568it.effect(
569 "a link forgotten while it resolves says it is not linked, not that it lost its credential",
570 () =>
571 Effect.scoped(
572 Effect.gen(function* () {
573 const b = yield* serveB(box);
574 const beforeGet = yield* Ref.make<Effect.Effect<void>>(Effect.void);
575 const racing = Layer.effect(
576 ServerSecretStore.ServerSecretStore,
577 Effect.map(ServerSecretStore.make, (store) =>
578 ServerSecretStore.ServerSecretStore.of({
579 ...store,
580 get: (name) =>
581 Ref.getAndSet(beforeGet, Effect.void).pipe(
582 Effect.flatten,
583 Effect.andThen(store.get(name)),
584 ),
585 }),
586 ),
587 );
588 const a = yield* makeA(laptop, racing);
589 const pairing = yield* b.auth.issuePairingCredential();
590 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
591​
592 yield* Ref.set(beforeGet, Effect.orDie(Effect.asVoid(a.links.unlink(box.environmentId))));
593 const forgotten = yield* probe(a).pipe(Effect.flip);
594 expect(forgotten.message).toContain("not linked to");
595 }),
596 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
597);
598​
599it.effect("tells the agent to link again once the peer revokes the link or it expires", () =>
600 Effect.scoped(
601 Effect.gen(function* () {
602 const b = yield* serveB(box);
603 const a = yield* makeA(laptop);
604 const pairing = yield* b.auth.issuePairingCredential();
605 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
606 yield* probe(a);
607​
608 const [session] = yield* linkedSessions(b);
609 yield* b.auth.revokeSession(session!.sessionId);
610 const revoked = yield* probe(a).pipe(Effect.flip);
611 expect(revoked.code).toBe("capability_denied");
612 expect(revoked.message).toContain("revoked there");
613​
614 yield* a.links.link({
615 url: b.url,
616 pairingCode: (yield* b.auth.issuePairingCredential()).credential,
617 access: "auto",
618 });
619 // A link made with a peer that later answers without the fence, as
620 // one made before the fence or a peer moved back to such a version.
621 yield* Ref.set(b.descriptor, descriptorOf("environment-box", "Box", { linkFence: false }));
622 yield* Ref.set(b.bearers, []);
623 const unfenced = yield* probe(a).pipe(Effect.flip);
624 expect(unfenced.code).toBe("capability_denied");
625 expect(unfenced.message).toContain("cannot keep a linked agent's limits");
626 expect(yield* Ref.get(b.bearers)).toEqual([]);
627 yield* Ref.set(b.descriptor, box);
628​
629 // A link stored before links were marked: its session there is not a
630 // link's, so the peer would not fence its work even though it can.
631 yield* a.sql`UPDATE peer_environment_links SET fenced = 0`;
632 // Linking again is its only way back, as for an expired link.
633 expect((yield* a.links.list).map((link) => link.status)).toEqual(["expired"]);
634 const legacy = yield* probe(a).pipe(Effect.flip);
635 expect(legacy.code).toBe("capability_denied");
636 expect(legacy.message).toContain("Link it again");
637 expect(yield* Ref.get(b.bearers)).toEqual([]);
638 yield* a.links.link({
639 url: b.url,
640 pairingCode: (yield* b.auth.issuePairingCredential()).credential,
641 access: "auto",
642 });
643 yield* probe(a);
644​
645 yield* TestClock.adjust(Duration.days(31));
646 expect((yield* a.links.list).map((link) => link.status)).toEqual(["expired"]);
647 yield* Ref.set(b.bearers, []);
648 const expired = yield* probe(a).pipe(Effect.flip);
649 expect(expired.code).toBe("capability_denied");
650 expect(expired.message).toContain("expired");
651 expect(yield* Ref.get(b.bearers)).toEqual([]);
652 }),
653 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
654);
655​
656it.effect(
657 "refuses to link itself, plain http off this machine and the tailnet, or a peer that cannot hold a linked agent to its limits",
658 () =>
659 Effect.scoped(
660 Effect.gen(function* () {
661 const b = yield* serveB(
662 descriptorOf("environment-box", "Box", { mcpModeLimitHeader: false }),
663 );
664 const a = yield* makeA(laptop);
665 const pairing = yield* b.auth.issuePairingCredential();
666 const older = yield* a.links
667 .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
668 .pipe(Effect.flip);
669 expect(older.reason).toBe("incompatible");
670 // Nor one whose link's work could reach the user's own threads there.
671 yield* Ref.set(b.descriptor, descriptorOf("environment-box", "Box", { linkFence: false }));
672 const unfenced = yield* a.links
673 .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
674 .pipe(Effect.flip);
675 expect(unfenced.reason).toBe("incompatible");
676​
677 // Plain http to a LAN address would carry the code and token in clear.
678 const lan = yield* a.links
679 .link({
680 url: "http://192.168.1.20:3773",
681 pairingCode: pairing.credential,
682 access: "auto",
683 })
684 .pipe(Effect.flip);
685 expect(lan.message).toContain("plain http");
686 const lanAlternate = yield* a.links
687 .link({
688 url: b.url,
689 alternateUrls: ["http://192.168.1.20:3773"],
690 pairingCode: pairing.credential,
691 access: "auto",
692 })
693 .pipe(Effect.flip);
694 expect(lanAlternate.message).toContain("plain http");
695​
696 yield* Ref.set(b.descriptor, laptop);
697 const self = yield* a.links
698 .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
699 .pipe(Effect.flip);
700 expect(self.reason).toBe("self");
701 // Neither attempt spent the pairing code on a session.
702 expect(yield* linkedSessions(b)).toEqual([]);
703 }),
704 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
705);
706​
707it.effect(
708 "linking a picked machine skips an address that answers as another, and never signs in there",
709 () =>
710 Effect.scoped(
711 Effect.gen(function* () {
712 const impostor = yield* serveApart(descriptorOf("environment-impostor", "Impostor"));
713 const b = yield* serveB(box);
714 const a = yield* makeA(laptop);
715 const pairing = yield* b.auth.issuePairingCredential();
716 const linked = yield* a.links.link({
717 url: impostor.url,
718 alternateUrls: [b.url],
719 pairingCode: pairing.credential,
720 access: "auto",
721 expectedEnvironmentId: box.environmentId,
722 });
723 expect(linked).toMatchObject({ environmentId: box.environmentId, urls: [b.url] });
724 // A picked machine is never linked at this machine's own loopback.
725 const own = yield* a.links
726 .link({
727 url: b.url.replace("127.0.0.1", "localhost"),
728 pairingCode: pairing.credential,
729 access: "auto",
730 expectedEnvironmentId: box.environmentId,
731 })
732 .pipe(Effect.flip);
733 expect(own.message).toContain("is this machine");
734 yield* probe(a);
735 expect(yield* linkedSessions(impostor)).toEqual([]);
736 expect(yield* Ref.get(impostor.bearers)).toEqual([]);
737 expect((yield* linkedSessions(b)).length).toBe(1);
738​
739 // An address alone that answers as the linked box never takes over its link.
740 yield* Ref.set(impostor.descriptor, box);
741 const second = yield* impostor.auth.issuePairingCredential();
742 const taken = yield* a.links
743 .link({ url: impostor.url, pairingCode: second.credential, access: "auto" })
744 .pipe(Effect.flip);
745 expect(taken.message).toContain("already linked");
746 expect(yield* linkedSessions(impostor)).toEqual([]);
747 expect(Option.getOrUndefined(yield* a.links.get(box.environmentId))?.urls).toEqual([b.url]);
748 // The address the link already has still renews it.
749 const renewal = yield* b.auth.issuePairingCredential();
750 expect(
751 yield* a.links.link({ url: b.url, pairingCode: renewal.credential, access: "auto" }),
752 ).toMatchObject({ urls: [b.url] });
753 }),
754 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
755);
756​
757it.effect("linking a picked machine that answers nowhere names it and links nothing", () =>
758 Effect.scoped(
759 Effect.gen(function* () {
760 const impostor = yield* serveApart(descriptorOf("environment-impostor", "Impostor"));
761 const a = yield* makeA(laptop);
762 const failed = yield* a.links
763 .link({
764 url: impostor.url,
765 alternateUrls: ["http://192.168.1.20:3773"],
766 pairingCode: "unused",
767 access: "auto",
768 expectedEnvironmentId: box.environmentId,
769 expectedLabel: "Box",
770 })
771 .pipe(Effect.flip);
772 expect(failed.reason).toBe("unreachable");
773 expect(failed.message).toBe(
774 `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.`,
775 );
776 expect(yield* a.links.list).toEqual([]);
777 expect(yield* linkedSessions(impostor)).toEqual([]);
778​
779 // Every address refused: the message says why.
780 const refused = yield* a.links
781 .link({
782 url: "http://192.168.1.20:3773",
783 pairingCode: "unused",
784 access: "auto",
785 expectedEnvironmentId: box.environmentId,
786 expectedLabel: "Box",
787 })
788 .pipe(Effect.flip);
789 expect(refused.message).toContain("could not reach Box");
790 expect(refused.message).toContain("plain http");
791 }),
792 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
793);
794​
795it.live("linking an address with nothing listening says so, unlike one that is not T3 Code", () =>
796 Effect.scoped(
797 Effect.gen(function* () {
798 const closed = yield* Effect.scoped(
799 serveRaw(() => Effect.succeed(HttpServerResponse.empty({ status: 404 }))),
800 );
801 const notT3 = yield* serveRaw(() =>
802 Effect.succeed(
803 HttpServerResponse.text("<h1>Not Found</h1>", { status: 404, contentType: "text/html" }),
804 ),
805 );
806 const a = yield* makeA(laptop);
807 const linking = (url: string) =>
808 a.links.link({ url, pairingCode: "unused", access: "auto" }).pipe(Effect.flip);
809 expect((yield* linking(closed)).message).toBe(`${closed} did not answer (ECONNREFUSED).`);
810 expect((yield* linking(notT3)).message).toBe(
811 `${notT3} answered, but not as a T3 Code environment this version understands.`,
812 );
813 expect(yield* a.links.list).toEqual([]);
814 }),
815 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
816);
817​
818/** An https listener whose certificate this machine does not trust. */
819const serveUntrusted = Layer.build(
820 Layer.fresh(
821 NodeHttpServer.layerServer(
822 () =>
823 NodeHttps.createServer({
824 key: NodeFS.readFileSync(new URL("./fixtures/localhost-key.pem", import.meta.url)),
825 cert: NodeFS.readFileSync(new URL("./fixtures/localhost-cert.pem", import.meta.url)),
826 }),
827 { port: 0, host: "127.0.0.1" },
828 ),
829 ),
830).pipe(
831 Effect.map((server) => {
832 const address = Context.get(server, HttpServer.HttpServer).address;
833 if (address._tag === "UnixPathAddress") throw new Error("expected a TCP address");
834 return `https://127.0.0.1:${address.port}`;
835 }),
836);
837​
838it.effect("names an untrusted certificate instead of calling the peer something else", () =>
839 Effect.scoped(
840 Effect.gen(function* () {
841 const untrusted = yield* serveUntrusted;
842 const a = yield* makeA(laptop);
843 const failed = yield* a.links
844 .link({ url: untrusted, pairingCode: "unused", access: "auto" })
845 .pipe(Effect.flip);
846 expect(failed.reason).toBe("unreachable");
847 expect(failed.message).toContain("certificate this machine rejected");
848 expect(failed.message).toContain("DEPTH_ZERO_SELF_SIGNED_CERT");
849 expect(yield* a.links.list).toEqual([]);
850​
851 // A stored link tries its next address past an untrusted one.
852 const b = yield* serveB(box);
853 const pairing = yield* b.auth.issuePairingCredential();
854 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
855 yield* a.sql`
856 UPDATE peer_environment_links
857 SET urls_json = ${JSON.stringify([untrusted, b.url])}
858 WHERE environment_id = ${box.environmentId}
859 `;
860 expect((yield* a.links.resolve(box.environmentId)).url).toBe(b.url);
861 expect((yield* a.links.list).map((link) => link.status)).toEqual(["reachable"]);
862 }),
863 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
864);
865​
866it("reads Node's TLS verification code from anywhere in a cause chain", () => {
867 for (const code of [
868 "DEPTH_ZERO_SELF_SIGNED_CERT",
869 "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
870 "CERT_HAS_EXPIRED",
871 "ERR_TLS_CERT_ALTNAME_INVALID",
872 "HOSTNAME_MISMATCH",
873 "INVALID_CA",
874 "INVALID_PURPOSE",
875 "PATH_LENGTH_EXCEEDED",
876 ]) {
877 expect(PeerLinks.certificateErrorCode({ code })).toBe(code);
878 }
879 const wrapped = { message: "fetch failed", cause: { cause: { code: "INVALID_CA" } } };
880 expect(PeerLinks.certificateErrorCode(wrapped)).toBe("INVALID_CA");
881 expect(PeerLinks.certificateErrorCode({ cause: { code: "ECONNREFUSED" } })).toBeUndefined();
882 expect(PeerLinks.certificateErrorCode(new Error("timed out"))).toBeUndefined();
883});