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

McpOAuth.test.ts

972 lines37.4 KB

1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import {
4 AuthMcpClientAccess,
5 AuthStandardClientScopes,
6 type AuthCreatePairingCredentialInput,
7 type EnvironmentCloudLinkStateResult,
8 EnvironmentHttpApi,
9 MCP_PEER_LINK_SOFTWARE_ID,
10 mcpClientScopes,
11} from "@t3tools/contracts";
12import { expect, it } from "@effect/vitest";
13import * as Clock from "effect/Clock";
14import * as Context from "effect/Context";
15import * as SecureRandom from "effect/crypto/SecureRandom";
16import * as Effect from "effect/Effect";
17import * as Layer from "effect/Layer";
18import * as Etag from "effect/http/Etag";
19import * as HttpPlatform from "effect/http/HttpPlatform";
20import * as HttpRouter from "effect/http/HttpRouter";
21import * as HttpServerRequest from "effect/http/HttpServerRequest";
22import * as HttpApi from "effect/http-api/HttpApi";
23import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
24import * as Schema from "effect/Schema";
25​
26import * as CloudLink from "../cloud/CloudLink.ts";
27import * as ServerConfig from "../config.ts";
28import { makeDpopKey } from "./dpop.testkit.ts";
29import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
30import * as ServerHttp from "../http.ts";
31import * as ServerSettings from "../serverSettings.ts";
32import * as Sqlite from "../persistence/Sqlite.ts";
33import * as EnvironmentAuth from "./EnvironmentAuth.ts";
34import * as McpOAuth from "./McpOAuth.ts";
35import * as McpOAuthHttp from "./mcpOAuthHttp.ts";
36import * as ServerSecretStore from "./ServerSecretStore.ts";
37import * as AuthHttp from "./http.ts";
38import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
39​
40class AuthTestApi extends HttpApi.make("environment")
41 .add(EnvironmentHttpApi.groups.auth)
42 .add(EnvironmentHttpApi.groups.mcpOAuth) {}
43​
44const layerConfig = ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-oauth-test-" });
45const layerEnvironmentAuth = EnvironmentAuth.layer.pipe(
46 Layer.provide(ManagedPolicy.layerTest()),
47 Layer.provide(Sqlite.layerMemory),
48 Layer.provideMerge(ServerSecretStore.layer),
49 Layer.provideMerge(ServerEnvironment.layerIdentity),
50 Layer.provide(layerConfig),
51);
52const notLinked: EnvironmentCloudLinkStateResult = {
53 linked: false,
54 cloudUserId: null,
55 relayUrl: null,
56 relayIssuer: null,
57 publishAgentActivity: false,
58};
59const makeLayerRoutes = (
60 capture: (auth: EnvironmentAuth.EnvironmentAuth["Service"]) => void,
61 linkState: EnvironmentCloudLinkStateResult,
62) =>
63 Layer.mergeAll(
64 Layer.effectDiscard(
65 EnvironmentAuth.EnvironmentAuth.pipe(Effect.tap((auth) => Effect.sync(() => capture(auth)))),
66 ),
67 HttpApiBuilder.layer(AuthTestApi).pipe(
68 Layer.provide(AuthHttp.layer),
69 Layer.provide(
70 McpOAuthHttp.layer.pipe(
71 Layer.provide(McpOAuth.layer),
72 Layer.provide(ServerSettings.layerTest({ linkedEnvironmentsEnabled: true })),
73 Layer.provide(
74 Layer.mock(CloudLink.CloudLink)({ linkState: () => Effect.succeed(linkState) }),
75 ),
76 ),
77 ),
78 Layer.provide(AuthHttp.layerAuthenticatedAuth),
79 Layer.provide(ServerHttp.layerApiBodyLimit),
80 ),
81 ).pipe(
82 Layer.provideMerge(layerEnvironmentAuth),
83 Layer.provide(layerConfig),
84 Layer.provideMerge(
85 HttpPlatform.layer.pipe(
86 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
87 Layer.provideMerge(Etag.layerWeak),
88 ),
89 ),
90 Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
91 );
92​
93const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
94const ORIGIN = "https://box.example.ts.net";
95const REDIRECT = "http://localhost/callback";
96const verifier = "a".repeat(43) + "-verifier-for-tests";
97const challenge = "DeB41nTVkPwpbbYecrnqtVq7VXLezustdHAK4SWt13c";
98​
99const at = (path: string, init?: RequestInit) =>
100 new Request(`http://127.0.0.1${path}`, {
101 ...init,
102 headers: { host: "box.example.ts.net", "x-forwarded-proto": "https", ...init?.headers },
103 });
104const form = (body: Record<string, string>) => ({
105 method: "POST",
106 headers: { "content-type": "application/x-www-form-urlencoded" },
107 body: new URLSearchParams(body).toString(),
108});
109​
110type Handler = (request: Request) => Effect.Effect<Response>;
111​
112const withRoutes = <A, E>(
113 use: (handler: Handler, auth: EnvironmentAuth.EnvironmentAuth["Service"]) => Effect.Effect<A, E>,
114 linkState = notLinked,
115) =>
116 Effect.gen(function* () {
117 const random = yield* SecureRandom.SecureRandom;
118 const context = Context.make(SecureRandom.SecureRandom, random);
119 let routerAuth: EnvironmentAuth.EnvironmentAuth["Service"] | undefined;
120 const layerRoutes = makeLayerRoutes((auth) => {
121 routerAuth = auth;
122 }, linkState);
123 return yield* Effect.acquireUseRelease(
124 Effect.sync(() => HttpRouter.toWebHandler(layerRoutes, { disableLogger: true })),
125 (web) =>
126 Effect.gen(function* () {
127 const handler: Handler = (request) => Effect.promise(() => web.handler(request, context));
128 yield* handler(at("/.well-known/oauth-authorization-server"));
129 return yield* use(handler, routerAuth!);
130 }),
131 (web) => Effect.promise(() => web.dispose()),
132 );
133 }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)));
134​
135const json = <A>(response: Response) => Effect.promise(() => response.json() as Promise<A>);
136​
137/** `credential` is a browser cookie, `Bearer <token>`, or the headers of a DPoP request. */
138const postJson = (path: string, body: unknown, credential?: string | Record<string, string>) =>
139 at(path, {
140 method: "POST",
141 headers: {
142 "content-type": "application/json",
143 ...(credential === undefined
144 ? {}
145 : typeof credential !== "string"
146 ? credential
147 : credential.startsWith("Bearer ")
148 ? { authorization: credential }
149 : { cookie: credential }),
150 },
151 body: encodeJson(body),
152 });
153​
154const decide = (
155 handler: Handler,
156 authorization: Record<string, string>,
157 decision: Record<string, string>,
158 cookie?: string | Record<string, string>,
159) =>
160 handler(postJson("/oauth/mcp/decision", { authorization, decision }, cookie)).pipe(
161 Effect.flatMap((response) =>
162 json<{ redirectTo?: string; message?: string }>(response).pipe(
163 Effect.map((payload) => ({ status: response.status, ...payload })),
164 ),
165 ),
166 );
167​
168const register = (handler: Handler, redirect = REDIRECT) =>
169 handler(
170 at("/oauth/mcp/register", {
171 method: "POST",
172 headers: { "content-type": "application/json" },
173 body: encodeJson({
174 client_name: "Claude Code",
175 redirect_uris: [redirect],
176 grant_types: ["authorization_code", "refresh_token"],
177 token_endpoint_auth_method: "none",
178 }),
179 }),
180 );
181​
182const registeredClientId = (handler: Handler) =>
183 register(handler).pipe(
184 Effect.flatMap((response) => json<{ client_id: string }>(response)),
185 Effect.map((body) => body.client_id),
186 );
187​
188const authorizeParams = (clientId: string, redirect = "http://localhost:51234/callback") => ({
189 response_type: "code",
190 client_id: clientId,
191 redirect_uri: redirect,
192 code_challenge: challenge,
193 code_challenge_method: "S256",
194 state: "state-1",
195 resource: `${ORIGIN}/mcp`,
196});
197​
198it.effect("derives discovery metadata from the origin the client reached", () =>
199 withRoutes((handler) =>
200 Effect.gen(function* () {
201 const resource = yield* handler(at("/.well-known/oauth-protected-resource/mcp"));
202 expect(yield* json<unknown>(resource)).toMatchObject({
203 resource: `${ORIGIN}/mcp`,
204 authorization_servers: [ORIGIN],
205 });
206 const server = yield* json<unknown>(
207 yield* handler(at("/.well-known/oauth-authorization-server")),
208 );
209 expect(server).toMatchObject({
210 issuer: ORIGIN,
211 authorization_endpoint: `${ORIGIN}/oauth/mcp/authorize`,
212 token_endpoint: `${ORIGIN}/oauth/mcp/token`,
213 registration_endpoint: `${ORIGIN}/oauth/mcp/register`,
214 revocation_endpoint: `${ORIGIN}/oauth/mcp/revoke`,
215 code_challenge_methods_supported: ["S256"],
216 });
217 }),
218 ),
219);
220​
221it.effect("answers 413 to a body over the API limit", () =>
222 withRoutes((handler) =>
223 Effect.gen(function* () {
224 const body = "x".repeat(ServerHttp.API_MAX_BODY_BYTES + 1);
225 for (const [path, contentType] of [
226 ["/api/auth/browser-session", "application/json"],
227 ["/oauth/token", "application/x-www-form-urlencoded"],
228 ["/oauth/mcp/register", "application/json"],
229 ]) {
230 const init = { method: "POST", headers: { "content-type": contentType! } };
231 expect((yield* handler(at(path!, { ...init, body }))).status, path).toBe(413);
232 // A chunked body declares no length, so the reader itself has to stop.
233 const chunked = new Blob([body]).stream();
234 const streamed = at(path!, { ...init, body: chunked, duplex: "half" } as RequestInit);
235 expect((yield* handler(streamed)).status, `${path} chunked`).toBe(413);
236 }
237 }),
238 ),
239);
240​
241it.effect("registers loopback and https clients and never redirects for an unverified client", () =>
242 withRoutes((handler) =>
243 Effect.gen(function* () {
244 for (const refused of [
245 "http://bot.example/callback",
246 "https://user:pass@bot.example/callback",
247 "https://bot.example/callback#",
248 "http://localhost/callback#",
249 "javascript:alert(1)",
250 ]) {
251 const response = yield* register(handler, refused);
252 expect(response.status).toBe(400);
253 expect(yield* json<unknown>(response)).toMatchObject({ error: "invalid_redirect_uri" });
254 }
255 // JSON escaping can inflate the signed client_id past what an authorize URL can carry.
256 const oversized = yield* handler(
257 at("/oauth/mcp/register", {
258 method: "POST",
259 headers: { "content-type": "application/json" },
260 body: encodeJson({
261 redirect_uris: Array.from(
262 { length: 10 },
263 (_, index) => `https://bot.example/${index}/${'"'.repeat(480)}`,
264 ),
265 }),
266 }),
267 );
268 expect(oversized.status).toBe(400);
269 const fiveLongCallbacks = yield* handler(
270 at("/oauth/mcp/register", {
271 method: "POST",
272 headers: { "content-type": "application/json" },
273 body: encodeJson({
274 client_name: "A".repeat(100),
275 redirect_uris: Array.from(
276 { length: 5 },
277 (_, index) => `https://a.co/${index}/${"界".repeat(497)}`,
278 ),
279 }),
280 }),
281 );
282 expect(fiveLongCallbacks.status).toBe(201);
283​
284 for (const malformed of [
285 { client_name: 42, redirect_uris: [REDIRECT] },
286 { redirect_uris: REDIRECT },
287 ]) {
288 const response = yield* handler(postJson("/oauth/mcp/register", malformed));
289 expect(response.status).toBe(400);
290 expect(response.headers.get("content-type")).toMatch(/^application\/json/);
291 expect(yield* json<{ error: string }>(response)).toMatchObject({
292 error: expect.stringMatching(/^invalid_(client_metadata|redirect_uri)$/),
293 });
294 }
295​
296 const registered = yield* register(handler);
297 expect(registered.status).toBe(201);
298 const { client_id: clientId } = (yield* json<unknown>(registered)) as { client_id: string };
299​
300 const forged = yield* handler(
301 at(
302 `/oauth/mcp/authorize?${new URLSearchParams(authorizeParams(`${clientId.split(".")[0]}.forged`))}`,
303 ),
304 );
305 expect(forged.status).toBe(400);
306 expect(forged.headers.get("location")).toBeNull();
307​
308 const unregistered = yield* handler(
309 at(
310 `/oauth/mcp/authorize?${new URLSearchParams(
311 authorizeParams(clientId, "http://localhost:51234/elsewhere"),
312 )}`,
313 ),
314 );
315 expect(unregistered.status).toBe(400);
316 expect(unregistered.headers.get("location")).toBeNull();
317​
318 for (const resource of [`${ORIGIN}/mcp#section`, `${ORIGIN}/mcp#`]) {
319 const wrongTarget = yield* handler(
320 at(
321 `/oauth/mcp/authorize?${new URLSearchParams({ ...authorizeParams(clientId), resource })}`,
322 ),
323 );
324 expect(wrongTarget.status).toBe(302);
325 const location = new URL(wrongTarget.headers.get("location")!, ORIGIN);
326 expect(location.searchParams.get("error"), resource).toBe("invalid_target");
327 }
328​
329 const query = new URLSearchParams(authorizeParams(clientId)).toString();
330 const handoff = yield* handler(at(`/oauth/mcp/authorize?${query}`));
331 expect(handoff.status).toBe(302);
332 expect(handoff.headers.get("location")).toBe(`/connect-agent?${query}`);
333 const details = yield* handler(
334 postJson("/oauth/mcp/approval", authorizeParams(clientId)),
335 ).pipe(Effect.flatMap(json<Record<string, unknown>>));
336 expect(details).toEqual({
337 clientName: "Claude Code",
338 redirectHost: "localhost:51234",
339 environmentHost: "box.example.ts.net",
340 });
341​
342 const forgedDetails = yield* handler(
343 postJson("/oauth/mcp/approval", authorizeParams(`${clientId.split(".")[0]}.forged`)),
344 );
345 expect(forgedDetails.status).toBe(400);
346 expect(yield* json<Record<string, unknown>>(forgedDetails)).not.toHaveProperty("redirectTo");
347 }),
348 ),
349);
350​
351it.live("signs in with a pairing code and issues a token only /mcp accepts", () =>
352 withRoutes((handler, auth) =>
353 Effect.gen(function* () {
354 const clientId = yield* registeredClientId(handler);
355 const pairing = yield* auth.issuePairingCredential();
356 const params = authorizeParams(clientId);
357​
358 const wrongCode = yield* decide(handler, params, {
359 _tag: "pairing-code",
360 access: "auto",
361 code: "nope",
362 });
363 expect(wrongCode.status).toBe(400);
364 expect(wrongCode.message).toContain("unknown, expired, or already used");
365​
366 const approved = yield* decide(handler, params, {
367 _tag: "pairing-code",
368 access: "auto",
369 code: pairing.credential,
370 });
371 expect(approved.status).toBe(200);
372 const callback = new URL(approved.redirectTo!);
373 expect(callback.origin).toBe("http://localhost:51234");
374 expect(callback.searchParams.get("state")).toBe("state-1");
375 expect(callback.searchParams.get("iss")).toBe(ORIGIN);
376 const code = callback.searchParams.get("code")!;
377​
378 const exchange = (codeVerifier: string) =>
379 handler(
380 at(
381 "/oauth/mcp/token",
382 form({
383 grant_type: "authorization_code",
384 code,
385 redirect_uri: params.redirect_uri,
386 client_id: clientId,
387 code_verifier: codeVerifier,
388 resource: `${ORIGIN}/mcp`,
389 }),
390 ),
391 );
392 const tokenResponse = yield* exchange(verifier);
393 expect(tokenResponse.status).toBe(200);
394 const token = (yield* json<unknown>(tokenResponse)) as {
395 access_token: string;
396 scope: string;
397 };
398 expect(token.scope).toBe("orchestration:read orchestration:operate");
399​
400 expect((yield* exchange(verifier)).status).toBe(400);
401​
402 for (const scheme of ["Bearer", "bearer", "bEaReR"]) {
403 const client = yield* auth.authenticateMcpClient(
404 HttpServerRequest.fromWeb(
405 at("/mcp", { headers: { authorization: `${scheme} ${token.access_token}` } }),
406 ),
407 );
408 expect(client).toMatchObject({ label: "Claude Code", access: "auto" });
409 }
410​
411 const session = yield* handler(
412 at("/api/auth/session", { headers: { authorization: `Bearer ${token.access_token}` } }),
413 );
414 expect(yield* json<unknown>(session)).toMatchObject({ authenticated: false });
415 const ticket = yield* handler(
416 at("/api/auth/websocket-ticket", {
417 method: "POST",
418 headers: { authorization: `Bearer ${token.access_token}` },
419 }),
420 );
421 expect(ticket.status).toBe(401);
422​
423 // Revocation ends only an MCP client's own session; any other token is answered alike and kept.
424 const owner = yield* auth.exchangeBootstrapCredentialForAccessToken(
425 (yield* auth.issuePairingCredential()).credential,
426 undefined,
427 { deviceType: "desktop" },
428 );
429 const bearer = (token: string) =>
430 HttpServerRequest.fromWeb(at("/api", { headers: { authorization: `Bearer ${token}` } }));
431 for (const other of ["not-a-token", owner.access_token]) {
432 expect((yield* handler(at("/oauth/mcp/revoke", form({ token: other })))).status).toBe(200);
433 }
434 yield* auth.authenticateHttpRequest(bearer(owner.access_token));
435 const revoked = yield* handler(at("/oauth/mcp/revoke", form({ token: token.access_token })));
436 expect(revoked.status).toBe(200);
437 yield* auth.authenticateMcpClient(bearer(token.access_token)).pipe(Effect.flip);
438 }),
439 ),
440);
441​
442it.live("signs in a hosted agent with an https callback that asked for a client secret", () =>
443 withRoutes((handler, auth) =>
444 Effect.gen(function* () {
445 const callbackUrl = "https://bot.example/oauth/callback";
446 const registered = yield* handler(
447 at("/oauth/mcp/register", {
448 method: "POST",
449 headers: { "content-type": "application/json" },
450 body: encodeJson({
451 client_name: "Hosted bot",
452 redirect_uris: [callbackUrl],
453 token_endpoint_auth_method: "client_secret_post",
454 }),
455 }),
456 );
457 expect(registered.status).toBe(201);
458 const client = (yield* json<unknown>(registered)) as {
459 client_id: string;
460 token_endpoint_auth_method: string;
461 };
462 expect(client.token_endpoint_auth_method).toBe("none");
463​
464 const params = authorizeParams(client.client_id, callbackUrl);
465 const details = yield* handler(postJson("/oauth/mcp/approval", params)).pipe(
466 Effect.flatMap(json<Record<string, unknown>>),
467 );
468 expect(details).toMatchObject({ clientName: "Hosted bot", redirectHost: "bot.example" });
469​
470 const pairing = yield* auth.issuePairingCredential();
471 const approved = yield* decide(handler, params, {
472 _tag: "pairing-code",
473 access: "approval-required",
474 code: pairing.credential,
475 });
476 const callback = new URL(approved.redirectTo!);
477 expect(`${callback.origin}${callback.pathname}`).toBe(callbackUrl);
478​
479 const tokenResponse = yield* handler(
480 at(
481 "/oauth/mcp/token",
482 form({
483 grant_type: "authorization_code",
484 code: callback.searchParams.get("code")!,
485 redirect_uri: callbackUrl,
486 client_id: client.client_id,
487 client_secret: "unused",
488 code_verifier: verifier,
489 }),
490 ),
491 );
492 expect(tokenResponse.status).toBe(200);
493 const token = (yield* json<unknown>(tokenResponse)) as { access_token: string };
494 const signedIn = yield* auth.authenticateMcpClient(
495 HttpServerRequest.fromWeb(
496 at("/mcp", { headers: { authorization: `Bearer ${token.access_token}` } }),
497 ),
498 );
499 expect(signedIn).toMatchObject({ label: "Hosted bot", access: "approval-required" });
500 }),
501 ),
502);
503​
504it.live("signs in Gemini, which registers six user-bound redirect URIs for one client", () =>
505 withRoutes((handler, auth) =>
506 Effect.gen(function* () {
507 const redirectUris = Array.from(
508 { length: 6 },
509 (_, index) =>
510 `https://oauth-redirect.googleusercontent.com/r/user_bound_custom-mcp-test${index}`,
511 );
512 const registered = yield* handler(
513 at("/oauth/mcp/register", {
514 method: "POST",
515 headers: { "content-type": "application/json" },
516 body: encodeJson({
517 client_name: "Google",
518 redirect_uris: redirectUris,
519 token_endpoint_auth_method: "client_secret_basic",
520 }),
521 }),
522 );
523 const client = (yield* json<unknown>(registered)) as { client_id: string };
524 expect(client).toMatchObject({ redirect_uris: redirectUris });
525 expect(registered.status).toBe(201);
526​
527 const callbackUrl = redirectUris[5]!;
528 const params = authorizeParams(client.client_id, callbackUrl);
529 const pairing = yield* auth.issuePairingCredential();
530 const approved = yield* decide(handler, params, {
531 _tag: "pairing-code",
532 access: "approval-required",
533 code: pairing.credential,
534 });
535 const callback = new URL(approved.redirectTo!);
536 expect(`${callback.origin}${callback.pathname}`).toBe(callbackUrl);
537 }),
538 ),
539);
540​
541it.live("issues no session for a sign-in approved before all other sessions were revoked", () =>
542 withRoutes((handler, auth) =>
543 Effect.gen(function* () {
544 const clientId = yield* registeredClientId(handler);
545 const params = authorizeParams(clientId);
546 const approved = yield* decide(handler, params, {
547 _tag: "pairing-code",
548 access: "approval-required",
549 code: (yield* auth.issuePairingCredential()).credential,
550 });
551 const code = new URL(approved.redirectTo!).searchParams.get("code")!;
552 const owner = yield* auth.issueSession();
553 yield* auth.revokeOtherClientSessions(owner.sessionId);
554​
555 const response = yield* handler(
556 at(
557 "/oauth/mcp/token",
558 form({
559 grant_type: "authorization_code",
560 code,
561 redirect_uri: params.redirect_uri,
562 client_id: clientId,
563 code_verifier: verifier,
564 }),
565 ),
566 );
567 expect(response.status).toBe(400);
568 expect(yield* json<unknown>(response)).toEqual({
569 error: "invalid_grant",
570 error_description: "The authorization code is invalid or expired.",
571 });
572 expect((yield* auth.listSessions()).map((session) => session.sessionId)).toEqual([
573 owner.sessionId,
574 ]);
575 }),
576 ),
577);
578​
579it.live("rejects a wrong PKCE verifier and spends the code", () =>
580 withRoutes((handler, auth) =>
581 Effect.gen(function* () {
582 const clientId = yield* registeredClientId(handler);
583 const pairing = yield* auth.issuePairingCredential();
584 const params = authorizeParams(clientId);
585 const approved = yield* decide(handler, params, {
586 _tag: "pairing-code",
587 access: "approval-required",
588 code: pairing.credential,
589 });
590 const code = new URL(approved.redirectTo!).searchParams.get("code")!;
591 const exchange = (codeVerifier: string) =>
592 handler(
593 at(
594 "/oauth/mcp/token",
595 form({
596 grant_type: "authorization_code",
597 code,
598 redirect_uri: params.redirect_uri,
599 client_id: clientId,
600 code_verifier: codeVerifier,
601 }),
602 ),
603 );
604 const wrong = yield* exchange("b".repeat(64));
605 expect(wrong.status).toBe(400);
606 expect(yield* json<unknown>(wrong)).toMatchObject({ error: "invalid_grant" });
607 expect((yield* exchange(verifier)).status).toBe(400);
608 }),
609 ),
610);
611​
612it.live(
613 "denies and refuses codes bound to another client's key or without the scopes it grants",
614 () =>
615 withRoutes((handler, auth) =>
616 Effect.gen(function* () {
617 const clientId = yield* registeredClientId(handler);
618 const params = authorizeParams(clientId);
619​
620 const denied = yield* decide(handler, params, { _tag: "deny" });
621 const deniedUrl = new URL(denied.redirectTo!);
622 expect(deniedUrl.searchParams.get("error")).toBe("access_denied");
623 expect(deniedUrl.searchParams.get("state")).toBe("state-1");
624​
625 const approveWith = (code: string) =>
626 decide(handler, params, { _tag: "pairing-code", access: "auto", code });
627​
628 const bound = yield* auth.createPairingLink({
629 proofKeyThumbprint: "device-key-thumbprint",
630 });
631 expect((yield* approveWith(bound.credential)).status).toBe(400);
632 const stillValid = yield* auth
633 .exchangeBootstrapCredentialForAccessToken(
634 bound.credential,
635 undefined,
636 { deviceType: "mobile" },
637 { proofKeyThumbprint: "device-key-thumbprint" },
638 )
639 .pipe(
640 Effect.as(true),
641 Effect.orElseSucceed(() => false),
642 );
643 expect(stillValid).toBe(true);
644​
645 const readOnly = yield* auth.issuePairingCredential({ scopes: ["orchestration:read"] });
646 const readOnlyResponse = yield* approveWith(readOnly.credential);
647 expect(readOnlyResponse.status).toBe(400);
648 expect(readOnlyResponse.message).toContain("cannot grant this access");
649 const operator = yield* auth.issuePairingCredential({
650 scopes: ["orchestration:read", "orchestration:operate"],
651 });
652 const operatorFull = yield* decide(handler, params, {
653 _tag: "pairing-code",
654 access: "full-access",
655 code: operator.credential,
656 });
657 expect(operatorFull.status).toBe(400);
658​
659 const readOnlyApproval = yield* decide(handler, params, {
660 _tag: "pairing-code",
661 access: "read-only",
662 code: readOnly.credential,
663 });
664 expect(readOnlyApproval.status).toBe(200);
665 const readOnlyToken = yield* handler(
666 at(
667 "/oauth/mcp/token",
668 form({
669 grant_type: "authorization_code",
670 code: new URL(readOnlyApproval.redirectTo!).searchParams.get("code")!,
671 redirect_uri: params.redirect_uri,
672 client_id: clientId,
673 code_verifier: verifier,
674 resource: `${ORIGIN}/mcp`,
675 }),
676 ),
677 ).pipe(Effect.flatMap(json<{ access_token: string; scope: string }>));
678 expect(readOnlyToken.scope).toBe("orchestration:read");
679 const readOnlyClient = yield* auth.authenticateMcpClient(
680 HttpServerRequest.fromWeb(
681 at("/mcp", { headers: { authorization: `Bearer ${readOnlyToken.access_token}` } }),
682 ),
683 );
684 expect(readOnlyClient.access).toBe("read-only");
685 }),
686 ),
687);
688​
689it.live("a code minted with an access level's scopes approves that access", () =>
690 withRoutes((handler, auth) =>
691 Effect.gen(function* () {
692 const params = authorizeParams(yield* registeredClientId(handler));
693 for (const access of AuthMcpClientAccess.literals) {
694 const code = yield* auth.issuePairingCredential({ scopes: [...mcpClientScopes(access)] });
695 const approval = yield* decide(handler, params, {
696 _tag: "pairing-code",
697 access,
698 code: code.credential,
699 });
700 expect(approval.status, access).toBe(200);
701 }
702 }),
703 ),
704);
705​
706it.live("an app approval code approves only an app sign-in, at its own level", () =>
707 withRoutes((handler, auth) =>
708 Effect.gen(function* () {
709 const clientId = yield* registeredClientId(handler);
710 const params = authorizeParams(clientId);
711 const issued = yield* auth.issuePairingCredential({ access: "approval-required" });
712 expect(issued.access).toBe("approval-required");
713 const code = issued.credential;
714 expect(code).toMatch(/^SUPERVISED-[2-9A-HJ-NP-Z]{12}$/);
715​
716 // Signing in a browser, a token exchange and linking all refuse it and leave it unspent.
717 const browser = yield* handler(
718 at("/api/auth/browser-session", {
719 method: "POST",
720 headers: { "content-type": "application/json" },
721 body: encodeJson({ credential: code }),
722 }),
723 );
724 expect(browser.status).toBe(401);
725 const exchanged = yield* auth
726 .exchangeBootstrapCredentialForAccessToken(code, undefined, { deviceType: "bot" })
727 .pipe(Effect.flip);
728 expect(exchanged._tag).toBe("ServerAuthInvalidCredentialError");
729 const peer = yield* handler(
730 at("/oauth/mcp/register", {
731 method: "POST",
732 headers: { "content-type": "application/json" },
733 body: encodeJson({
734 client_name: "Studio",
735 software_id: MCP_PEER_LINK_SOFTWARE_ID,
736 redirect_uris: [REDIRECT],
737 }),
738 }),
739 ).pipe(Effect.flatMap(json<{ client_id: string }>));
740 const linked = yield* decide(handler, authorizeParams(peer.client_id), {
741 _tag: "pairing-code",
742 access: "approval-required",
743 code,
744 });
745 expect(linked.status).toBe(400);
746​
747 // Supervised and Auto share scopes, so only the code's own level may spend it.
748 const otherLevel = yield* decide(handler, params, {
749 _tag: "pairing-code",
750 access: "auto",
751 code,
752 });
753 expect(otherLevel.status).toBe(400);
754​
755 const approved = yield* decide(handler, params, {
756 _tag: "pairing-code",
757 access: "approval-required",
758 code: code.toLowerCase(),
759 });
760 expect(approved.status).toBe(200);
761 const token = yield* handler(
762 at(
763 "/oauth/mcp/token",
764 form({
765 grant_type: "authorization_code",
766 code: new URL(approved.redirectTo!).searchParams.get("code")!,
767 redirect_uri: params.redirect_uri,
768 client_id: clientId,
769 code_verifier: verifier,
770 }),
771 ),
772 ).pipe(Effect.flatMap(json<{ access_token: string }>));
773 const signedIn = yield* auth.authenticateMcpClient(
774 HttpServerRequest.fromWeb(
775 at("/mcp", { headers: { authorization: `Bearer ${token.access_token}` } }),
776 ),
777 );
778 expect(signedIn.access).toBe("approval-required");
779 expect(
780 (yield* decide(handler, params, {
781 _tag: "pairing-code",
782 access: "approval-required",
783 code,
784 })).status,
785 ).toBe(400);
786 }),
787 ),
788);
789​
790it.effect(
791 "sends an app sign-in on the linked tunnel to the hosted app, and a link to its own page",
792 () =>
793 Effect.gen(function* () {
794 const handoff = (tunnelHostname: string, peerLink = false) =>
795 withRoutes(
796 (handler) =>
797 Effect.gen(function* () {
798 const registered = yield* handler(
799 at("/oauth/mcp/register", {
800 method: "POST",
801 headers: { "content-type": "application/json" },
802 body: encodeJson({
803 client_name: "Agent",
804 redirect_uris: [REDIRECT],
805 token_endpoint_auth_method: "none",
806 ...(peerLink ? { software_id: MCP_PEER_LINK_SOFTWARE_ID } : {}),
807 }),
808 }),
809 ).pipe(Effect.flatMap(json<{ client_id: string }>));
810 const query = new URLSearchParams(
811 authorizeParams(registered.client_id, "http://localhost:51234/callback"),
812 );
813 const response = yield* handler(at(`/oauth/mcp/authorize?${query}`));
814 return { location: response.headers.get("location")!, query: query.toString() };
815 }),
816 { ...notLinked, linked: true, cloudUserId: "user_1", tunnelHostname },
817 );
818​
819 const onTunnel = yield* handoff("box.example.ts.net");
820 const hosted = new URL(onTunnel.location);
821 expect(`${hosted.origin}${hosted.pathname}`).toBe("https://app.t3.codes/approve-agent");
822 expect(hosted.searchParams.get("environment")).toEqual(expect.any(String));
823 hosted.searchParams.delete("environment");
824 expect(hosted.searchParams.toString()).toBe(onTunnel.query);
825​
826 const elsewhere = yield* handoff("other.t3coderelay.com");
827 expect(elsewhere.location).toBe(`/connect-agent?${elsewhere.query}`);
828 const peerLink = yield* handoff("box.example.ts.net", true);
829 expect(peerLink.location).toBe(`/connect-agent?${peerLink.query}`);
830 }),
831);
832​
833it.live("one-click approves only access the browser session holds the scopes for", () =>
834 withRoutes((handler, auth) =>
835 Effect.gen(function* () {
836 const clientId = yield* registeredClientId(handler);
837 const params = authorizeParams(clientId);
838 const browserCookie = (scopes: NonNullable<AuthCreatePairingCredentialInput["scopes"]>) =>
839 Effect.gen(function* () {
840 const pairing = yield* auth.issuePairingCredential({ scopes });
841 const response = yield* handler(
842 at("/api/auth/browser-session", {
843 method: "POST",
844 headers: { "content-type": "application/json" },
845 body: encodeJson({ credential: pairing.credential }),
846 }),
847 );
848 return response.headers.getSetCookie()[0]!.split(";", 1)[0]!;
849 });
850 const details = (cookie: string) =>
851 handler(postJson("/oauth/mcp/approval", params, cookie)).pipe(
852 Effect.flatMap(json<{ csrfToken?: string; oneClickAccess?: ReadonlyArray<string> }>),
853 );
854​
855 const admin = yield* browserCookie([...AuthStandardClientScopes]);
856 const adminDetails = yield* details(admin);
857 expect(adminDetails.csrfToken).toEqual(expect.any(String));
858 expect(adminDetails.oneClickAccess).toEqual([
859 "read-only",
860 "approval-required",
861 "auto-accept-edits",
862 "auto",
863 "full-access",
864 ]);
865 const oneClick = yield* decide(
866 handler,
867 params,
868 { _tag: "browser-session", access: "auto", csrfToken: adminDetails.csrfToken! },
869 admin,
870 );
871 expect(new URL(oneClick.redirectTo!).searchParams.get("code")).toEqual(expect.any(String));
872​
873 const accessOnly = yield* browserCookie(["access:read", "access:write"]);
874 expect((yield* details(accessOnly)).csrfToken).toBeUndefined();
875 const forged = yield* decide(
876 handler,
877 params,
878 { _tag: "browser-session", access: "auto", csrfToken: "forged" },
879 accessOnly,
880 );
881 expect(forged.status).toBe(400);
882 expect(forged.message).toContain("Enter a pairing code instead");
883​
884 const reader = yield* browserCookie(["access:write", "orchestration:read"]);
885 const readerDetails = yield* details(reader);
886 expect(readerDetails.csrfToken).toEqual(expect.any(String));
887 expect(readerDetails.oneClickAccess).toEqual(["read-only"]);
888 const tooBroad = yield* decide(
889 handler,
890 params,
891 { _tag: "browser-session", access: "auto", csrfToken: readerDetails.csrfToken! },
892 reader,
893 );
894 expect(tooBroad.status).toBe(400);
895 const readOnly = yield* decide(
896 handler,
897 params,
898 { _tag: "browser-session", access: "read-only", csrfToken: readerDetails.csrfToken! },
899 reader,
900 );
901 expect(new URL(readOnly.redirectTo!).searchParams.get("code")).toEqual(expect.any(String));
902​
903 // The hosted app approves with the owner's T3 Connect session, which sends no cookie.
904 const connect = `Bearer ${(yield* auth.issueSession({ scopes: [...AuthStandardClientScopes] })).token}`;
905 const connectDetails = yield* details(connect);
906 expect(connectDetails.oneClickAccess).toContain("full-access");
907 const viaConnect = yield* decide(
908 handler,
909 params,
910 { _tag: "browser-session", access: "auto", csrfToken: connectDetails.csrfToken! },
911 connect,
912 );
913 expect(new URL(viaConnect.redirectTo!).searchParams.get("code")).toEqual(expect.any(String));
914​
915 // The hosted app may load and decide with two credentials minted for the same browser key.
916 const key = makeDpopKey();
917 const dpopSession = (thumbprint: string) =>
918 auth.issuePairingCredential({ scopes: [...AuthStandardClientScopes] }).pipe(
919 Effect.flatMap((pairing) =>
920 auth.exchangeBootstrapCredentialForAccessToken(
921 pairing.credential,
922 undefined,
923 { deviceType: "desktop" },
924 { proofKeyThumbprint: thumbprint },
925 ),
926 ),
927 Effect.map((exchanged) => exchanged.access_token),
928 );
929 const iat = Math.floor((yield* Clock.currentTimeMillis) / 1_000);
930 const dpopHeaders = (signer: typeof key, token: string, path: string) => ({
931 authorization: `DPoP ${token}`,
932 dpop: signer.sign({ method: "POST", url: `${ORIGIN}${path}`, token, iat }),
933 });
934 const loadedWith = yield* dpopSession(key.thumbprint);
935 const loaded = yield* handler(
936 postJson(
937 "/oauth/mcp/approval",
938 params,
939 dpopHeaders(key, loadedWith, "/oauth/mcp/approval"),
940 ),
941 ).pipe(Effect.flatMap(json<{ csrfToken?: string }>));
942 const renewed = yield* dpopSession(key.thumbprint);
943 const sameKey = yield* decide(
944 handler,
945 params,
946 { _tag: "browser-session", access: "auto", csrfToken: loaded.csrfToken! },
947 dpopHeaders(key, renewed, "/oauth/mcp/decision"),
948 );
949 expect(new URL(sameKey.redirectTo!).searchParams.get("code")).toEqual(expect.any(String));
950 const otherKey = makeDpopKey();
951 const elsewhere = yield* decide(
952 handler,
953 params,
954 { _tag: "browser-session", access: "auto", csrfToken: loaded.csrfToken! },
955 dpopHeaders(otherKey, yield* dpopSession(otherKey.thumbprint), "/oauth/mcp/decision"),
956 );
957 expect(elsewhere.status).toBe(400);
958 }),
959 ),
960);
961​
962it("matches loopback redirects on everything but the port, and https redirects exactly", () => {
963 const matches = McpOAuth.redirectMatches;
964 expect(matches("http://localhost/callback", "http://localhost:9/callback")).toBe(true);
965 expect(matches("http://127.0.0.1:1/callback", "http://127.0.0.1:2/callback")).toBe(true);
966 expect(matches("http://localhost/callback", "http://127.0.0.1/callback")).toBe(false);
967 expect(matches("http://localhost/callback", "https://localhost/callback")).toBe(false);
968 expect(matches("https://bot.example/cb", "https://bot.example/cb")).toBe(true);
969 expect(matches("https://bot.example/cb", "https://bot.example:8443/cb")).toBe(false);
970 expect(matches("https://bot.example/cb", "https://bot.example/cb?x=1")).toBe(false);
971 expect(matches("https://bot.example/cb", "https://evil.example/cb")).toBe(false);
972});