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

McpOAuth.test.ts

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