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

PeerLinks.test.ts

374 lines14.5 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 McpHttpServer from "../mcp/McpHttpServer.ts";
23import * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
24import * as McpToolAccess from "../mcp/McpToolAccess.ts";
25import * as PeerLinks from "./PeerLinks.ts";
26import {
27 descriptorOf,
28 layerLinkingEnvironment,
29 servePeer,
30 type ServedPeer,
31} from "./PeerLinks.testkit.ts";
32import * as PeerMcpClient from "./PeerMcpClient.ts";
33​
34/** What B's probe saw: the calling client and the modes it may start work with. */
35const Probe = Schema.Struct({ caller: Schema.String, modes: Schema.String });
36​
37const ProbeToolkit = Toolkit.make(
38 Tool.make("probe", {
39 description: "Reports the calling client and the modes it may start work with.",
40 success: Probe,
41 failure: OrchestratorMcpFailure,
42 failureMode: "return",
43 dependencies: [McpInvocationContext.McpInvocationContext],
44 }),
45 Tool.make("refuse", {
46 description: "Always refuses.",
47 success: Probe,
48 failure: OrchestratorMcpFailure,
49 failureMode: "return",
50 }),
51);
52​
53const probeHandlers = McpToolAccess.toLayer(ProbeToolkit, {
54 probe: McpToolAccess.reads(() =>
55 McpInvocationContext.McpInvocationContext.pipe(
56 Effect.map((scope) => {
57 const modes = McpInvocationContext.clientModeCeiling(scope.client);
58 return {
59 caller: scope.client?.label ?? "none",
60 modes: `${modes.runtimeMode}/${modes.interactionMode}`,
61 };
62 }),
63 ),
64 ),
65 refuse: McpToolAccess.reads(() =>
66 Effect.fail(
67 new OrchestratorMcpFailure({ code: "thread_not_found", message: "No such thread." }),
68 ),
69 ),
70});
71​
72const serveB = (descriptor: ExecutionEnvironmentDescriptor) =>
73 servePeer(descriptor, McpHttpServer.toolkitRegistration(ProbeToolkit, probeHandlers));
74​
75/** Environment A, which links to B. */
76const makeA = (descriptor: ExecutionEnvironmentDescriptor) =>
77 layerLinkingEnvironment(descriptor).pipe(
78 Layer.build,
79 Effect.map((context) => ({
80 links: Context.get(context, PeerLinks.PeerLinks),
81 peer: Context.get(context, PeerMcpClient.PeerMcpClient),
82 sql: Context.get(context, SqlClient.SqlClient),
83 })),
84 );
85​
86const laptop = descriptorOf("environment-laptop", "Laptop");
87const box = descriptorOf("environment-box", "Box");
88const probe = (
89 a: Effect.Success<ReturnType<typeof makeA>>,
90 limits: PeerMcpClient.PeerCallLimits = { runtimeMode: "full-access", interactionMode: "default" },
91 tool = "probe",
92) =>
93 a.peer.call({
94 environmentId: box.environmentId,
95 tool,
96 arguments: {},
97 limits,
98 success: Probe,
99 });
100​
101const linkedSessions = (b: ServedPeer) => b.linkedSessions;
102​
103it.effect("links with a pairing code, and the peer holds its agents to the limits they carry", () =>
104 Effect.scoped(
105 Effect.gen(function* () {
106 const b = yield* serveB(box);
107 const a = yield* makeA(laptop);
108​
109 const refused = yield* a.links
110 .link({ url: b.url, pairingCode: "not-a-code", access: "auto" })
111 .pipe(Effect.flip);
112 expect(refused.reason).toBe("pairing_rejected");
113 expect(yield* linkedSessions(b)).toEqual([]);
114​
115 const pairing = yield* b.auth.issuePairingCredential();
116 const linked = yield* a.links.link({
117 url: b.url,
118 pairingCode: pairing.credential,
119 access: "auto",
120 });
121 expect(linked).toMatchObject({
122 environmentId: box.environmentId,
123 label: "Box",
124 urls: [b.url],
125 access: "auto",
126 });
127 // B lists the link under A's name, where it can be revoked.
128 expect((yield* linkedSessions(b)).map((session) => session.client.label)).toEqual([
129 "T3 Code · Laptop",
130 ]);
131 expect(
132 (yield* a.links.list).map(({ environmentId, status }) => [environmentId, status]),
133 ).toEqual([[box.environmentId, "reachable"]]);
134​
135 // The caller's limits narrow the link's access; they never widen it.
136 expect(
137 yield* probe(a, { runtimeMode: "approval-required", interactionMode: "plan" }),
138 ).toEqual({ caller: "T3 Code · Laptop", modes: "approval-required/plan" });
139 expect(yield* probe(a)).toEqual({ caller: "T3 Code · Laptop", modes: "auto/default" });
140​
141 // A refusal keeps the peer's reason.
142 const notFound = yield* probe(a, undefined, "refuse").pipe(Effect.flip);
143 expect(notFound).toMatchObject({ code: "thread_not_found", message: "No such thread." });
144 }),
145 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
146);
147​
148it.effect("two links racing to one peer leave the stored access matching the token", () =>
149 Effect.scoped(
150 Effect.gen(function* () {
151 const b = yield* serveB(box);
152 const a = yield* makeA(laptop);
153 const [first, second] = yield* Effect.all(
154 [b.auth.issuePairingCredential(), b.auth.issuePairingCredential()],
155 { concurrency: 2 },
156 );
157 yield* Effect.all(
158 [
159 a.links.link({ url: b.url, pairingCode: first.credential, access: "read-only" }),
160 a.links.link({ url: b.url, pairingCode: second.credential, access: "full-access" }),
161 ],
162 { concurrency: 2 },
163 );
164 const [stored] = yield* a.links.list;
165 // The token sent is the one issued with the access the row records.
166 const { modes } = yield* probe(a);
167 expect(modes).toBe(
168 stored!.access === "read-only" ? "approval-required/default" : "full-access/default",
169 );
170 }),
171 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
172);
173​
174/** A bare HTTP server on a socket of its own, answering with `handle`. */
175const serveRaw = <E, R>(
176 handle: (
177 request: HttpServerRequest.HttpServerRequest,
178 ) => Effect.Effect<HttpServerResponse.HttpServerResponse, E, R>,
179) =>
180 Layer.build(Layer.fresh(NodeHttpServer.layerTest)).pipe(
181 Effect.flatMap((server) =>
182 Effect.gen(function* () {
183 yield* HttpServer.serve(Effect.flatMap(HttpServerRequest.HttpServerRequest, handle)).pipe(
184 Layer.build,
185 );
186 const address = (yield* HttpServer.HttpServer).address;
187 if (address._tag === "UnixPathAddress") return yield* Effect.die("expected a TCP address");
188 return `http://127.0.0.1:${address.port}`;
189 }).pipe(Effect.provideContext(server)),
190 ),
191 );
192​
193it.effect("never follows a peer's redirect with the pairing code", () =>
194 Effect.scoped(
195 Effect.gen(function* () {
196 const b = yield* serveB(box);
197 const received = yield* Ref.make<ReadonlyArray<string>>([]);
198 const elsewhere = yield* serveRaw((request) =>
199 Ref.update(received, (seen) => [...seen, `${request.method} ${request.url}`]).pipe(
200 Effect.as(HttpServerResponse.empty({ status: 404 })),
201 ),
202 );
203 // Answers as B, then sends every linking request on to another address.
204 const front = yield* serveRaw((request) =>
205 request.url.startsWith("/.well-known/t3/environment")
206 ? HttpClient.get(`${b.url}${request.url}`).pipe(
207 Effect.flatMap((response) => response.text),
208 Effect.map((body) =>
209 HttpServerResponse.text(body, { contentType: "application/json" }),
210 ),
211 Effect.provide(FetchHttpClient.layer),
212 Effect.orDie,
213 )
214 : Effect.succeed(
215 HttpServerResponse.empty({
216 status: 307,
217 headers: { location: `${elsewhere}${request.url}` },
218 }),
219 ),
220 );
221 const a = yield* makeA(laptop);
222 const pairing = yield* b.auth.issuePairingCredential();
223 yield* a.links
224 .link({ url: front, pairingCode: pairing.credential, access: "auto" })
225 .pipe(Effect.flip);
226 expect(yield* Ref.get(received)).toEqual([]);
227 expect(yield* a.links.list).toEqual([]);
228 }),
229 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
230);
231​
232it.effect("never sends a link's token to an address that stops answering as that peer", () =>
233 Effect.scoped(
234 Effect.gen(function* () {
235 const b = yield* serveB(box);
236 const a = yield* makeA(laptop);
237 const pairing = yield* b.auth.issuePairingCredential();
238 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
239 yield* probe(a);
240 expect((yield* Ref.get(b.bearers)).length).toBeGreaterThan(0);
241​
242 // The address now answers as another environment, as a reused LAN address would.
243 yield* Ref.set(b.descriptor, descriptorOf("environment-impostor", "Impostor"));
244 yield* Ref.set(b.bearers, []);
245 const failed = yield* probe(a).pipe(Effect.flip);
246 expect(failed.message).toContain("Box did not answer");
247 expect(yield* Ref.get(b.bearers)).toEqual([]);
248 expect((yield* a.links.list).map((link) => link.status)).toEqual(["unreachable"]);
249 }),
250 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
251);
252​
253it.effect("reads one stored link without asking the peer", () =>
254 Effect.scoped(
255 Effect.gen(function* () {
256 const b = yield* serveB(box);
257 const a = yield* makeA(laptop);
258 const pairing = yield* b.auth.issuePairingCredential();
259 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
260 yield* Ref.set(b.probes, 0);
261​
262 const stored = yield* a.links.get(box.environmentId);
263 expect(Option.map(stored, (link) => link.label)).toEqual(Option.some("Box"));
264 expect(Option.isNone(yield* a.links.get(laptop.environmentId))).toBe(true);
265 expect(yield* Ref.get(b.probes)).toBe(0);
266 }),
267 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
268);
269​
270it.effect("tells the agent to link again once the peer revokes the link or it expires", () =>
271 Effect.scoped(
272 Effect.gen(function* () {
273 const b = yield* serveB(box);
274 const a = yield* makeA(laptop);
275 const pairing = yield* b.auth.issuePairingCredential();
276 yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" });
277 yield* probe(a);
278​
279 const [session] = yield* linkedSessions(b);
280 yield* b.auth.revokeSession(session!.sessionId);
281 const revoked = yield* probe(a).pipe(Effect.flip);
282 expect(revoked.code).toBe("capability_denied");
283 expect(revoked.message).toContain("revoked there");
284​
285 yield* a.links.link({
286 url: b.url,
287 pairingCode: (yield* b.auth.issuePairingCredential()).credential,
288 access: "auto",
289 });
290 // A link made with a peer that later answers without the fence, as
291 // one made before the fence or a peer moved back to such a version.
292 yield* Ref.set(b.descriptor, descriptorOf("environment-box", "Box", { linkFence: false }));
293 yield* Ref.set(b.bearers, []);
294 const unfenced = yield* probe(a).pipe(Effect.flip);
295 expect(unfenced.code).toBe("capability_denied");
296 expect(unfenced.message).toContain("cannot keep a linked agent's limits");
297 expect(yield* Ref.get(b.bearers)).toEqual([]);
298 yield* Ref.set(b.descriptor, box);
299​
300 // A link stored before links were marked: its session there is not a
301 // link's, so the peer would not fence its work even though it can.
302 yield* a.sql`UPDATE peer_environment_links SET fenced = 0`;
303 const legacy = yield* probe(a).pipe(Effect.flip);
304 expect(legacy.code).toBe("capability_denied");
305 expect(legacy.message).toContain("Link it again");
306 expect(yield* Ref.get(b.bearers)).toEqual([]);
307 yield* a.links.link({
308 url: b.url,
309 pairingCode: (yield* b.auth.issuePairingCredential()).credential,
310 access: "auto",
311 });
312 yield* probe(a);
313​
314 yield* TestClock.adjust(Duration.days(31));
315 expect((yield* a.links.list).map((link) => link.status)).toEqual(["expired"]);
316 yield* Ref.set(b.bearers, []);
317 const expired = yield* probe(a).pipe(Effect.flip);
318 expect(expired.code).toBe("capability_denied");
319 expect(expired.message).toContain("expired");
320 expect(yield* Ref.get(b.bearers)).toEqual([]);
321 }),
322 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
323);
324​
325it.effect(
326 "refuses to link itself, plain http off this machine and the tailnet, or a peer that cannot hold a linked agent to its limits",
327 () =>
328 Effect.scoped(
329 Effect.gen(function* () {
330 const b = yield* serveB(
331 descriptorOf("environment-box", "Box", { mcpModeLimitHeader: false }),
332 );
333 const a = yield* makeA(laptop);
334 const pairing = yield* b.auth.issuePairingCredential();
335 const older = yield* a.links
336 .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
337 .pipe(Effect.flip);
338 expect(older.reason).toBe("incompatible");
339 // Nor one whose link's work could reach the user's own threads there.
340 yield* Ref.set(b.descriptor, descriptorOf("environment-box", "Box", { linkFence: false }));
341 const unfenced = yield* a.links
342 .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
343 .pipe(Effect.flip);
344 expect(unfenced.reason).toBe("incompatible");
345​
346 // Plain http to a LAN address would carry the code and token in clear.
347 const lan = yield* a.links
348 .link({
349 url: "http://192.168.1.20:3773",
350 pairingCode: pairing.credential,
351 access: "auto",
352 })
353 .pipe(Effect.flip);
354 expect(lan.message).toContain("plain http");
355 const lanAlternate = yield* a.links
356 .link({
357 url: b.url,
358 alternateUrls: ["http://192.168.1.20:3773"],
359 pairingCode: pairing.credential,
360 access: "auto",
361 })
362 .pipe(Effect.flip);
363 expect(lanAlternate.message).toContain("plain http");
364​
365 yield* Ref.set(b.descriptor, laptop);
366 const self = yield* a.links
367 .link({ url: b.url, pairingCode: pairing.credential, access: "auto" })
368 .pipe(Effect.flip);
369 expect(self.reason).toBe("self");
370 // Neither attempt spent the pairing code on a session.
371 expect(yield* linkedSessions(b)).toEqual([]);
372 }),
373 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
374);