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

McpOAuth.test.ts

590 lines22.1 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import {
3 AuthMcpClientAccess,
4 AuthStandardClientScopes,
5 type AuthCreatePairingCredentialInput,
6 EnvironmentHttpApi,
7 mcpClientScopes,
8} from "@t3tools/contracts";
9import { expect, it } from "@effect/vitest";
10import * as Context from "effect/Context";
11import * as Crypto from "effect/Crypto";
12import * as Effect from "effect/Effect";
13import * as Layer from "effect/Layer";
14import * as Etag from "effect/http/Etag";
15import * as HttpPlatform from "effect/http/HttpPlatform";
16import * as HttpRouter from "effect/http/HttpRouter";
17import * as HttpServerRequest from "effect/http/HttpServerRequest";
18import * as HttpApi from "effect/http-api/HttpApi";
19import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
20import * as Schema from "effect/Schema";
21​
22import * as ServerConfig from "../config.ts";
23import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
24import * as ServerSettings from "../serverSettings.ts";
25import * as Sqlite from "../persistence/Sqlite.ts";
26import * as EnvironmentAuth from "./EnvironmentAuth.ts";
27import * as McpOAuth from "./McpOAuth.ts";
28import * as McpOAuthHttp from "./mcpOAuthHttp.ts";
29import * as ServerSecretStore from "./ServerSecretStore.ts";
30import * as AuthHttp from "./http.ts";
31​
32class AuthTestApi extends HttpApi.make("environment")
33 .add(EnvironmentHttpApi.groups.auth)
34 .add(EnvironmentHttpApi.groups.mcpOAuth) {}
35​
36const layerConfig = ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-oauth-test-" });
37const layerEnvironmentAuth = EnvironmentAuth.layer.pipe(
38 Layer.provide(Sqlite.layerMemory),
39 Layer.provideMerge(ServerSecretStore.layer),
40 Layer.provideMerge(ServerEnvironment.layerIdentity),
41 Layer.provide(layerConfig),
42);
43const makeLayerRoutes = (capture: (auth: EnvironmentAuth.EnvironmentAuth["Service"]) => void) =>
44 Layer.mergeAll(
45 Layer.effectDiscard(
46 EnvironmentAuth.EnvironmentAuth.pipe(Effect.tap((auth) => Effect.sync(() => capture(auth)))),
47 ),
48 HttpApiBuilder.layer(AuthTestApi).pipe(
49 Layer.provide(AuthHttp.layer),
50 Layer.provide(
51 McpOAuthHttp.layer.pipe(
52 Layer.provide(McpOAuth.layer),
53 Layer.provide(ServerSettings.layerTest()),
54 ),
55 ),
56 Layer.provide(AuthHttp.layerAuthenticatedAuth),
57 ),
58 ).pipe(
59 Layer.provideMerge(layerEnvironmentAuth),
60 Layer.provide(layerConfig),
61 Layer.provideMerge(
62 HttpPlatform.layer.pipe(
63 Layer.provideMerge(NodeServices.layer),
64 Layer.provideMerge(Etag.layerWeak),
65 ),
66 ),
67 Layer.provide(NodeServices.layer),
68 );
69​
70const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
71const ORIGIN = "https://box.example.ts.net";
72const REDIRECT = "http://localhost/callback";
73const verifier = "a".repeat(43) + "-verifier-for-tests";
74const challenge = "DeB41nTVkPwpbbYecrnqtVq7VXLezustdHAK4SWt13c";
75​
76const at = (path: string, init?: RequestInit) =>
77 new Request(`http://127.0.0.1${path}`, {
78 ...init,
79 headers: { host: "box.example.ts.net", "x-forwarded-proto": "https", ...init?.headers },
80 });
81const form = (body: Record<string, string>) => ({
82 method: "POST",
83 headers: { "content-type": "application/x-www-form-urlencoded" },
84 body: new URLSearchParams(body).toString(),
85});
86​
87type Handler = (request: Request) => Effect.Effect<Response>;
88​
89const withRoutes = <A, E>(
90 use: (handler: Handler, auth: EnvironmentAuth.EnvironmentAuth["Service"]) => Effect.Effect<A, E>,
91) =>
92 Effect.gen(function* () {
93 const crypto = yield* Crypto.Crypto;
94 const context = Context.make(Crypto.Crypto, crypto);
95 let routerAuth: EnvironmentAuth.EnvironmentAuth["Service"] | undefined;
96 const layerRoutes = makeLayerRoutes((auth) => {
97 routerAuth = auth;
98 });
99 return yield* Effect.acquireUseRelease(
100 Effect.sync(() => HttpRouter.toWebHandler(layerRoutes, { disableLogger: true })),
101 (web) =>
102 Effect.gen(function* () {
103 const handler: Handler = (request) => Effect.promise(() => web.handler(request, context));
104 yield* handler(at("/.well-known/oauth-authorization-server"));
105 return yield* use(handler, routerAuth!);
106 }),
107 (web) => Effect.promise(() => web.dispose()),
108 );
109 }).pipe(Effect.provide(NodeServices.layer));
110​
111const json = <A>(response: Response) => Effect.promise(() => response.json() as Promise<A>);
112​
113const postJson = (path: string, body: unknown, cookie?: string) =>
114 at(path, {
115 method: "POST",
116 headers: { "content-type": "application/json", ...(cookie ? { cookie } : {}) },
117 body: encodeJson(body),
118 });
119​
120const decide = (
121 handler: Handler,
122 authorization: Record<string, string>,
123 decision: Record<string, string>,
124 cookie?: string,
125) =>
126 handler(postJson("/oauth/mcp/decision", { authorization, decision }, cookie)).pipe(
127 Effect.flatMap((response) =>
128 json<{ redirectTo?: string; message?: string }>(response).pipe(
129 Effect.map((payload) => ({ status: response.status, ...payload })),
130 ),
131 ),
132 );
133​
134const register = (handler: Handler, redirect = REDIRECT) =>
135 handler(
136 at("/oauth/mcp/register", {
137 method: "POST",
138 headers: { "content-type": "application/json" },
139 body: encodeJson({
140 client_name: "Claude Code",
141 redirect_uris: [redirect],
142 grant_types: ["authorization_code", "refresh_token"],
143 token_endpoint_auth_method: "none",
144 }),
145 }),
146 );
147​
148const registeredClientId = (handler: Handler) =>
149 register(handler).pipe(
150 Effect.flatMap((response) => json<{ client_id: string }>(response)),
151 Effect.map((body) => body.client_id),
152 );
153​
154const authorizeParams = (clientId: string, redirect = "http://localhost:51234/callback") => ({
155 response_type: "code",
156 client_id: clientId,
157 redirect_uri: redirect,
158 code_challenge: challenge,
159 code_challenge_method: "S256",
160 state: "state-1",
161 resource: `${ORIGIN}/mcp`,
162});
163​
164it.live("derives discovery metadata from the origin the client reached", () =>
165 withRoutes((handler) =>
166 Effect.gen(function* () {
167 const resource = yield* handler(at("/.well-known/oauth-protected-resource/mcp"));
168 expect(yield* json<unknown>(resource)).toMatchObject({
169 resource: `${ORIGIN}/mcp`,
170 authorization_servers: [ORIGIN],
171 });
172 const server = yield* json<unknown>(
173 yield* handler(at("/.well-known/oauth-authorization-server")),
174 );
175 expect(server).toMatchObject({
176 issuer: ORIGIN,
177 authorization_endpoint: `${ORIGIN}/oauth/mcp/authorize`,
178 token_endpoint: `${ORIGIN}/oauth/mcp/token`,
179 registration_endpoint: `${ORIGIN}/oauth/mcp/register`,
180 code_challenge_methods_supported: ["S256"],
181 });
182 }),
183 ),
184);
185​
186it.live("registers loopback and https clients and never redirects for an unverified client", () =>
187 withRoutes((handler) =>
188 Effect.gen(function* () {
189 for (const refused of [
190 "http://bot.example/callback",
191 "https://user:pass@bot.example/callback",
192 "https://bot.example/callback#",
193 "http://localhost/callback#",
194 "javascript:alert(1)",
195 ]) {
196 const response = yield* register(handler, refused);
197 expect(response.status).toBe(400);
198 expect(yield* json<unknown>(response)).toMatchObject({ error: "invalid_redirect_uri" });
199 }
200​
201 const registered = yield* register(handler);
202 expect(registered.status).toBe(201);
203 const { client_id: clientId } = (yield* json<unknown>(registered)) as { client_id: string };
204​
205 const forged = yield* handler(
206 at(
207 `/oauth/mcp/authorize?${new URLSearchParams(authorizeParams(`${clientId.split(".")[0]}.forged`))}`,
208 ),
209 );
210 expect(forged.status).toBe(400);
211 expect(forged.headers.get("location")).toBeNull();
212​
213 const unregistered = yield* handler(
214 at(
215 `/oauth/mcp/authorize?${new URLSearchParams(
216 authorizeParams(clientId, "http://localhost:51234/elsewhere"),
217 )}`,
218 ),
219 );
220 expect(unregistered.status).toBe(400);
221 expect(unregistered.headers.get("location")).toBeNull();
222​
223 const query = new URLSearchParams(authorizeParams(clientId)).toString();
224 const handoff = yield* handler(at(`/oauth/mcp/authorize?${query}`));
225 expect(handoff.status).toBe(302);
226 expect(handoff.headers.get("location")).toBe(`/connect-agent?${query}`);
227 const details = yield* handler(
228 postJson("/oauth/mcp/approval", authorizeParams(clientId)),
229 ).pipe(Effect.flatMap(json<Record<string, unknown>>));
230 expect(details).toEqual({
231 clientName: "Claude Code",
232 redirectHost: "localhost:51234",
233 environmentHost: "box.example.ts.net",
234 });
235​
236 const forgedDetails = yield* handler(
237 postJson("/oauth/mcp/approval", authorizeParams(`${clientId.split(".")[0]}.forged`)),
238 );
239 expect(forgedDetails.status).toBe(400);
240 expect(yield* json<Record<string, unknown>>(forgedDetails)).not.toHaveProperty("redirectTo");
241 }),
242 ),
243);
244​
245it.live("signs in with a pairing code and issues a token only /mcp accepts", () =>
246 withRoutes((handler, auth) =>
247 Effect.gen(function* () {
248 const clientId = yield* registeredClientId(handler);
249 const pairing = yield* auth.issuePairingCredential();
250 const params = authorizeParams(clientId);
251​
252 const wrongCode = yield* decide(handler, params, {
253 _tag: "pairing-code",
254 access: "auto",
255 code: "nope",
256 });
257 expect(wrongCode.status).toBe(400);
258 expect(wrongCode.message).toContain("unknown, expired, or already used");
259​
260 const approved = yield* decide(handler, params, {
261 _tag: "pairing-code",
262 access: "auto",
263 code: pairing.credential,
264 });
265 expect(approved.status).toBe(200);
266 const callback = new URL(approved.redirectTo!);
267 expect(callback.origin).toBe("http://localhost:51234");
268 expect(callback.searchParams.get("state")).toBe("state-1");
269 expect(callback.searchParams.get("iss")).toBe(ORIGIN);
270 const code = callback.searchParams.get("code")!;
271​
272 const exchange = (codeVerifier: string) =>
273 handler(
274 at(
275 "/oauth/mcp/token",
276 form({
277 grant_type: "authorization_code",
278 code,
279 redirect_uri: params.redirect_uri,
280 client_id: clientId,
281 code_verifier: codeVerifier,
282 resource: `${ORIGIN}/mcp`,
283 }),
284 ),
285 );
286 const tokenResponse = yield* exchange(verifier);
287 expect(tokenResponse.status).toBe(200);
288 const token = (yield* json<unknown>(tokenResponse)) as {
289 access_token: string;
290 scope: string;
291 };
292 expect(token.scope).toBe("orchestration:read orchestration:operate");
293​
294 expect((yield* exchange(verifier)).status).toBe(400);
295​
296 const client = yield* auth.authenticateMcpClient(
297 HttpServerRequest.fromWeb(
298 at("/mcp", { headers: { authorization: `Bearer ${token.access_token}` } }),
299 ),
300 );
301 expect(client).toMatchObject({ label: "Claude Code", access: "auto" });
302​
303 const session = yield* handler(
304 at("/api/auth/session", { headers: { authorization: `Bearer ${token.access_token}` } }),
305 );
306 expect(yield* json<unknown>(session)).toMatchObject({ authenticated: false });
307 const ticket = yield* handler(
308 at("/api/auth/websocket-ticket", {
309 method: "POST",
310 headers: { authorization: `Bearer ${token.access_token}` },
311 }),
312 );
313 expect(ticket.status).toBe(401);
314 }),
315 ),
316);
317​
318it.live("signs in a hosted agent with an https callback that asked for a client secret", () =>
319 withRoutes((handler, auth) =>
320 Effect.gen(function* () {
321 const callbackUrl = "https://bot.example/oauth/callback";
322 const registered = yield* handler(
323 at("/oauth/mcp/register", {
324 method: "POST",
325 headers: { "content-type": "application/json" },
326 body: encodeJson({
327 client_name: "Hosted bot",
328 redirect_uris: [callbackUrl],
329 token_endpoint_auth_method: "client_secret_post",
330 }),
331 }),
332 );
333 expect(registered.status).toBe(201);
334 const client = (yield* json<unknown>(registered)) as {
335 client_id: string;
336 token_endpoint_auth_method: string;
337 };
338 expect(client.token_endpoint_auth_method).toBe("none");
339​
340 const params = authorizeParams(client.client_id, callbackUrl);
341 const details = yield* handler(postJson("/oauth/mcp/approval", params)).pipe(
342 Effect.flatMap(json<Record<string, unknown>>),
343 );
344 expect(details).toMatchObject({ clientName: "Hosted bot", redirectHost: "bot.example" });
345​
346 const pairing = yield* auth.issuePairingCredential();
347 const approved = yield* decide(handler, params, {
348 _tag: "pairing-code",
349 access: "approval-required",
350 code: pairing.credential,
351 });
352 const callback = new URL(approved.redirectTo!);
353 expect(`${callback.origin}${callback.pathname}`).toBe(callbackUrl);
354​
355 const tokenResponse = yield* handler(
356 at(
357 "/oauth/mcp/token",
358 form({
359 grant_type: "authorization_code",
360 code: callback.searchParams.get("code")!,
361 redirect_uri: callbackUrl,
362 client_id: client.client_id,
363 client_secret: "unused",
364 code_verifier: verifier,
365 }),
366 ),
367 );
368 expect(tokenResponse.status).toBe(200);
369 const token = (yield* json<unknown>(tokenResponse)) as { access_token: string };
370 const signedIn = yield* auth.authenticateMcpClient(
371 HttpServerRequest.fromWeb(
372 at("/mcp", { headers: { authorization: `Bearer ${token.access_token}` } }),
373 ),
374 );
375 expect(signedIn).toMatchObject({ label: "Hosted bot", access: "approval-required" });
376 }),
377 ),
378);
379​
380it.live("rejects a wrong PKCE verifier and spends the code", () =>
381 withRoutes((handler, auth) =>
382 Effect.gen(function* () {
383 const clientId = yield* registeredClientId(handler);
384 const pairing = yield* auth.issuePairingCredential();
385 const params = authorizeParams(clientId);
386 const approved = yield* decide(handler, params, {
387 _tag: "pairing-code",
388 access: "approval-required",
389 code: pairing.credential,
390 });
391 const code = new URL(approved.redirectTo!).searchParams.get("code")!;
392 const exchange = (codeVerifier: string) =>
393 handler(
394 at(
395 "/oauth/mcp/token",
396 form({
397 grant_type: "authorization_code",
398 code,
399 redirect_uri: params.redirect_uri,
400 client_id: clientId,
401 code_verifier: codeVerifier,
402 }),
403 ),
404 );
405 const wrong = yield* exchange("b".repeat(64));
406 expect(wrong.status).toBe(400);
407 expect(yield* json<unknown>(wrong)).toMatchObject({ error: "invalid_grant" });
408 expect((yield* exchange(verifier)).status).toBe(400);
409 }),
410 ),
411);
412​
413it.live(
414 "denies and refuses codes bound to another client's key or without the scopes it grants",
415 () =>
416 withRoutes((handler, auth) =>
417 Effect.gen(function* () {
418 const clientId = yield* registeredClientId(handler);
419 const params = authorizeParams(clientId);
420​
421 const denied = yield* decide(handler, params, { _tag: "deny" });
422 const deniedUrl = new URL(denied.redirectTo!);
423 expect(deniedUrl.searchParams.get("error")).toBe("access_denied");
424 expect(deniedUrl.searchParams.get("state")).toBe("state-1");
425​
426 const approveWith = (code: string) =>
427 decide(handler, params, { _tag: "pairing-code", access: "auto", code });
428​
429 const bound = yield* auth.createPairingLink({
430 proofKeyThumbprint: "device-key-thumbprint",
431 });
432 expect((yield* approveWith(bound.credential)).status).toBe(400);
433 const stillValid = yield* auth
434 .exchangeBootstrapCredentialForAccessToken(
435 bound.credential,
436 undefined,
437 { deviceType: "mobile" },
438 { proofKeyThumbprint: "device-key-thumbprint" },
439 )
440 .pipe(
441 Effect.as(true),
442 Effect.orElseSucceed(() => false),
443 );
444 expect(stillValid).toBe(true);
445​
446 const readOnly = yield* auth.issuePairingCredential({ scopes: ["orchestration:read"] });
447 const readOnlyResponse = yield* approveWith(readOnly.credential);
448 expect(readOnlyResponse.status).toBe(400);
449 expect(readOnlyResponse.message).toContain("cannot grant this access");
450 const operator = yield* auth.issuePairingCredential({
451 scopes: ["orchestration:read", "orchestration:operate"],
452 });
453 const operatorFull = yield* decide(handler, params, {
454 _tag: "pairing-code",
455 access: "full-access",
456 code: operator.credential,
457 });
458 expect(operatorFull.status).toBe(400);
459​
460 const readOnlyApproval = yield* decide(handler, params, {
461 _tag: "pairing-code",
462 access: "read-only",
463 code: readOnly.credential,
464 });
465 expect(readOnlyApproval.status).toBe(200);
466 const readOnlyToken = yield* handler(
467 at(
468 "/oauth/mcp/token",
469 form({
470 grant_type: "authorization_code",
471 code: new URL(readOnlyApproval.redirectTo!).searchParams.get("code")!,
472 redirect_uri: params.redirect_uri,
473 client_id: clientId,
474 code_verifier: verifier,
475 resource: `${ORIGIN}/mcp`,
476 }),
477 ),
478 ).pipe(Effect.flatMap(json<{ access_token: string; scope: string }>));
479 expect(readOnlyToken.scope).toBe("orchestration:read");
480 const readOnlyClient = yield* auth.authenticateMcpClient(
481 HttpServerRequest.fromWeb(
482 at("/mcp", { headers: { authorization: `Bearer ${readOnlyToken.access_token}` } }),
483 ),
484 );
485 expect(readOnlyClient.access).toBe("read-only");
486 }),
487 ),
488);
489​
490it.live("a code minted with an access level's scopes approves that access", () =>
491 withRoutes((handler, auth) =>
492 Effect.gen(function* () {
493 const params = authorizeParams(yield* registeredClientId(handler));
494 for (const access of AuthMcpClientAccess.literals) {
495 const code = yield* auth.issuePairingCredential({ scopes: [...mcpClientScopes(access)] });
496 const approval = yield* decide(handler, params, {
497 _tag: "pairing-code",
498 access,
499 code: code.credential,
500 });
501 expect(approval.status, access).toBe(200);
502 }
503 }),
504 ),
505);
506​
507it.live("one-click approves only access the browser session holds the scopes for", () =>
508 withRoutes((handler, auth) =>
509 Effect.gen(function* () {
510 const clientId = yield* registeredClientId(handler);
511 const params = authorizeParams(clientId);
512 const browserCookie = (scopes: NonNullable<AuthCreatePairingCredentialInput["scopes"]>) =>
513 Effect.gen(function* () {
514 const pairing = yield* auth.issuePairingCredential({ scopes });
515 const response = yield* handler(
516 at("/api/auth/browser-session", {
517 method: "POST",
518 headers: { "content-type": "application/json" },
519 body: encodeJson({ credential: pairing.credential }),
520 }),
521 );
522 return response.headers.getSetCookie()[0]!.split(";", 1)[0]!;
523 });
524 const details = (cookie: string) =>
525 handler(postJson("/oauth/mcp/approval", params, cookie)).pipe(
526 Effect.flatMap(json<{ csrfToken?: string; oneClickAccess?: ReadonlyArray<string> }>),
527 );
528​
529 const admin = yield* browserCookie([...AuthStandardClientScopes]);
530 const adminDetails = yield* details(admin);
531 expect(adminDetails.csrfToken).toEqual(expect.any(String));
532 expect(adminDetails.oneClickAccess).toEqual([
533 "read-only",
534 "approval-required",
535 "auto-accept-edits",
536 "auto",
537 "full-access",
538 ]);
539 const oneClick = yield* decide(
540 handler,
541 params,
542 { _tag: "browser-session", access: "auto", csrfToken: adminDetails.csrfToken! },
543 admin,
544 );
545 expect(new URL(oneClick.redirectTo!).searchParams.get("code")).toEqual(expect.any(String));
546​
547 const accessOnly = yield* browserCookie(["access:read", "access:write"]);
548 expect((yield* details(accessOnly)).csrfToken).toBeUndefined();
549 const forged = yield* decide(
550 handler,
551 params,
552 { _tag: "browser-session", access: "auto", csrfToken: "forged" },
553 accessOnly,
554 );
555 expect(forged.status).toBe(400);
556 expect(forged.message).toContain("Enter a pairing code instead");
557​
558 const reader = yield* browserCookie(["access:write", "orchestration:read"]);
559 const readerDetails = yield* details(reader);
560 expect(readerDetails.csrfToken).toEqual(expect.any(String));
561 expect(readerDetails.oneClickAccess).toEqual(["read-only"]);
562 const tooBroad = yield* decide(
563 handler,
564 params,
565 { _tag: "browser-session", access: "auto", csrfToken: readerDetails.csrfToken! },
566 reader,
567 );
568 expect(tooBroad.status).toBe(400);
569 const readOnly = yield* decide(
570 handler,
571 params,
572 { _tag: "browser-session", access: "read-only", csrfToken: readerDetails.csrfToken! },
573 reader,
574 );
575 expect(new URL(readOnly.redirectTo!).searchParams.get("code")).toEqual(expect.any(String));
576 }),
577 ),
578);
579​
580it("matches loopback redirects on everything but the port, and https redirects exactly", () => {
581 const matches = McpOAuth.redirectMatches;
582 expect(matches("http://localhost/callback", "http://localhost:9/callback")).toBe(true);
583 expect(matches("http://127.0.0.1:1/callback", "http://127.0.0.1:2/callback")).toBe(true);
584 expect(matches("http://localhost/callback", "http://127.0.0.1/callback")).toBe(false);
585 expect(matches("http://localhost/callback", "https://localhost/callback")).toBe(false);
586 expect(matches("https://bot.example/cb", "https://bot.example/cb")).toBe(true);
587 expect(matches("https://bot.example/cb", "https://bot.example:8443/cb")).toBe(false);
588 expect(matches("https://bot.example/cb", "https://bot.example/cb?x=1")).toBe(false);
589 expect(matches("https://bot.example/cb", "https://evil.example/cb")).toBe(false);
590});