fix: serve RFC 9728 path-suffixed metadata, document connector redirect URIs
Two separate discovery footguns, both found while debugging an Authentik "Redirect URI Error" on a claude.ai custom connector. RFC 9728 §3.1 puts the metadata for a resource identified by `https://host/api/mcp` at `/.well-known/oauth-protected-resource/api/mcp`. Only the root form was served, so clients that derive the metadata URL from the MCP endpoint URL — rather than reading `resource_metadata` off our 401 — got Next.js's HTML 404 and failed discovery with a JSON parse error. Add a `[...path]` route serving the same document with `resource` naming the suffixed identifier (§3.3 has the client compare it as an exact string, so echoing the bare origin would be rejected). The document body moves to `lib/auth/resource-metadata.ts` so the two routes cannot drift apart on `scopes_supported` — a divergence there costs you the `aud` claim or the refresh token. Paths are allowlisted rather than wildcarded so this cannot advertise resources the app does not serve. `buildWwwAuthenticate()` still points at the root URL; this change is purely additive. Separately, the redirect URIs an MCP provider needs depend on how clients reach it: a loopback URI for the CLI, `https://claude.ai/api/mcp/auth_callback` for a claude.ai custom connector. Registering only the former is what produces the "Redirect URI Error" page, and a portless `http://localhost/callback` entry matches nothing the CLI sends. Document both, keyed on the literal error text, and note that DCR is enterprise-gated on Authentik so these are hand-registered on a FOSS instance. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
|
||||
/**
|
||||
* RFC 9728 §3.1 puts the metadata for `https://host/api/mcp` at
|
||||
* `https://host/.well-known/oauth-protected-resource/api/mcp`. MCP clients
|
||||
* that derive that URL from the endpoint URL — instead of following the
|
||||
* `resource_metadata` parameter on our 401 — used to receive the Next.js 404
|
||||
* HTML page here, so discovery died on a JSON parse error.
|
||||
*
|
||||
* Two things therefore have to hold, and both are easy to break silently:
|
||||
* the document must name the SUFFIXED resource (§3.3 has the client reject a
|
||||
* document whose `resource` isn't the identifier it asked about), and it must
|
||||
* stay byte-for-byte in step with the root document's scope list, because a
|
||||
* scope missing from whichever document a given client reads is a scope that
|
||||
* client will never request.
|
||||
*/
|
||||
|
||||
type Metadata = { resource: string; scopes_supported: string[] };
|
||||
|
||||
async function fetchSuffixed(
|
||||
segments: string[],
|
||||
): Promise<{ status: number; body: Metadata }> {
|
||||
vi.resetModules();
|
||||
const { GET } = await import(
|
||||
"@/app/.well-known/oauth-protected-resource/[...path]/route"
|
||||
);
|
||||
const res = await GET(new Request("http://localhost/ignored"), {
|
||||
params: Promise.resolve({ path: segments }),
|
||||
});
|
||||
return { status: res.status, body: (await res.json()) as Metadata };
|
||||
}
|
||||
|
||||
async function fetchRoot(): Promise<Metadata> {
|
||||
vi.resetModules();
|
||||
const { GET } = await import("@/app/.well-known/oauth-protected-resource/route");
|
||||
return (await GET().json()) as Metadata;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env.OIDC_OFFLINE_ACCESS;
|
||||
delete process.env.OIDC_AUDIENCE_SCOPE;
|
||||
});
|
||||
|
||||
describe("path-suffixed oauth-protected-resource metadata", () => {
|
||||
test("serves the MCP endpoint's document with the suffixed resource identifier", async () => {
|
||||
const { status, body } = await fetchSuffixed(["api", "mcp"]);
|
||||
|
||||
expect(status).toBe(200);
|
||||
// §3.3: a strict client compares this against the identifier it asked
|
||||
// about, so the bare origin would get the whole document rejected.
|
||||
expect(body.resource).toBe("http://localhost:3000/api/mcp");
|
||||
});
|
||||
|
||||
test("404s for a path this app does not serve, rather than advertising it", async () => {
|
||||
// The allowlist exists so we never claim that arbitrary paths are
|
||||
// OAuth-protected resources of this deployment.
|
||||
const { status } = await fetchSuffixed(["api", "not-mcp"]);
|
||||
|
||||
expect(status).toBe(404);
|
||||
});
|
||||
|
||||
test("advertises exactly the scopes the root document does", async () => {
|
||||
// Regression guard against the two documents drifting apart: the audience
|
||||
// scope is what makes `aud` appear on the token at all, and a client that
|
||||
// discovered us through the suffixed URL would never request a scope that
|
||||
// only the root document lists.
|
||||
process.env.OIDC_OFFLINE_ACCESS = "true";
|
||||
|
||||
const root = await fetchRoot();
|
||||
const { body: suffixed } = await fetchSuffixed(["api", "mcp"]);
|
||||
|
||||
expect(suffixed.scopes_supported).toEqual(root.scopes_supported);
|
||||
expect(suffixed.scopes_supported).toContain("aud-test-audience");
|
||||
expect(suffixed.scopes_supported).toContain("offline_access");
|
||||
});
|
||||
|
||||
test("honours an explicit audience scope name, like the root document", async () => {
|
||||
process.env.OIDC_AUDIENCE_SCOPE = "custom-aud-scope";
|
||||
|
||||
const root = await fetchRoot();
|
||||
const { body: suffixed } = await fetchSuffixed(["api", "mcp"]);
|
||||
|
||||
expect(suffixed.scopes_supported).toContain("custom-aud-scope");
|
||||
expect(suffixed.scopes_supported).toEqual(root.scopes_supported);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { buildResourceMetadata, publicOrigin } from "@/lib/auth/resource-metadata";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/**
|
||||
* Resource paths this deployment will publish metadata for.
|
||||
*
|
||||
* An allowlist rather than a wildcard, for two reasons. RFC 9728 §3.1 maps a
|
||||
* metadata URL to one specific protected resource, so answering for arbitrary
|
||||
* paths would advertise resources this app does not serve — a client could
|
||||
* "discover" `https://host/anything` as an OAuth-protected resource and be
|
||||
* told, wrongly, that tokens for it are obtainable from our IdP. And every
|
||||
* path that answers is surface: a wildcard turns this into an open reflector
|
||||
* that echoes attacker-chosen path segments back inside a JSON document.
|
||||
*
|
||||
* `api/mcp` is the only MCP endpoint here (app/api/mcp/route.ts). Add an
|
||||
* entry when a second one ships — not before.
|
||||
*/
|
||||
const METADATA_RESOURCE_PATHS: ReadonlySet<string> = new Set(["api/mcp"]);
|
||||
|
||||
/**
|
||||
* RFC 9728 §3.1 — path-suffixed protected resource metadata.
|
||||
*
|
||||
* For a resource identified by `https://host/api/mcp`, the spec puts its
|
||||
* metadata at `https://host/.well-known/oauth-protected-resource/api/mcp`:
|
||||
* the resource's path is appended to the well-known path. Clients that derive
|
||||
* the metadata URL from the MCP endpoint URL — rather than reading
|
||||
* `resource_metadata` off our 401's `WWW-Authenticate` header — probe that URL
|
||||
* first, and before this route existed they got Next.js's 404 HTML page, which
|
||||
* fails discovery with a JSON parse error rather than anything diagnosable.
|
||||
*
|
||||
* The document is identical to the root one except for `resource`, which must
|
||||
* name the suffixed identifier: §3.3 requires the client to check that the
|
||||
* returned `resource` equals the identifier it asked about, so echoing the
|
||||
* bare origin here would make a strict client reject the document outright.
|
||||
*/
|
||||
export async function GET(
|
||||
_req: Request,
|
||||
ctx: { params: Promise<{ path: string[] }> },
|
||||
): Promise<NextResponse> {
|
||||
const { path } = await ctx.params;
|
||||
// Segments arrive already percent-decoded and never empty, but join and
|
||||
// compare on the same normalized form the allowlist is written in.
|
||||
const resourcePath = path.join("/");
|
||||
|
||||
if (!METADATA_RESOURCE_PATHS.has(resourcePath)) {
|
||||
// JSON, not the HTML 404 page, so a client that probes a wrong path gets
|
||||
// a parseable answer instead of the failure mode this route exists to fix.
|
||||
return NextResponse.json(
|
||||
{ error: "not_found", error_description: "no such protected resource" },
|
||||
{ status: 404 },
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
buildResourceMetadata(`${publicOrigin()}/${resourcePath}`),
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { env } from "@/lib/env";
|
||||
import { mcpIssuer } from "@/lib/auth/jwt";
|
||||
import { buildResourceMetadata, publicOrigin } from "@/lib/auth/resource-metadata";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
@@ -10,36 +9,12 @@ export const dynamic = "force-dynamic";
|
||||
*
|
||||
* MCP clients discover the authorization server (Authentik) via this
|
||||
* endpoint after receiving a 401 with `WWW-Authenticate: resource_metadata=...`.
|
||||
*
|
||||
* This is the root form of the document, describing the deployment origin as
|
||||
* the protected resource. Clients that derive the metadata URL from the MCP
|
||||
* endpoint URL instead of following the header land on the path-suffixed form
|
||||
* (§3.1) served by the sibling `[...path]` route.
|
||||
*/
|
||||
export function GET() {
|
||||
const resource = env().PUBLIC_URL.replace(/\/$/, "");
|
||||
|
||||
// The audience scope MUST be advertised. Authentik only evaluates a scope
|
||||
// mapping when the client requests that scope by name, and the client only
|
||||
// learns scope names from this document. Omit it and every access token
|
||||
// arrives without `aud`, which jwt.ts rejects as "claim invalid: aud".
|
||||
const audienceScope =
|
||||
env().OIDC_AUDIENCE_SCOPE ?? `aud-${env().OIDC_AUDIENCE}`;
|
||||
|
||||
// Same mechanism as the audience scope, different consequence: a client
|
||||
// only requests `offline_access` if it sees the name here, and without
|
||||
// that request the IdP returns no refresh token — so the client cannot
|
||||
// renew and the user gets kicked back to an interactive login whenever
|
||||
// the access token expires.
|
||||
//
|
||||
// Opt-in, because the IdP needs a matching scope mapping; advertising one
|
||||
// it doesn't offer can fail the whole authorization request.
|
||||
const scopes = ["openid", "profile", "email", audienceScope];
|
||||
if (env().OIDC_OFFLINE_ACCESS) scopes.push("offline_access");
|
||||
|
||||
return NextResponse.json({
|
||||
resource,
|
||||
// The MCP application's issuer, which is not necessarily the Web UI's —
|
||||
// see mcpIssuer(). Advertising the wrong one sends clients to a discovery
|
||||
// document whose tokens this endpoint will then reject on `iss`.
|
||||
authorization_servers: [mcpIssuer()], // as configured, slash and all
|
||||
scopes_supported: scopes,
|
||||
bearer_methods_supported: ["header"],
|
||||
resource_documentation: `${resource}/`,
|
||||
});
|
||||
return NextResponse.json(buildResourceMetadata(publicOrigin()));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { env } from "@/lib/env";
|
||||
import { mcpIssuer } from "@/lib/auth/jwt";
|
||||
|
||||
/**
|
||||
* The protected-resource metadata document, RFC 9728 §2.
|
||||
*
|
||||
* Shared by both metadata routes — the root `/.well-known/oauth-protected-
|
||||
* resource` and the path-suffixed `/.well-known/oauth-protected-resource/
|
||||
* <resource path>` form of §3.1 — because the two documents differ ONLY in
|
||||
* the `resource` identifier they describe. Anything else drifting between
|
||||
* them is a bug: a client that discovers us through the suffixed URL would
|
||||
* be told to request a different scope set than one that follows the
|
||||
* `WWW-Authenticate: resource_metadata=...` header, and whichever of the two
|
||||
* lost the audience scope would hand back tokens with no `aud` claim.
|
||||
*/
|
||||
export interface ResourceMetadata {
|
||||
resource: string;
|
||||
authorization_servers: string[];
|
||||
scopes_supported: string[];
|
||||
bearer_methods_supported: string[];
|
||||
resource_documentation: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The public origin, with any trailing slash stripped.
|
||||
*
|
||||
* `resource` values are compared as exact strings by clients (RFC 9728 §3.3),
|
||||
* so `https://host/` and `https://host` are not interchangeable — PUBLIC_URL
|
||||
* is written both ways in the wild and only the stripped form is emitted.
|
||||
*/
|
||||
export function publicOrigin(): string {
|
||||
return env().PUBLIC_URL.replace(/\/$/, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the metadata document for `resource`.
|
||||
*
|
||||
* The caller supplies the resource identifier because it depends on which
|
||||
* URL the document was fetched from; everything else is deployment config.
|
||||
*/
|
||||
export function buildResourceMetadata(resource: string): ResourceMetadata {
|
||||
// The audience scope MUST be advertised. Authentik only evaluates a scope
|
||||
// mapping when the client requests that scope by name, and the client only
|
||||
// learns scope names from this document. Omit it and every access token
|
||||
// arrives without `aud`, which jwt.ts rejects as "claim invalid: aud".
|
||||
const audienceScope =
|
||||
env().OIDC_AUDIENCE_SCOPE ?? `aud-${env().OIDC_AUDIENCE}`;
|
||||
|
||||
// Same mechanism as the audience scope, different consequence: a client
|
||||
// only requests `offline_access` if it sees the name here, and without
|
||||
// that request the IdP returns no refresh token — so the client cannot
|
||||
// renew and the user gets kicked back to an interactive login whenever
|
||||
// the access token expires.
|
||||
//
|
||||
// Opt-in, because the IdP needs a matching scope mapping; advertising one
|
||||
// it doesn't offer can fail the whole authorization request.
|
||||
const scopes = ["openid", "profile", "email", audienceScope];
|
||||
if (env().OIDC_OFFLINE_ACCESS) scopes.push("offline_access");
|
||||
|
||||
return {
|
||||
resource,
|
||||
// The MCP application's issuer, which is not necessarily the Web UI's —
|
||||
// see mcpIssuer(). Advertising the wrong one sends clients to a discovery
|
||||
// document whose tokens this endpoint will then reject on `iss`.
|
||||
authorization_servers: [mcpIssuer()], // as configured, slash and all
|
||||
scopes_supported: scopes,
|
||||
bearer_methods_supported: ["header"],
|
||||
// Documentation lives at the site root regardless of which resource this
|
||||
// document describes, so it is always derived from the public origin and
|
||||
// not from `resource`.
|
||||
resource_documentation: `${publicOrigin()}/`,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user