diff --git a/docs/native-oauth.md b/docs/native-oauth.md index 862df8ce..32a7888a 100644 --- a/docs/native-oauth.md +++ b/docs/native-oauth.md @@ -31,14 +31,31 @@ On every request the server: 4. Calls the Kernel API, starting with `GET /auth/context`, with only the exchanged token. The MCP-audience token never reaches the API. -| Outcome | Response | -| ------------------------------------------------------------------------------------------------- | ----------------------------- | -| native OAuth not configured on this server | 401 `invalid_token` | -| token fails local verification | 401 `invalid_token` | -| issuer answers `invalid_grant` (revoked, expired) | 401 `invalid_token` | -| issuer answers `invalid_scope` | 403 `insufficient_scope` | -| issuer keys or token endpoint unreachable, 5xx, `temporarily_unavailable` | 503 `temporarily_unavailable` | -| issuer refuses this server (`invalid_target`, `invalid_client`, …) or returns an unexpected token | 503, logged as an error | +| Outcome | Response | +| ------------------------------------------------------------------------------------------------- | -------------------------------------- | +| native OAuth not configured on this server | 401 `invalid_token` | +| token fails local verification | 401 `invalid_token` | +| issuer answers `invalid_grant` (revoked, expired) | 401 `invalid_token` | +| issuer answers `invalid_scope` | 403 `insufficient_scope`, challenged | +| `/auth/context` answers 403 with an `insufficient_scope` challenge | 403 `insufficient_scope`, challenged | +| `/auth/context` answers any other 403 | 403 `insufficient_scope`, no challenge | +| issuer keys or token endpoint unreachable, 5xx, `temporarily_unavailable` | 503 `temporarily_unavailable` | +| issuer refuses this server (`invalid_target`, `invalid_client`, …) or returns an unexpected token | 503, logged as an error | + +"Challenged" means the response carries +`WWW-Authenticate: Bearer error="insufficient_scope", resource_metadata="/.well-known/oauth-protected-resource/mcp"`, +plus the API's `scope` when it names one, so clients sign in again (MCP +step-up authorization). The API challenges a sign-in only when the consent +page could grant what it lacks, and names the token's actions plus the +missing ones; this server forwards that scope with its own resource metadata. +A 403 without a challenge is one signing in again would not fix, such as a +credential scoped to another project, and gets none here either. + +A tool call the API refuses with a challenge has already started, so it +cannot become this server's 403: a client retrying it could repeat work. The +call fails as a tool error (`isError`) whose text asks the user to reconnect, +with the challenge in `_meta["mcp/www_authenticate"]` +(`src/lib/mcp/scope-challenge-results.ts`). ### Caching and freshness diff --git a/src/app/[transport]/route.test.ts b/src/app/[transport]/route.test.ts index 096555db..949e2b6c 100644 --- a/src/app/[transport]/route.test.ts +++ b/src/app/[transport]/route.test.ts @@ -454,7 +454,7 @@ describe("native OAuth credentials", () => { response = await POST(mcpRequest(await issuer.parent())); expect(response.status).toBe(403); expect(response.headers.get("WWW-Authenticate")).toBe( - 'Bearer realm="OAuth", error="insufficient_scope"', + `Bearer error="insufficient_scope", resource_metadata="https://mcp.example.test/.well-known/oauth-protected-resource/mcp", error_description="This credential's scope does not cover this request"`, ); expect((await response.json()).error_description).toBe( "This credential's scope does not cover this request", @@ -764,11 +764,44 @@ describe("connection scope failures through the handler", () => { const response = await POST(initializeRequest()); expect(response.status).toBe(403); + expect(response.headers.get("WWW-Authenticate")).toBeNull(); expect((await response.json()).error).toBe("insufficient_scope"); expect(captured[0]?.upstreamStatusCode).toBe(403); expect(captured[0]?.responseStatusCode).toBe(403); }); + test("forwards an API challenge with this server's resource metadata", async () => { + failingAuthContext( + Object.assign(new Error("missing permission"), { + status: 403, + headers: new Headers({ + "WWW-Authenticate": + 'Bearer error="insufficient_scope", scope="browsers:use profiles:create", resource_metadata="https://api.example.test/.well-known/oauth-protected-resource", error_description="Sign in again and grant profiles:create"', + }), + }), + ); + + const response = await POST(initializeRequest()); + + expect(response.status).toBe(403); + expect(response.headers.get("WWW-Authenticate")).toBe( + 'Bearer error="insufficient_scope", scope="browsers:use profiles:create", resource_metadata="https://mcp.example.test/.well-known/oauth-protected-resource/mcp", error_description="Sign in again and grant profiles:create"', + ); + expect(await response.json()).toEqual({ + error: "insufficient_scope", + error_description: "Sign in again and grant profiles:create", + }); + expect(captured).toEqual([ + { + stage: "scope", + outcome: "rejected", + credentialType: "api_key", + upstreamStatusCode: 403, + responseStatusCode: 403, + }, + ]); + }); + test("answers an upstream outage with a retryable 503", async () => { failingAuthContext( Object.assign(new Error("unavailable"), { status: 502 }), diff --git a/src/app/[transport]/route.ts b/src/app/[transport]/route.ts index 273e8cd6..047ecd80 100644 --- a/src/app/[transport]/route.ts +++ b/src/app/[transport]/route.ts @@ -12,6 +12,8 @@ import { isNativeOAuthCredential, } from "@/lib/native-oauth"; import { oauthResourceMetadataUrl } from "@/lib/oauth-discovery"; +import { mcpScopeChallenge } from "@/lib/scope-challenge"; +import { returnScopeChallenges } from "@/lib/mcp/scope-challenge-results"; import { captureMcpConnectionScopeFailure, flushMcpAnalytics, @@ -149,16 +151,29 @@ export function connectionScopeFailureResponse( } if (failure.status === "rejected") { switch (failure.statusCode) { - case 403: + case 403: { + // Only a refusal that signing in again can fix carries a challenge; + // any other would send the client through consent in a loop. + const description = + failure.challenge?.description ?? + failure.description ?? + (failure.challenge + ? "This credential lacks a permission this request needs" + : "This credential is not scoped to the requested Kernel project"); return errorResponse( 403, "insufficient_scope", - failure.description ?? - "This credential is not scoped to the requested Kernel project", - { - "WWW-Authenticate": `Bearer realm="OAuth", error="insufficient_scope"`, - }, + description, + failure.challenge + ? { + "WWW-Authenticate": mcpScopeChallenge( + { ...failure.challenge, description }, + oauthResourceMetadataUrl(req), + ), + } + : {}, ); + } case 404: return errorResponse( 404, @@ -186,6 +201,7 @@ const handler = createMcpHandler(({ authInfo }) => { { name, version }, { instructions: MCP_SERVER_INSTRUCTIONS }, ); + returnScopeChallenges(server); instrumentMcpAnalytics(server); registerMcpCapabilities(server, { mcpApps: authInfo?.extra?.mcpApps === true, diff --git a/src/lib/mcp/apps/generated/managed-auth-app.ts b/src/lib/mcp/apps/generated/managed-auth-app.ts index ebeeef47..e97ad608 100644 --- a/src/lib/mcp/apps/generated/managed-auth-app.ts +++ b/src/lib/mcp/apps/generated/managed-auth-app.ts @@ -1,2 +1,2 @@ // Generated by scripts/build-managed-auth-app.mjs. Do not edit. -export const MANAGED_AUTH_APP_HTML = "\n\n\n\n\nKernel Managed Authentication\n\n\n
\n\n\n"; +export const MANAGED_AUTH_APP_HTML = "\n\n\n\n\nKernel Managed Authentication\n\n\n
\n\n\n"; diff --git a/src/lib/mcp/apps/managed-auth-flow.test.ts b/src/lib/mcp/apps/managed-auth-flow.test.ts index d2f0160a..8af5e1b0 100644 --- a/src/lib/mcp/apps/managed-auth-flow.test.ts +++ b/src/lib/mcp/apps/managed-auth-flow.test.ts @@ -38,6 +38,23 @@ function beginResult(state = "embedded_ready"): BeginResult { } describe("managed-auth App flow reducer", () => { + test("shows why the begin tool refused to start", () => { + const text = + "error in begin_auth_login (new_login): managed authentication needs a permission this connection lacks. Signing in again can grant auth_connections:create: ask the user to reconnect the KERNEL MCP server and allow it."; + expect( + managedAuthFlowReducer(initialManagedAuthFlowState, { + type: "BEGIN_RECEIVED", + result: { isError: true, content: [{ type: "text", text }] }, + }), + ).toMatchObject({ phase: "start_error", status: text }); + expect( + managedAuthFlowReducer(initialManagedAuthFlowState, { + type: "BEGIN_RECEIVED", + result: { isError: true }, + }).status, + ).toBe("Secure login could not start. Close this panel and retry."); + }); + test("moves from consent through pending to authenticated", () => { const starting = managedAuthFlowReducer(initialManagedAuthFlowState, { type: "BEGIN_REQUESTED", diff --git a/src/lib/mcp/apps/managed-auth-flow.ts b/src/lib/mcp/apps/managed-auth-flow.ts index d638a5ff..c16fedb1 100644 --- a/src/lib/mcp/apps/managed-auth-flow.ts +++ b/src/lib/mcp/apps/managed-auth-flow.ts @@ -34,11 +34,14 @@ export const initialManagedAuthFlowState: ManagedAuthFlowState = { status: "", }; -function toolErrorText(result: WaitToolResult): string { +function toolErrorText( + result: BeginResult | WaitToolResult, + fallback: string, +): string { const text = result.content?.find( (item) => item.type === "text" && typeof item.text === "string", )?.text; - return text || "Secure login status could not be verified. Close and retry."; + return text || fallback; } export function managedAuthFlowReducer( @@ -51,10 +54,14 @@ export function managedAuthFlowReducer( case "BEGIN_RECEIVED": { const connection = event.result.structuredContent?.connection; if (event.result.isError || !connection) { + const fallback = + "Secure login could not start. Close this panel and retry."; return { ...state, phase: "start_error", - status: "Secure login could not start. Close this panel and retry.", + status: event.result.isError + ? toolErrorText(event.result, fallback) + : fallback, }; } if (event.result.structuredContent?.state === "already_authenticated") { @@ -85,7 +92,10 @@ export function managedAuthFlowReducer( return { ...state, phase: "wait_error", - status: toolErrorText(event.result), + status: toolErrorText( + event.result, + "Secure login status could not be verified. Close and retry.", + ), }; } const connection = event.result.structuredContent?.connection ?? null; diff --git a/src/lib/mcp/auth-context.ts b/src/lib/mcp/auth-context.ts index 1b36e906..f3ffdbac 100644 --- a/src/lib/mcp/auth-context.ts +++ b/src/lib/mcp/auth-context.ts @@ -6,6 +6,7 @@ import { defaultMcpDependencies, type McpDependencies, } from "@/lib/mcp/dependencies"; +import { scopeChallengeOf, type ScopeChallenge } from "@/lib/scope-challenge"; const policyConditionSchema = z.object({ key: z.literal("source_ip"), @@ -92,7 +93,13 @@ type ResolveAuthContextOptions = { }; export type McpConnectionContextFailure = - | { status: "rejected"; statusCode: 401 | 403 | 404; description?: string } + | { + status: "rejected"; + statusCode: 401 | 403 | 404; + description?: string; + // Present when signing in again can grant what was refused. + challenge?: ScopeChallenge; + } | { status: "unavailable"; statusCode?: number } | { status: "invalid" }; @@ -115,9 +122,15 @@ function classifyAuthContextError(error: unknown): McpConnectionContextFailure { : undefined; if (typeof status === "number") { - if (status === 401 || status === 403 || status === 404) { + if (status === 401 || status === 404) { return { status: "rejected", statusCode: status }; } + if (status === 403) { + const challenge = scopeChallengeOf(error); + return challenge + ? { status: "rejected", statusCode: status, challenge } + : { status: "rejected", statusCode: status }; + } if (status === 408 || status === 429 || status >= 500) { return { status: "unavailable", statusCode: status }; } diff --git a/src/lib/mcp/responses.ts b/src/lib/mcp/responses.ts index c26eff97..0226b916 100644 --- a/src/lib/mcp/responses.ts +++ b/src/lib/mcp/responses.ts @@ -107,8 +107,8 @@ function errorMessage(error: unknown) { // org hitting its limits (429) or a fault on our side (5xx). Status codes only; the // message stays out. class ToolCallError extends Error { - constructor(name: string, message: string) { - super(message); + constructor(name: string, message: string, cause: unknown) { + super(message, { cause }); this.name = name; } } @@ -147,6 +147,7 @@ export function throwToolError( throw new ToolCallError( errorName(error), `error in ${toolName} (${action}): ${safeMessage ?? errorMessage(error)}${note ? ` ${note}` : ""}`, + error, ); } @@ -163,5 +164,6 @@ export function throwToolErrorWithApiBody( throw new ToolCallError( errorName(error), `error in ${toolName} (${action}): ${detail}${note}`, + error, ); } diff --git a/src/lib/mcp/scope-challenge-results.test.ts b/src/lib/mcp/scope-challenge-results.test.ts new file mode 100644 index 00000000..8164ce00 --- /dev/null +++ b/src/lib/mcp/scope-challenge-results.test.ts @@ -0,0 +1,168 @@ +/// +import { Client } from "@modelcontextprotocol/client"; +import { McpServer, InMemoryTransport } from "@modelcontextprotocol/server"; +import { APIError } from "@onkernel/sdk"; +import { describe, expect, test } from "bun:test"; +import { z } from "zod"; + +import { throwToolError } from "@/lib/mcp/responses"; +import { returnScopeChallenges } from "@/lib/mcp/scope-challenge-results"; +import { apiScopeChallenge, mcpScopeChallenge } from "@/lib/scope-challenge"; + +const API_CHALLENGE = + 'Bearer error="insufficient_scope", scope="browsers:use profiles:create", resource_metadata="https://api.onkernel.com/.well-known/oauth-protected-resource", error_description="Sign in again and grant profiles:create"'; +const MCP_CHALLENGE = + 'Bearer error="insufficient_scope", scope="browsers:use profiles:create", resource_metadata="https://mcp.onkernel.com/.well-known/oauth-protected-resource/mcp", error_description="Sign in again and grant profiles:create"'; + +function forbidden(headers: Record) { + return APIError.generate( + 403, + { + code: "insufficient_scope", + message: "This operation requires profiles:create on projects/p/*", + missing_scopes: ["profiles:create"], + }, + undefined, + new Headers(headers), + ); +} + +describe("scope challenges", () => { + test("reads the API's insufficient_scope challenge", () => { + expect( + apiScopeChallenge(new Headers({ "WWW-Authenticate": API_CHALLENGE })), + ).toEqual({ + scope: "browsers:use profiles:create", + description: "Sign in again and grant profiles:create", + }); + expect( + apiScopeChallenge( + new Headers({ + "WWW-Authenticate": + 'bearer scope=profiles:create, error="insufficient_scope"', + }), + ), + ).toEqual({ scope: "profiles:create", description: undefined }); + }); + + test("ignores anything else", () => { + for (const header of [ + 'Bearer error="invalid_token"', + 'Bearer resource_metadata="https://api.onkernel.com/.well-known/oauth-protected-resource"', + 'Basic realm="oauth"', + "", + ]) { + expect( + apiScopeChallenge(new Headers({ "WWW-Authenticate": header })), + ).toBeNull(); + } + expect(apiScopeChallenge(new Headers())).toBeNull(); + }); + + test("points the client at this server's resource metadata", () => { + expect( + mcpScopeChallenge( + apiScopeChallenge(new Headers({ "WWW-Authenticate": API_CHALLENGE }))!, + "https://mcp.onkernel.com/.well-known/oauth-protected-resource/mcp", + ), + ).toBe(MCP_CHALLENGE); + expect( + mcpScopeChallenge( + { description: 'a "quoted" \\ value' }, + "https://mcp.onkernel.com/.well-known/oauth-protected-resource/mcp", + ), + ).toBe( + 'Bearer error="insufficient_scope", resource_metadata="https://mcp.onkernel.com/.well-known/oauth-protected-resource/mcp", error_description="a quoted value"', + ); + }); +}); + +describe("tool calls the API refuses", () => { + async function callTool(error: unknown) { + const server = new McpServer({ name: "test", version: "0.0.0" }); + returnScopeChallenges(server); + server.registerTool( + "manage_profiles", + { inputSchema: z.object({}) }, + async () => { + throwToolError("manage_profiles", "create", error); + }, + ); + const client = new Client({ name: "test-client", version: "0.0.0" }); + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + await Promise.all([ + server.connect(serverTransport), + client.connect(clientTransport), + ]); + const result = await client.callTool({ + name: "manage_profiles", + arguments: {}, + }); + await client.close(); + return result; + } + + test("carry the challenge in _meta when signing in again can grant it", async () => { + const result = await callTool( + forbidden({ "WWW-Authenticate": API_CHALLENGE }), + ); + expect(result.isError).toBe(true); + expect(result._meta).toEqual({ "mcp/www_authenticate": [MCP_CHALLENGE] }); + expect(result.content).toEqual([ + { + type: "text", + text: "error in manage_profiles (create): 403 This operation requires profiles:create on projects/p/* [code: insufficient_scope] Signing in again can grant profiles:create: ask the user to reconnect the KERNEL MCP server and allow it.", + }, + ]); + }); + + test("stay plain tool errors otherwise", async () => { + for (const error of [ + forbidden({}), + APIError.generate( + 401, + undefined, + "unauthorized", + new Headers({ "WWW-Authenticate": API_CHALLENGE }), + ), + new Error("boom"), + ]) { + const result = await callTool(error); + expect(result.isError).toBe(true); + expect(result._meta).toBeUndefined(); + expect(JSON.stringify(result.content)).not.toContain("reconnect"); + } + }); + + test("name the metadata of the host the client connected to", async () => { + let registered: ((...params: unknown[]) => Promise) | undefined; + const server = { + registerTool: (_name: string, _config: unknown, callback: never) => { + registered = callback; + }, + } as unknown as McpServer; + returnScopeChallenges(server); + server.registerTool( + "manage_profiles", + { inputSchema: z.object({}) }, + async () => { + throwToolError( + "manage_profiles", + "create", + forbidden({ "WWW-Authenticate": API_CHALLENGE }), + ); + }, + ); + const result = (await registered!( + {}, + { http: { req: new Request("https://preview.example.test/mcp") } }, + )) as { _meta: Record }; + expect(result._meta["mcp/www_authenticate"]).toEqual([ + MCP_CHALLENGE.replace( + "https://mcp.onkernel.com/", + "https://preview.example.test/", + ), + ]); + }); +}); diff --git a/src/lib/mcp/scope-challenge-results.ts b/src/lib/mcp/scope-challenge-results.ts new file mode 100644 index 00000000..746d4c5b --- /dev/null +++ b/src/lib/mcp/scope-challenge-results.ts @@ -0,0 +1,62 @@ +import type { McpServer } from "@modelcontextprotocol/server"; +import { errorResponse } from "@/lib/mcp/responses"; +import { oauthResourceMetadataUrl } from "@/lib/oauth-discovery"; +import { mcpScopeChallenge, scopeChallengeOf } from "@/lib/scope-challenge"; + +const WWW_AUTHENTICATE_META = "mcp/www_authenticate"; + +// The API names the missing actions in the error body. +function reconnectNote(cause: unknown): string { + const body = (cause as { error?: { missing_scopes?: unknown } }).error; + const missing = Array.isArray(body?.missing_scopes) + ? body.missing_scopes.filter((scope) => typeof scope === "string") + : []; + const what = missing.length > 0 ? missing.join(", ") : "this permission"; + return `Signing in again can grant ${what}: ask the user to reconnect the KERNEL MCP server and allow it.`; +} + +type ToolCallback = (...params: unknown[]) => unknown; + +// A tool call the Kernel API refuses for a permission that signing in again +// can grant has already started, so this server cannot answer it with an +// HTTP 403 challenge: a client retrying the call could repeat work it already +// did. It fails as a tool error instead, carrying the challenge in +// _meta["mcp/www_authenticate"] for clients that step up from tool results. +export function returnScopeChallenges(server: McpServer) { + const registerTool = server.registerTool.bind(server) as ( + name: string, + config: unknown, + callback: ToolCallback, + ) => unknown; + server.registerTool = (( + name: string, + config: unknown, + callback: ToolCallback, + ) => + registerTool(name, config, async (...params: unknown[]) => { + try { + return await callback(...params); + } catch (error) { + const challenge = + error instanceof Error ? scopeChallengeOf(error.cause) : null; + if (!challenge) throw error; + // Name the metadata of the host the client connected to, as the + // transport's own challenges do. + const req = (params.at(-1) as { http?: { req?: Request } } | undefined) + ?.http?.req; + return { + ...errorResponse( + `${(error as Error).message} ${reconnectNote((error as Error).cause)}`, + ), + _meta: { + [WWW_AUTHENTICATE_META]: [ + mcpScopeChallenge( + challenge, + req ? oauthResourceMetadataUrl(req) : undefined, + ), + ], + }, + }; + } + })) as McpServer["registerTool"]; +} diff --git a/src/lib/mcp/tools/auth-login-app.ts b/src/lib/mcp/tools/auth-login-app.ts index 09f4b3f4..aba320fa 100644 --- a/src/lib/mcp/tools/auth-login-app.ts +++ b/src/lib/mcp/tools/auth-login-app.ts @@ -19,7 +19,8 @@ import { validateAuthLoginInput, } from "@/lib/mcp/tools/managed-auth-state"; import { managedAuthBrowserTelemetrySchema } from "@/lib/mcp/tools/managed-auth-telemetry"; -import { errorResponse } from "@/lib/mcp/responses"; +import { errorResponse, throwToolError } from "@/lib/mcp/responses"; +import { scopeChallengeOf } from "@/lib/scope-challenge"; import { DEPRECATED_TOOL_PARAMS, deprecatedParamConflict, @@ -264,6 +265,15 @@ export function registerAuthLoginApp(server: McpServer) { }, }; } catch (error) { + if (scopeChallengeOf(error)) { + throwToolError( + "open_auth_login", + input.mode, + error, + undefined, + "managed authentication needs a permission this connection lacks.", + ); + } return errorResponse( error instanceof AuthLoginStartError ? error.safeMessage @@ -358,6 +368,15 @@ export function registerAuthLoginApp(server: McpServer) { }, }; } catch (error) { + if (scopeChallengeOf(error)) { + throwToolError( + "begin_auth_login", + input.mode, + error, + undefined, + "managed authentication needs a permission this connection lacks.", + ); + } return errorResponse( error instanceof AuthLoginStartError ? error.safeMessage diff --git a/src/lib/mcp/tools/managed-auth-state.ts b/src/lib/mcp/tools/managed-auth-state.ts index f9d61983..72839746 100644 --- a/src/lib/mcp/tools/managed-auth-state.ts +++ b/src/lib/mcp/tools/managed-auth-state.ts @@ -10,6 +10,7 @@ import { } from "@/lib/mcp/tools/managed-auth-checkpoint"; import type { ManagedAuthBrowserTelemetry } from "@/lib/mcp/tools/managed-auth-telemetry"; import { proxyConfigError, type ProxyConfig } from "@/lib/mcp/proxy-config"; +import { scopeChallengeOf } from "@/lib/scope-challenge"; export type ManagedAuthRegion = | "us-east" @@ -325,7 +326,9 @@ export async function waitForAuthConnection( } } } catch (error) { - if (error instanceof AuthLoginStartError) throw error; + // A permission signing in again can grant will not appear by polling. + if (error instanceof AuthLoginStartError || scopeChallengeOf(error)) + throw error; } const remaining = deadline - Date.now(); diff --git a/src/lib/mcp/tools/managed-auth-wait.test.ts b/src/lib/mcp/tools/managed-auth-wait.test.ts index 64a669a8..8e879eef 100644 --- a/src/lib/mcp/tools/managed-auth-wait.test.ts +++ b/src/lib/mcp/tools/managed-auth-wait.test.ts @@ -43,6 +43,35 @@ function checkpoint( } describe("managed-auth wait", () => { + test("stops at a denial that signing in again can grant", async () => { + let retrieveCalls = 0; + const denied = Object.assign(new Error("forbidden"), { + status: 403, + headers: new Headers({ + "WWW-Authenticate": + 'Bearer error="insufficient_scope", scope="auth_connections:read auth_connections:use"', + }), + }); + const client = { + auth: { + connections: { + retrieve: async () => { + retrieveCalls++; + throw denied; + }, + }, + }, + } as unknown as KernelClient; + await expect( + waitForAuthConnection( + client, + { connectionId: "conn_1" }, + { timeoutMs: 50, pollIntervalMs: 1 }, + ), + ).rejects.toBe(denied); + expect(retrieveCalls).toBe(1); + }); + test("long-polls until an exact connection is authenticated", async () => { const { client, retrieveCalls } = waitClient({ states: [ diff --git a/src/lib/native-oauth.test.ts b/src/lib/native-oauth.test.ts index 067f3796..7a5bfd16 100644 --- a/src/lib/native-oauth.test.ts +++ b/src/lib/native-oauth.test.ts @@ -329,6 +329,7 @@ describe("native token exchange", () => { status: "rejected", statusCode: 403, description: "This credential's scope does not cover this request", + challenge: {}, }, ], [ diff --git a/src/lib/native-oauth.ts b/src/lib/native-oauth.ts index 05a63945..cdde5daa 100644 --- a/src/lib/native-oauth.ts +++ b/src/lib/native-oauth.ts @@ -14,6 +14,7 @@ import { } from "jose"; import { z } from "zod"; import { kernelDeployment, mcpServerOrigin } from "@/lib/oauth-discovery"; +import type { ScopeChallenge } from "@/lib/scope-challenge"; import { getNativeExchange, setNativeExchange } from "@/lib/redis"; // The Kernel issuer's access-token profile: at most 4 KiB, MCP-audience @@ -79,7 +80,12 @@ export type NativeCredential = { export type NativeOAuthResult = | { status: "ok"; credential: NativeCredential } - | { status: "rejected"; statusCode: 401 | 403; description: string } + | { + status: "rejected"; + statusCode: 401 | 403; + description: string; + challenge?: ScopeChallenge; + } | { status: "unavailable" }; type NativeOAuthFailure = Exclude; @@ -347,8 +353,9 @@ async function readExchangeResponse(response: Response): Promise { } // RFC 8693 errors from the issuer: an inactive grant rejects the credential -// and a scope it no longer covers is forbidden. Anything naming this -// server's request or client is a server fault, logged as an error. +// and a scope it no longer covers is forbidden, with a challenge to sign in +// again. Anything naming this server's request or client is a server fault, +// logged as an error. function exchangeFailure(status: number, body: unknown): NativeOAuthError { const error = z.object({ error: z.string() }).safeParse(body).data?.error; if (error === "invalid_grant") @@ -359,6 +366,7 @@ function exchangeFailure(status: number, body: unknown): NativeOAuthError { status: "rejected", statusCode: 403, description: "This credential's scope does not cover this request", + challenge: {}, }, "native exchange: scope not granted", ); diff --git a/src/lib/scope-challenge.ts b/src/lib/scope-challenge.ts new file mode 100644 index 00000000..d41f7063 --- /dev/null +++ b/src/lib/scope-challenge.ts @@ -0,0 +1,65 @@ +import { + mcpServerOrigin, + OAUTH_RESOURCE_METADATA_PATH, +} from "@/lib/oauth-discovery"; + +// What an RFC 6750 insufficient_scope challenge asks for: the scopes to sign +// in again with, when the challenger names them. +export type ScopeChallenge = { scope?: string; description?: string }; + +const AUTH_PARAM = /([A-Za-z0-9_-]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^\s,"]+))/g; + +function bearerParams(header: string): Map | null { + const match = /^\s*Bearer\s+([\s\S]*)$/i.exec(header); + if (!match) return null; + const params = new Map(); + for (const [, name, quoted, token] of match[1]!.matchAll(AUTH_PARAM)) { + const key = name!.toLowerCase(); + if (!params.has(key)) + params.set(key, quoted?.replace(/\\(.)/g, "$1") ?? token ?? ""); + } + return params; +} + +// The insufficient_scope challenge on a Kernel API response. The API sends +// one only when signing in again could grant what was denied; any other 403 +// carries none, and gets none from this server either. +export function apiScopeChallenge( + headers: Headers | null | undefined, +): ScopeChallenge | null { + const header = headers?.get("www-authenticate"); + if (!header) return null; + const params = bearerParams(header); + if (params?.get("error") !== "insufficient_scope") return null; + return { + scope: params.get("scope") || undefined, + description: params.get("error_description") || undefined, + }; +} + +// The scope challenge from an error a Kernel API call threw, if any. +export function scopeChallengeOf(error: unknown): ScopeChallenge | null { + if (!error || typeof error !== "object") return null; + const { status, headers } = error as { status?: unknown; headers?: unknown }; + if (status !== 403 || !(headers instanceof Headers)) return null; + return apiScopeChallenge(headers); +} + +function quoted(value: string): string { + return `"${value.replace(/["\\]/g, "")}"`; +} + +// The challenge this server sends: the same request for scopes, pointing at +// this server's protected resource metadata rather than the API's, since the +// client signs in again for the MCP resource. +export function mcpScopeChallenge( + challenge: ScopeChallenge, + resourceMetadataUrl = `${mcpServerOrigin()}${OAUTH_RESOURCE_METADATA_PATH}`, +): string { + const params = ['error="insufficient_scope"']; + if (challenge.scope) params.push(`scope=${quoted(challenge.scope)}`); + params.push(`resource_metadata=${quoted(resourceMetadataUrl)}`); + if (challenge.description) + params.push(`error_description=${quoted(challenge.description)}`); + return `Bearer ${params.join(", ")}`; +}