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