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

PeerClientPairing.test.ts

332 lines12.8 KB

1import { NodeHttpServer } from "@effect/platform-node";
2import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3import {
4 AuthAccessWriteScope,
5 type AuthEnvironmentScope,
6 type AuthMcpClientAccess,
7 AuthOrchestrationOperateScope,
8 AuthOrchestrationReadScope,
9 AuthRelayConfigureScope,
10 AuthStandardClientScopes,
11 AuthTerminalOperateScope,
12 type ExecutionEnvironmentDescriptor,
13 ProviderInstanceId,
14 ThreadId,
15} from "@t3tools/contracts";
16import { expect, it } from "@effect/vitest";
17import * as Context from "effect/Context";
18import * as Effect from "effect/Effect";
19import * as Layer from "effect/Layer";
20import * as Ref from "effect/Ref";
21import * as FetchHttpClient from "effect/http/FetchHttpClient";
22import * as HttpBody from "effect/http/HttpBody";
23import * as HttpClient from "effect/http/HttpClient";
24import * as HttpClientRequest from "effect/http/HttpClientRequest";
25import * as TestClock from "effect/testing/TestClock";
26import { Toolkit } from "effect/ai";
27​
28import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
29import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
30import * as McpHttpServer from "../mcp/McpHttpServer.ts";
31import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
32import * as McpToolAccess from "../mcp/McpToolAccess.ts";
33import * as ServerSettings from "../serverSettings.ts";
34import * as PeerClientPairing from "./PeerClientPairing.ts";
35import * as PeerLinks from "./PeerLinks.ts";
36import {
37 descriptorOf,
38 layerEnvironmentAuth,
39 layerLinkingEnvironment,
40 linkTo,
41 type ServedPeer,
42 servePeer,
43} from "./PeerLinks.testkit.ts";
44​
45const laptop = descriptorOf("environment-laptop", "Laptop");
46const box = descriptorOf("environment-box", "Box", {
47 linkClientPairing: true,
48 linkPairingForLink: true,
49});
50const NoTools = Toolkit.make();
51​
52const serveBox = (descriptor: ExecutionEnvironmentDescriptor = box) =>
53 servePeer(
54 descriptor,
55 McpHttpServer.toolkitRegistration(NoTools, McpToolAccess.toLayer(NoTools, {})),
56 );
57​
58/** The laptop: its links, its own clients, and what answers a client asking to pair with a link. */
59const makeLaptop = Effect.gen(function* () {
60 const linking = yield* Layer.build(layerLinkingEnvironment(laptop));
61 const authContext = yield* Layer.build(layerEnvironmentAuth("t3-peer-link-here-auth-"));
62 const auth = Context.get(authContext, EnvironmentAuth.EnvironmentAuth);
63 const pairing = yield* PeerClientPairing.layer.pipe(
64 Layer.provide(Layer.succeedContext(linking)),
65 Layer.provide(Layer.succeed(EnvironmentAuth.EnvironmentAuth, auth)),
66 Layer.provide(FetchHttpClient.layer),
67 Layer.build,
68 );
69 return {
70 links: Context.get(linking, PeerLinks.PeerLinks),
71 settings: Context.get(linking, ServerSettings.ServerSettingsService),
72 pairing: Context.get(pairing, PeerClientPairing.PeerClientPairing),
73 /** A client paired with the laptop, such as a phone. */
74 client: (scopes: ReadonlyArray<AuthEnvironmentScope>) =>
75 auth.issueSession({ scopes, label: "Phone" }),
76 };
77});
78​
79const metadata = { deviceType: "mobile" as const };
80​
81/** Asks the box's route directly, as anything holding `bearer` could, and answers its status. */
82const askBox = (b: ServedPeer, bearer: string | undefined, headers: Record<string, string> = {}) =>
83 HttpClient.execute(
84 HttpClientRequest.post(`${b.url}/api/peer-link/client-pairing`).pipe(
85 HttpClientRequest.setHeaders({
86 ...(bearer === undefined ? {} : { authorization: `Bearer ${bearer}` }),
87 ...headers,
88 }),
89 HttpClientRequest.setBody(
90 HttpBody.text(
91 JSON.stringify({ scopes: AuthStandardClientScopes, clientLabel: "Phone" }),
92 "application/json",
93 ),
94 ),
95 ),
96 ).pipe(
97 Effect.map((response) => response.status),
98 Effect.provide(FetchHttpClient.layer),
99 );
100​
101const linkTokenOf = (a: Effect.Success<typeof makeLaptop>) =>
102 a.links.resolve(box.environmentId).pipe(Effect.map((resolved) => resolved.token));
103​
104it.effect(
105 "a full-access link gets a client one pairing, with no more than the client holds here",
106 () =>
107 Effect.scoped(
108 Effect.gen(function* () {
109 const b = yield* serveBox();
110 const a = yield* makeLaptop;
111 yield* linkTo(a.links, b, "full-access");
112 // Holds less than a pairing code grants, and one scope no pairing code grants.
113 const held = [
114 AuthOrchestrationReadScope,
115 AuthOrchestrationOperateScope,
116 AuthAccessWriteScope,
117 AuthRelayConfigureScope,
118 ];
119 const phone = yield* a.client(held);
120​
121 const result = yield* a.pairing.request({ environmentId: box.environmentId }, phone);
122 if (result.type !== "credential") return yield* Effect.die(result);
123 expect(result).toMatchObject({
124 environmentId: box.environmentId,
125 label: "Box",
126 urls: [b.url],
127 });
128 // The box's Connections says where the pairing came from, and can revoke it.
129 expect(yield* b.auth.listPairingLinks()).toMatchObject([{ label: "Phone · via Laptop" }]);
130​
131 const session = yield* b.auth.exchangeBootstrapCredentialForAccessToken(
132 result.credential,
133 undefined,
134 metadata,
135 );
136 expect(new Set(session.scope.split(" "))).toEqual(
137 new Set([
138 AuthOrchestrationReadScope,
139 AuthOrchestrationOperateScope,
140 AuthAccessWriteScope,
141 ]),
142 );
143 expect(session.scope).not.toContain(AuthTerminalOperateScope);
144 const again = yield* b.auth
145 .exchangeBootstrapCredentialForAccessToken(result.credential, undefined, metadata)
146 .pipe(Effect.flip);
147 expect(again._tag).toBe("ServerAuthInvalidCredentialError");
148​
149 // One the client never redeems is gone within minutes.
150 const unused = yield* a.pairing.request({ environmentId: box.environmentId }, phone);
151 if (unused.type !== "credential") return yield* Effect.die(unused);
152 yield* TestClock.adjust("3 minutes");
153 const late = yield* b.auth
154 .exchangeBootstrapCredentialForAccessToken(unused.credential, undefined, metadata)
155 .pipe(Effect.flip);
156 expect(late._tag).toBe("ServerAuthInvalidCredentialError");
157 }),
158 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
159);
160​
161it.effect.each(["read-only", "approval-required", "auto"] as const)(
162 "a %s link cannot pair a client, even when the linking environment is bypassed",
163 (access: AuthMcpClientAccess) =>
164 Effect.scoped(
165 Effect.gen(function* () {
166 const b = yield* serveBox();
167 const a = yield* makeLaptop;
168 yield* linkTo(a.links, b, access);
169 const phone = yield* a.client(AuthStandardClientScopes);
170​
171 expect(yield* a.pairing.request({ environmentId: box.environmentId }, phone)).toEqual({
172 type: "unsupported",
173 reason: "link_access",
174 environmentId: box.environmentId,
175 label: "Box",
176 urls: [b.url],
177 });
178 expect(yield* Ref.get(b.bearers)).toEqual([]);
179​
180 expect(yield* askBox(b, yield* linkTokenOf(a))).toBe(403);
181 expect(yield* b.auth.listPairingLinks()).toEqual([]);
182 }),
183 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
184);
185​
186it.effect("only a full-access link's own session reaches the box's pairing route", () =>
187 Effect.scoped(
188 Effect.gen(function* () {
189 const b = yield* serveBox();
190 const a = yield* makeLaptop;
191 yield* linkTo(a.links, b, "full-access");
192 const linkToken = yield* linkTokenOf(a);
193​
194 // An outside agent approved at full access is not a link.
195 const agent = yield* b.auth.issueMcpClientSession({
196 label: "Outside agent",
197 access: "full-access",
198 peerLink: false,
199 client: { deviceType: "bot" },
200 });
201 expect(yield* askBox(b, agent.token)).toBe(403);
202​
203 // An agent's thread credential, which a link-started agent holds too, is not a session.
204 const registry = yield* McpSessionRegistry.layer.pipe(
205 Layer.provide(
206 Layer.succeed(ServerEnvironment.ServerEnvironment, {
207 getEnvironmentId: Effect.succeed(box.environmentId),
208 getDescriptor: Effect.succeed(box),
209 }),
210 ),
211 Layer.provide(NodeCrypto.layer),
212 Layer.build,
213 );
214 const thread = yield* Context.get(registry, McpSessionRegistry.McpSessionRegistry).issue({
215 threadId: ThreadId.make("thread:box-link-started"),
216 providerInstanceId: ProviderInstanceId.make("codex"),
217 });
218 expect(yield* askBox(b, thread.config.authorizationHeader.slice("Bearer ".length))).toBe(401);
219​
220 // The box's own administrator client pairs devices from Connections, not from here.
221 const owner = yield* b.auth.issueSession({ scopes: AuthStandardClientScopes });
222 expect(yield* askBox(b, owner.token)).toBe(401);
223 expect(yield* askBox(b, undefined)).toBe(401);
224 // A page in a browser never holds a link's token.
225 expect(yield* askBox(b, linkToken, { origin: "https://example.com" })).toBe(403);
226 expect(yield* b.auth.listPairingLinks()).toEqual([]);
227​
228 expect(yield* askBox(b, linkToken)).toBe(200);
229 }),
230 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
231);
232​
233it.effect("pairs no client while Linked environments is off on either side", () =>
234 Effect.scoped(
235 Effect.gen(function* () {
236 const b = yield* serveBox();
237 const a = yield* makeLaptop;
238 yield* linkTo(a.links, b, "full-access");
239 const phone = yield* a.client(AuthStandardClientScopes);
240 const linkToken = yield* linkTokenOf(a);
241​
242 yield* b.settings.updateSettings({ linkedEnvironmentsEnabled: false });
243 expect(yield* askBox(b, linkToken)).toBe(403);
244 expect(yield* a.pairing.request({ environmentId: box.environmentId }, phone)).toMatchObject({
245 type: "unsupported",
246 reason: "refused",
247 });
248 yield* b.settings.updateSettings({ linkedEnvironmentsEnabled: true });
249​
250 yield* a.settings.updateSettings({ linkedEnvironmentsEnabled: false });
251 const off = yield* a.pairing
252 .request({ environmentId: box.environmentId }, phone)
253 .pipe(Effect.flip);
254 expect(off.reason).toBe("disabled");
255 expect(yield* b.auth.listPairingLinks()).toEqual([]);
256 }),
257 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
258);
259​
260it.effect("a full-access link gets a pairing code that links another environment to the box", () =>
261 Effect.scoped(
262 Effect.gen(function* () {
263 const b = yield* serveBox();
264 const a = yield* makeLaptop;
265 yield* linkTo(a.links, b, "full-access");
266 const phone = yield* a.client([AuthAccessWriteScope]);
267​
268 const result = yield* a.pairing.requestForLink(
269 { environmentId: box.environmentId, access: "approval-required" },
270 phone,
271 );
272 if (result.type !== "credential") return yield* Effect.die(result);
273 expect(result).toMatchObject({ environmentId: box.environmentId, urls: [b.url] });
274​
275 // A third environment links with it, at the access the code was minted for.
276 const desk = yield* Layer.build(
277 layerLinkingEnvironment(descriptorOf("environment-desk", "Desk")),
278 );
279 const linked = yield* Context.get(desk, PeerLinks.PeerLinks).link({
280 url: b.url,
281 pairingCode: result.credential,
282 access: "approval-required",
283 });
284 expect(linked).toMatchObject({
285 environmentId: box.environmentId,
286 access: "approval-required",
287 });
288 }),
289 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
290);
291​
292it.effect("a linked environment from before link pairing is never asked for one", () =>
293 Effect.scoped(
294 Effect.gen(function* () {
295 const b = yield* serveBox(
296 descriptorOf("environment-box", "Box", { linkClientPairing: true }),
297 );
298 const a = yield* makeLaptop;
299 yield* linkTo(a.links, b, "full-access");
300 const phone = yield* a.client([AuthAccessWriteScope]);
301​
302 // It would read the request as a client's and hand back a client pairing.
303 expect(
304 yield* a.pairing.requestForLink(
305 { environmentId: box.environmentId, access: "auto" },
306 phone,
307 ),
308 ).toMatchObject({ type: "unsupported", reason: "version" });
309 expect(yield* Ref.get(b.bearers)).toEqual([]);
310 }),
311 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
312);
313​
314it.effect("a linked environment from before client pairing is never asked", () =>
315 Effect.scoped(
316 Effect.gen(function* () {
317 const b = yield* serveBox(descriptorOf("environment-box", "Box"));
318 const a = yield* makeLaptop;
319 yield* linkTo(a.links, b, "full-access");
320 const phone = yield* a.client(AuthStandardClientScopes);
321​
322 expect(yield* a.pairing.request({ environmentId: box.environmentId }, phone)).toEqual({
323 type: "unsupported",
324 reason: "version",
325 environmentId: box.environmentId,
326 label: "Box",
327 urls: [b.url],
328 });
329 expect(yield* Ref.get(b.bearers)).toEqual([]);
330 }),
331 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
332);