Public: anyone can read this; the crew can change it.
The MCP's 401 is one challenge from one function: it names the scopes, and says invalid_token when a presented token is expired or revoked #8365
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/8362-the-mcp-s-401-is-one-challenge-from-one → main 2 commits fork
5 files
changed +91
−7
src/http/mcp.ts +2 −2
| @@ -23,7 +23,7 @@ import { scopeAllows } from "../core/tokens.ts"; | ||
| 23 | 23 | import type { User } from "../core/users.ts"; |
| 24 | 24 | import type { Ctx, Handler } from "./context.ts"; |
| 25 | 25 | import { running } from "../kernel/version.ts"; |
| 26 | import { resourceMetadataUrl } from "./oauth.ts"; | |
| 26 | import { bearerChallenge } from "./oauth.ts"; | |
| 27 | 27 | import { body, boundedBody, json } from "./respond.ts"; |
| 28 | 28 | import type { Router } from "./router.ts"; |
| 29 | 29 | import { clientBucket } from "./peer.ts"; |
| @@ -382,7 +382,7 @@ export function mcpRoutes(router: Router<Handler>): void { | ||
| 382 | 382 | status: 401, |
| 383 | 383 | headers: { |
| 384 | 384 | "content-type": "application/json", |
| 385 | "www-authenticate": `Bearer realm="forge", resource_metadata="${resourceMetadataUrl(ctx.url.origin)}"`, | |
| 385 | "www-authenticate": bearerChallenge(ctx.url.origin, ctx.request), | |
| 386 | 386 | link: `<${ctx.url.origin}/llms.txt>; rel="service-doc"; type="text/markdown"`, |
| 387 | 387 | }, |
| 388 | 388 | }, |
src/http/oauth.ts +12 −3
| @@ -41,9 +41,18 @@ const limiterOf = (app: App): RateLimiter => { | ||
| 41 | 41 | export const resourceMetadataUrl = (origin: string): string => |
| 42 | 42 | `${origin}/.well-known/oauth-protected-resource`; |
| 43 | 43 | |
| 44 | /** The challenge a refused client learns where to sign in from; /mcp and the API send this one. */ | |
| 45 | export const bearerChallenge = (origin: string): string => | |
| 46 | `Bearer realm="forge", resource_metadata="${resourceMetadataUrl(origin)}"`; | |
| 44 | /** | |
| 45 | * The one challenge a refused client learns from; /mcp and the API send it. | |
| 46 | * It names the scopes, and says `invalid_token` (RFC 6750 §3) when a bearer | |
| 47 | * was sent and refused, so "sign in" and "re-authorize" are told apart. | |
| 48 | */ | |
| 49 | export const bearerChallenge = (origin: string, request?: Request): string => { | |
| 50 | const sent = /^Bearer\s+\S/i.test(request?.headers.get("authorization") ?? ""); | |
| 51 | return ( | |
| 52 | `Bearer realm="forge", resource_metadata="${resourceMetadataUrl(origin)}", scope="${OAUTH_SCOPES.join(" ")}"` + | |
| 53 | (sent ? `, error="invalid_token"` : "") | |
| 54 | ); | |
| 55 | }; | |
| 47 | 56 | |
| 48 | 57 | const open = { "access-control-allow-origin": "*" }; |
| 49 | 58 | const docHeaders = { ...open, "cache-control": "public, max-age=300" }; |
src/http/server.ts +1 −1
| @@ -2346,7 +2346,7 @@ export async function serve(app: App): Promise<Servers> { | ||
| 2346 | 2346 | if (response.status === 401 && !response.headers.has("www-authenticate")) { |
| 2347 | 2347 | const url = publicUrl(request, owner.config.url); |
| 2348 | 2348 | if (url.pathname.startsWith("/api/v1/")) |
| 2349 | response.headers.set("www-authenticate", bearerChallenge(url.origin)); | |
| 2349 | response.headers.set("www-authenticate", bearerChallenge(url.origin, request)); | |
| 2350 | 2350 | } |
| 2351 | 2351 | const done = await compress(request, response).then(securityFloor).then((r) => privateWhenSignedIn(request, r)); |
| 2352 | 2352 | if (namesFrame(request)) notePhase(request, "compress", performance.now() - compressing); |
test/oauth-challenge.test.ts added +75
| @@ -0,0 +1,75 @@ | ||
| 1 | /** | |
| 2 | * The 401 on /mcp and on the API is one challenge from one function: it names | |
| 3 | * the scopes, and says invalid_token only when a bearer was sent and refused. | |
| 4 | */ | |
| 5 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 6 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 7 | import { tmpdir } from "node:os"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { createApp, type App } from "../src/app.ts"; | |
| 10 | import { createToken } from "../src/core/tokens.ts"; | |
| 11 | import { createUser } from "../src/core/users.ts"; | |
| 12 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 13 | ||
| 14 | const BASE = `Bearer realm="forge", resource_metadata="https://forge.example/.well-known/oauth-protected-resource", scope="ro rw"`; | |
| 15 | ||
| 16 | describe("the bearer challenge", () => { | |
| 17 | let dataDir: string; | |
| 18 | let app: App; | |
| 19 | let servers: Servers; | |
| 20 | let expired = ""; | |
| 21 | ||
| 22 | beforeAll(async () => { | |
| 23 | dataDir = await mkdtemp(join(tmpdir(), "forge-challenge-")); | |
| 24 | app = createApp({ dataDir, port: 0, url: "https://forge.example" }); | |
| 25 | servers = await serve(app); | |
| 26 | const made = await createUser(app.db, { | |
| 27 | origin: "seed", | |
| 28 | trusted: true, | |
| 29 | username: "alice", | |
| 30 | email: "[email protected]", | |
| 31 | password: "a-good-passphrase", | |
| 32 | adminIfFirst: true, | |
| 33 | }); | |
| 34 | if (!made.ok) throw new Error(made.error); | |
| 35 | expired = createToken(app.db, made.value.id, "old", "rw", { | |
| 36 | expiresAt: new Date(Date.now() - 60_000).toISOString(), | |
| 37 | }).token; | |
| 38 | }, 30_000); | |
| 39 | afterAll(async () => { | |
| 40 | servers.stop(); | |
| 41 | app.close(); | |
| 42 | await rm(dataDir, { recursive: true, force: true }); | |
| 43 | }); | |
| 44 | ||
| 45 | const mcp = (authorization?: string) => | |
| 46 | fetch(`${servers.url}/mcp`, { | |
| 47 | method: "POST", | |
| 48 | headers: { "content-type": "application/json", ...(authorization ? { authorization } : {}) }, | |
| 49 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }), | |
| 50 | }); | |
| 51 | const api = (authorization?: string) => | |
| 52 | fetch(`${servers.url}/api/v1/repos`, { | |
| 53 | method: "POST", | |
| 54 | headers: { "content-type": "application/json", ...(authorization ? { authorization } : {}) }, | |
| 55 | body: "{}", | |
| 56 | }); | |
| 57 | ||
| 58 | for (const [name, call] of [["/mcp", mcp], ["the API", api]] as const) { | |
| 59 | test(`${name}: no token is the plain challenge with scopes`, async () => { | |
| 60 | const res = await call(); | |
| 61 | expect(res.status).toBe(401); | |
| 62 | expect(res.headers.get("www-authenticate")).toBe(BASE); | |
| 63 | }); | |
| 64 | test(`${name}: a garbage token is invalid_token`, async () => { | |
| 65 | const res = await call("Bearer forge_nonsense"); | |
| 66 | expect(res.status).toBe(401); | |
| 67 | expect(res.headers.get("www-authenticate")).toBe(`${BASE}, error="invalid_token"`); | |
| 68 | }); | |
| 69 | test(`${name}: an expired token is invalid_token`, async () => { | |
| 70 | const res = await call(`Bearer ${expired}`); | |
| 71 | expect(res.status).toBe(401); | |
| 72 | expect(res.headers.get("www-authenticate")).toBe(`${BASE}, error="invalid_token"`); | |
| 73 | }); | |
| 74 | } | |
| 75 | }); |
test/oauth-discovery.test.ts +1 −1
| @@ -71,7 +71,7 @@ describe("oauth discovery and registration", () => { | ||
| 71 | 71 | }); |
| 72 | 72 | |
| 73 | 73 | test("a 401 from the API carries the same challenge as /mcp", async () => { |
| 74 | const want = `Bearer realm="forge", resource_metadata="${base}/.well-known/oauth-protected-resource"`; | |
| 74 | const want = `Bearer realm="forge", resource_metadata="${base}/.well-known/oauth-protected-resource", scope="ro rw"`; | |
| 75 | 75 | const mcp = await fetch(`${base}/mcp`, { |
| 76 | 76 | method: "POST", |
| 77 | 77 | headers: { "content-type": "application/json" }, |
new above
offline