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

McpOAuth.test.ts

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