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

PeerLinks.test.ts

528 lines20.8 KB

1import { NodeHttpServer } from "@effect/platform-node";
2import { type ExecutionEnvironmentDescriptor, OrchestratorMcpFailure } from "@t3tools/contracts";
3import { expect, it } from "@effect/vitest";
4import * as Context from "effect/Context";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as Layer from "effect/Layer";
8import * as Option from "effect/Option";
9import * as Ref from "effect/Ref";
10import * as Schema from "effect/Schema";
11import * as SqlClient from "effect/sql/SqlClient";
12import * as TestClock from "effect/testing/TestClock";
13import { Tool, Toolkit } from "effect/ai";
14import {
15 FetchHttpClient,
16 HttpClient,
17 HttpServer,
18 HttpServerRequest,
19 HttpServerResponse,
20} from "effect/http";
21​
22import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
23import * as McpHttpServer from "../mcp/McpHttpServer.ts";
24import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
25import * as McpToolAccess from "../mcp/McpToolAccess.ts";
26import * as PeerLinks from "./PeerLinks.ts";
27import * as ServerSettings from "../serverSettings.ts";
28import {
29 descriptorOf,
30 layerLinkingEnvironment,
31 servePeer,
32 type ServedPeer,
33} from "./PeerLinks.testkit.ts";
34import * as PeerMcpClient from "./PeerMcpClient.ts";
35​
36/** What B's probe saw: the calling client and the modes it may start work with. */
37const Probe = Schema.Struct({ caller: Schema.String, modes: Schema.String });
38​
39const ProbeToolkit = Toolkit.make(
40 Tool.make("probe", {
41 description: "Reports the calling client and the modes it may start work with.",
42 success: Probe,
43 failure: OrchestratorMcpFailure,
44 failureMode: "return",
45 dependencies: [McpInvocationContext.McpInvocationContext],
46 }),
47 Tool.make("refuse", {
48 description: "Always refuses.",
49 success: Probe,
50 failure: OrchestratorMcpFailure,
51 failureMode: "return",
52 }),
53);
54​
55const probeHandlers = McpToolAccess.toLayer(ProbeToolkit, {
56 probe: McpToolAccess.reads(() =>
57 McpInvocationContext.McpInvocationContext.pipe(
58 Effect.map((scope) => {
59 const modes = McpInvocationContext.clientModeCeiling(scope.client);
60 return {
61 caller: scope.client?.label ?? "none",
62 modes: `${modes.runtimeMode}/${modes.interactionMode}`,
63 };
64 }),
65 ),
66 ),
67 refuse: McpToolAccess.reads(() =>
68 Effect.fail(
69 new OrchestratorMcpFailure({ code: "thread_not_found", message: "No such thread." }),
70 ),
71 ),
72});
73​
74const serveB = (descriptor: ExecutionEnvironmentDescriptor) =>
75 servePeer(descriptor, McpHttpServer.toolkitRegistration(ProbeToolkit, probeHandlers));
76​
77/** Environment A, which links to B. */
78const makeA = (
79 descriptor: ExecutionEnvironmentDescriptor,
80 secrets?: typeof ServerSecretStore.layer,
81) =>
82 layerLinkingEnvironment(descriptor, secrets).pipe(
83 Layer.build,
84 Effect.map((context) => ({
85 links: Context.get(context, PeerLinks.PeerLinks),
86 peer: Context.get(context, PeerMcpClient.PeerMcpClient),
87 sql: Context.get(context, SqlClient.SqlClient),
88 settings: Context.get(context, ServerSettings.ServerSettingsService),
89 })),
90 );
91​
92const laptop = descriptorOf("environment-laptop", "Laptop");
93const box = descriptorOf("environment-box", "Box");
94const probe = (
95 a: Effect.Success<ReturnType<typeof makeA>>,
96 limits: PeerMcpClient.PeerCallLimits = { runtimeMode: "full-access", interactionMode: "default" },
97 tool = "probe",
98) =>
99 a.peer.call({
100 environmentId: box.environmentId,
101 tool,
102 arguments: {},
103 limits,
104 success: Probe,
105 });
106​
107const linkedSessions = (b: ServedPeer) => b.linkedSessions;
108​
109/** Another environment on a socket of its own, answering as `descriptor`. */
110const serveApart = (descriptor: ExecutionEnvironmentDescriptor) =>
111 Layer.build(Layer.fresh(NodeHttpServer.layerTest)).pipe(
112 Effect.flatMap((server) => serveB(descriptor).pipe(Effect.provideContext(server))),
113 );
114​
115it.effect("links with a pairing code, and the peer holds its agents to the limits they carry", () =>
116 Effect.scoped(
117 Effect.gen(function* () {
118 const b = yield* serveB(box);
119 const a = yield* makeA(laptop);
120​
121 const refused = yield* a.links
122 .link({ url: b.url, pairingCode: "not-a-code", access: "auto" })
123 .pipe(Effect.flip);
124 expect(refused.reason).toBe("pairing_rejected");
125 expect(yield* linkedSessions(b)).toEqual([]);
126​
127 const pairing = yield* b.auth.issuePairingCredential();
128 const linked = yield* a.links.link({
129 url: b.url,
130 pairingCode: pairing.credential,
131 access: "auto",
132 });
133 expect(linked).toMatchObject({
134 environmentId: box.environmentId,
135 label: "Box",
136 urls: [b.url],
137 access: "auto",
138 });
139 // B lists the link under A's name, where it can be revoked.
140 expect((yield* linkedSessions(b)).map((session) => session.client.label)).toEqual([
141 "T3 Code · Laptop",
142 ]);
143 expect(
144 (yield* a.links.list).map(({ environmentId, status }) => [environmentId, status]),
145 ).toEqual([[box.environmentId, "reachable"]]);
146​
147 // The caller's limits narrow the link's access; they never widen it.
148 expect(
149 yield* probe(a, { runtimeMode: "approval-required", interactionMode: "plan" }),
150 ).toEqual({ caller: "T3 Code · Laptop", modes: "approval-required/plan" });
151 expect(yield* probe(a)).toEqual({ caller: "T3 Code · Laptop", modes: "auto/default" });
152​
153 // A refusal keeps the peer's reason.
154 const notFound = yield* probe(a, undefined, "refuse").pipe(Effect.flip);
155 expect(notFound).toMatchObject({ code: "thread_not_found", message: "No such thread." });
156 }),
157 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
158);
159​
160it.effect(
161 "each machine's Linked environments beta gates links, and a link waits while it is off",
162 () =>
163 Effect.scoped(
164 Effect.gen(function* () {
165 const b = yield* serveB(box);
166 const a = yield* makeA(laptop);
167 const pairing = yield* b.auth.issuePairingCredential();
168 const link = a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
169​
170 yield* a.settings.updateSettings({ linkedEnvironmentsEnabled: false });
171 expect(yield* link.pipe(Effect.flip)).toMatchObject({
172 reason: "disabled",
173 message: PeerLinks.LINKED_ENVIRONMENTS_OFF,
174 });
175 expect(yield* Ref.get(b.bearers)).toEqual([]);
176​
177 yield* a.settings.updateSettings({ linkedEnvironmentsEnabled: true });
178 yield* b.settings.updateSettings({ linkedEnvironmentsEnabled: false });
179 const refusedThere = yield* link.pipe(Effect.flip);
180 expect(refusedThere.reason).toBe("pairing_rejected");
181 expect(refusedThere.message).toContain("Linked environments is off on that machine");
182 expect(yield* linkedSessions(b)).toEqual([]);
183​
184 yield* b.settings.updateSettings({ linkedEnvironmentsEnabled: true });
185 yield* link;
186 yield* b.settings.updateSettings({ linkedEnvironmentsEnabled: false });
187 // Not final, so a task already running there picks up again once it is back on.
188 const waiting = yield* probe(a).pipe(Effect.flip);
189 expect(waiting.code).toBe("orchestration_error");
190 expect(waiting.message).toContain("has Linked environments turned off");
191 yield* b.settings.updateSettings({ linkedEnvironmentsEnabled: true });
192 expect(yield* probe(a)).toEqual({ caller: "T3 Code · Laptop", modes: "auto/default" });
193 }),
194 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
195);
196​
197it.effect("a link whose row cannot be stored keeps none of its token", () =>
198 Effect.scoped(
199 Effect.gen(function* () {
200 const b = yield* serveB(box);
201 const held = yield* Ref.make<ReadonlySet<string>>(new Set());
202 const noted = Layer.effect(
203 ServerSecretStore.ServerSecretStore,
204 Effect.map(ServerSecretStore.make, (store) =>
205 ServerSecretStore.ServerSecretStore.of({
206 ...store,
207 set: (name, value) =>
208 store
209 .set(name, value)
210 .pipe(Effect.andThen(Ref.update(held, (names) => new Set([...names, name])))),
211 remove: (name) =>
212 store
213 .remove(name)
214 .pipe(
215 Effect.andThen(
216 Ref.update(held, (names) => new Set([...names].filter((at) => at !== name))),
217 ),
218 ),
219 }),
220 ),
221 );
222 const a = yield* makeA(laptop, noted);
223 yield* a.sql`
224 CREATE TRIGGER refuse_link BEFORE INSERT ON peer_environment_links
225 BEGIN SELECT RAISE(ABORT, 'database or disk is full'); END
226 `;
227 const pairing = yield* b.auth.issuePairingCredential();
228 const failed = yield* a.links
229 .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
230 .pipe(Effect.flip);
231 expect(failed.reason).toBe("storage");
232 expect(yield* Ref.get(held)).toEqual(new Set());
233 }),
234 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
235);
236​
237it.effect("two links racing to one peer leave the stored access matching the token", () =>
238 Effect.scoped(
239 Effect.gen(function* () {
240 const b = yield* serveB(box);
241 const a = yield* makeA(laptop);
242 const [first, second] = yield* Effect.all(
243 [b.auth.issuePairingCredential(), b.auth.issuePairingCredential()],
244 { concurrency: 2 },
245 );
246 yield* Effect.all(
247 [
248 a.links.link({ url: b.url, pairingCode: first.credential, access: "read-only" }),
249 a.links.link({ url: b.url, pairingCode: second.credential, access: "full-access" }),
250 ],
251 { concurrency: 2 },
252 );
253 const [stored] = yield* a.links.list;
254 // The token sent is the one issued with the access the row records.
255 const { modes } = yield* probe(a);
256 expect(modes).toBe(
257 stored!.access === "read-only" ? "approval-required/default" : "full-access/default",
258 );
259 }),
260 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
261);
262​
263/** A bare HTTP server on a socket of its own, answering with `handle`. */
264const serveRaw = <E, R>(
265 handle: (
266 request: HttpServerRequest.HttpServerRequest,
267 ) => Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>,
268) =>
269 Layer.build(Layer.fresh(NodeHttpServer.layerTest)).pipe(
270 Effect.flatMap((server) =>
271 Effect.gen(function* () {
272 yield* HttpServer.serve(Effect.flatMap(HttpServerRequest.HttpServerRequest, handle)).pipe(
273 Layer.build,
274 );
275 const address = (yield* HttpServer.HttpServer).address;
276 if (address._tag === "UnixPathAddress") return yield* Effect.die("expected a TCP address");
277 return `http://127.0.0.1:${address.port}`;
278 }).pipe(Effect.provideContext(server)),
279 ),
280 );
281​
282it.effect("never follows a peer's redirect with the pairing code", () =>
283 Effect.scoped(
284 Effect.gen(function* () {
285 const b = yield* serveB(box);
286 const received = yield* Ref.make<ReadonlyArray<string>>([]);
287 const elsewhere = yield* serveRaw((request) =>
288 Ref.update(received, (seen) => [...seen, `${request.method} ${request.url}`]).pipe(
289 Effect.as(HttpServerResponse.empty({ status: 404 })),
290 ),
291 );
292 // Answers as B, then sends every linking request on to another address.
293 const front = yield* serveRaw((request) =>
294 request.url.startsWith("/.well-known/t3/environment")
295 ? HttpClient.get(`${b.url}${request.url}`).pipe(
296 Effect.flatMap((response) => response.text),
297 Effect.map((body) =>
298 HttpServerResponse.text(body, { contentType: "application/json" }),
299 ),
300 Effect.provide(FetchHttpClient.layer),
301 Effect.orDie,
302 )
303 : Effect.succeed(
304 HttpServerResponse.empty({
305 status: 307,
306 headers: { location: `${elsewhere}${request.url}` },
307 }),
308 ),
309 );
310 const a = yield* makeA(laptop);
311 const pairing = yield* b.auth.issuePairingCredential();
312 yield* a.links
313 .link({ url: front, pairingCode: pairing.credential, access: "auto" })
314 .pipe(Effect.flip);
315 expect(yield* Ref.get(received)).toEqual([]);
316 expect(yield* a.links.list).toEqual([]);
317 }),
318 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
319);
320​
321it.effect("never sends a link's token to an address that stops answering as that peer", () =>
322 Effect.scoped(
323 Effect.gen(function* () {
324 const b = yield* serveB(box);
325 const a = yield* makeA(laptop);
326 const pairing = yield* b.auth.issuePairingCredential();
327 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
328 yield* probe(a);
329 expect((yield* Ref.get(b.bearers)).length).toBeGreaterThan(0);
330​
331 // The address now answers as another environment, as a reused LAN address would.
332 yield* Ref.set(b.descriptor, descriptorOf("environment-impostor", "Impostor"));
333 yield* Ref.set(b.bearers, []);
334 const failed = yield* probe(a).pipe(Effect.flip);
335 expect(failed.message).toContain("Box did not answer");
336 expect(yield* Ref.get(b.bearers)).toEqual([]);
337 expect((yield* a.links.list).map((link) => link.status)).toEqual(["unreachable"]);
338 }),
339 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
340);
341​
342it.effect("reads one stored link without asking the peer", () =>
343 Effect.scoped(
344 Effect.gen(function* () {
345 const b = yield* serveB(box);
346 const a = yield* makeA(laptop);
347 const pairing = yield* b.auth.issuePairingCredential();
348 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
349 yield* Ref.set(b.probes, 0);
350​
351 const stored = yield* a.links.get(box.environmentId);
352 expect(Option.map(stored, (link) => link.label)).toEqual(Option.some("Box"));
353 expect(Option.isNone(yield* a.links.get(laptop.environmentId))).toBe(true);
354 expect(yield* Ref.get(b.probes)).toBe(0);
355 }),
356 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
357);
358​
359it.effect("tells the agent to link again once the peer revokes the link or it expires", () =>
360 Effect.scoped(
361 Effect.gen(function* () {
362 const b = yield* serveB(box);
363 const a = yield* makeA(laptop);
364 const pairing = yield* b.auth.issuePairingCredential();
365 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
366 yield* probe(a);
367​
368 const [session] = yield* linkedSessions(b);
369 yield* b.auth.revokeSession(session!.sessionId);
370 const revoked = yield* probe(a).pipe(Effect.flip);
371 expect(revoked.code).toBe("capability_denied");
372 expect(revoked.message).toContain("revoked there");
373​
374 yield* a.links.link({
375 url: b.url,
376 pairingCode: (yield* b.auth.issuePairingCredential()).credential,
377 access: "auto",
378 });
379 // A link made with a peer that later answers without the fence, as
380 // one made before the fence or a peer moved back to such a version.
381 yield* Ref.set(b.descriptor, descriptorOf("environment-box", "Box", { linkFence: false }));
382 yield* Ref.set(b.bearers, []);
383 const unfenced = yield* probe(a).pipe(Effect.flip);
384 expect(unfenced.code).toBe("capability_denied");
385 expect(unfenced.message).toContain("cannot keep a linked agent's limits");
386 expect(yield* Ref.get(b.bearers)).toEqual([]);
387 yield* Ref.set(b.descriptor, box);
388​
389 // A link stored before links were marked: its session there is not a
390 // link's, so the peer would not fence its work even though it can.
391 yield* a.sql`UPDATE peer_environment_links SET fenced = 0`;
392 // Linking again is its only way back, as for an expired link.
393 expect((yield* a.links.list).map((link) => link.status)).toEqual(["expired"]);
394 const legacy = yield* probe(a).pipe(Effect.flip);
395 expect(legacy.code).toBe("capability_denied");
396 expect(legacy.message).toContain("Link it again");
397 expect(yield* Ref.get(b.bearers)).toEqual([]);
398 yield* a.links.link({
399 url: b.url,
400 pairingCode: (yield* b.auth.issuePairingCredential()).credential,
401 access: "auto",
402 });
403 yield* probe(a);
404​
405 yield* TestClock.adjust(Duration.days(31));
406 expect((yield* a.links.list).map((link) => link.status)).toEqual(["expired"]);
407 yield* Ref.set(b.bearers, []);
408 const expired = yield* probe(a).pipe(Effect.flip);
409 expect(expired.code).toBe("capability_denied");
410 expect(expired.message).toContain("expired");
411 expect(yield* Ref.get(b.bearers)).toEqual([]);
412 }),
413 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
414);
415​
416it.effect(
417 "refuses to link itself, plain http off this machine and the tailnet, or a peer that cannot hold a linked agent to its limits",
418 () =>
419 Effect.scoped(
420 Effect.gen(function* () {
421 const b = yield* serveB(
422 descriptorOf("environment-box", "Box", { mcpModeLimitHeader: false }),
423 );
424 const a = yield* makeA(laptop);
425 const pairing = yield* b.auth.issuePairingCredential();
426 const older = yield* a.links
427 .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
428 .pipe(Effect.flip);
429 expect(older.reason).toBe("incompatible");
430 // Nor one whose link's work could reach the user's own threads there.
431 yield* Ref.set(b.descriptor, descriptorOf("environment-box", "Box", { linkFence: false }));
432 const unfenced = yield* a.links
433 .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
434 .pipe(Effect.flip);
435 expect(unfenced.reason).toBe("incompatible");
436​
437 // Plain http to a LAN address would carry the code and token in clear.
438 const lan = yield* a.links
439 .link({
440 url: "http://192.168.1.20:3773",
441 pairingCode: pairing.credential,
442 access: "auto",
443 })
444 .pipe(Effect.flip);
445 expect(lan.message).toContain("plain http");
446 const lanAlternate = yield* a.links
447 .link({
448 url: b.url,
449 alternateUrls: ["http://192.168.1.20:3773"],
450 pairingCode: pairing.credential,
451 access: "auto",
452 })
453 .pipe(Effect.flip);
454 expect(lanAlternate.message).toContain("plain http");
455​
456 yield* Ref.set(b.descriptor, laptop);
457 const self = yield* a.links
458 .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
459 .pipe(Effect.flip);
460 expect(self.reason).toBe("self");
461 // Neither attempt spent the pairing code on a session.
462 expect(yield* linkedSessions(b)).toEqual([]);
463 }),
464 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
465);
466​
467it.effect(
468 "linking a picked machine skips an address that answers as another, and never signs in there",
469 () =>
470 Effect.scoped(
471 Effect.gen(function* () {
472 const impostor = yield* serveApart(descriptorOf("environment-impostor", "Impostor"));
473 const b = yield* serveB(box);
474 const a = yield* makeA(laptop);
475 const pairing = yield* b.auth.issuePairingCredential();
476 const linked = yield* a.links.link({
477 url: impostor.url,
478 alternateUrls: [b.url],
479 pairingCode: pairing.credential,
480 access: "auto",
481 expectedEnvironmentId: box.environmentId,
482 });
483 expect(linked).toMatchObject({ environmentId: box.environmentId, urls: [b.url] });
484 yield* probe(a);
485 expect(yield* linkedSessions(impostor)).toEqual([]);
486 expect(yield* Ref.get(impostor.bearers)).toEqual([]);
487 expect((yield* linkedSessions(b)).length).toBe(1);
488 }),
489 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
490);
491​
492it.effect("linking a picked machine that answers nowhere names it and links nothing", () =>
493 Effect.scoped(
494 Effect.gen(function* () {
495 const impostor = yield* serveApart(descriptorOf("environment-impostor", "Impostor"));
496 const a = yield* makeA(laptop);
497 const failed = yield* a.links
498 .link({
499 url: impostor.url,
500 alternateUrls: ["http://192.168.1.20:3773"],
501 pairingCode: "unused",
502 access: "auto",
503 expectedEnvironmentId: box.environmentId,
504 expectedLabel: "Box",
505 })
506 .pipe(Effect.flip);
507 expect(failed.reason).toBe("unreachable");
508 expect(failed.message).toBe(
509 `This environment could not reach Box at ${impostor.url}, http://192.168.1.20:3773.`,
510 );
511 expect(yield* a.links.list).toEqual([]);
512 expect(yield* linkedSessions(impostor)).toEqual([]);
513​
514 // Every address refused: the message says why.
515 const refused = yield* a.links
516 .link({
517 url: "http://192.168.1.20:3773",
518 pairingCode: "unused",
519 access: "auto",
520 expectedEnvironmentId: box.environmentId,
521 expectedLabel: "Box",
522 })
523 .pipe(Effect.flip);
524 expect(refused.message).toContain("could not reach Box");
525 expect(refused.message).toContain("plain http");
526 }),
527 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
528);