Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 25 additions & 8 deletions docs/native-oauth.md
Original file line number Diff line number Diff line change
Expand Up @@ -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="<this server>/.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

Expand Down
35 changes: 34 additions & 1 deletion src/app/[transport]/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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 }),
Expand Down
28 changes: 22 additions & 6 deletions src/app/[transport]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion src/lib/mcp/apps/generated/managed-auth-app.ts

Large diffs are not rendered by default.

17 changes: 17 additions & 0 deletions src/lib/mcp/apps/managed-auth-flow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
18 changes: 14 additions & 4 deletions src/lib/mcp/apps/managed-auth-flow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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") {
Expand Down Expand Up @@ -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;
Expand Down
17 changes: 15 additions & 2 deletions src/lib/mcp/auth-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down Expand Up @@ -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" };

Expand All @@ -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 };
}
Expand Down
6 changes: 4 additions & 2 deletions src/lib/mcp/responses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
Expand Down Expand Up @@ -147,6 +147,7 @@ export function throwToolError(
throw new ToolCallError(
errorName(error),
`error in ${toolName} (${action}): ${safeMessage ?? errorMessage(error)}${note ? ` ${note}` : ""}`,
error,
);
}

Expand All @@ -163,5 +164,6 @@ export function throwToolErrorWithApiBody(
throw new ToolCallError(
errorName(error),
`error in ${toolName} (${action}): ${detail}${note}`,
error,
);
}
Loading
Loading