fix(oauth): keep the server's path in the fallback authorization-server URL
When RFC 9728 protected-resource metadata names no authorization server, the
MCP server URL stands in as one. `getAuthorizationServerUrl` built that with
`new URL("/", serverUrl)`, which discards the path — exactly the part discovery
needs when the server is not hosted at the domain root. The SDK's
`buildDiscoveryUrls` derives the path-scoped well-known locations from that
pathname, so an origin-only value could only ever probe the domain root, which
404s for a server like `https://example.com/mod/minilesson/mcp.php`.
Keep the path (and strip query/fragment, which an RFC 8414 issuer never
carries). A straight swap would regress the case the origin-only value did
serve — a server that merely lives under a path while publishing its metadata
at the root — so the URL becomes the first of two candidates:
`getAuthorizationServerUrlCandidates` yields the path-scoped form then the bare
origin, and `discoverAuthorizationServerMetadataForServer` walks them, treating
a candidate's failure as non-fatal while another remains and rethrowing the
first error only when all of them fail.
`discoverScopes` and the CIMD pre-registration probe both go through the walk.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013hzwzS8UvBsr4yZm7o7sev
Signed-off-by: cliffhall <cliff@futurescale.com>
This commit is contained in:
parent
ca2846de28
commit
afa0ba6eeb
4 changed files with 292 additions and 21 deletions
18
AGENTS.md
18
AGENTS.md
|
|
@ -73,6 +73,24 @@ v2/main/
|
|||
│ │ # the advertised document rather than a
|
||||
│ │ # location derived from the MCP server
|
||||
│ │ # URL — #2071;
|
||||
│ │ # discovery.ts the authorization-server
|
||||
│ │ # URL POLICY — when protected-resource
|
||||
│ │ # metadata names no authorization
|
||||
│ │ # server, the MCP server URL stands in,
|
||||
│ │ # and its PATH is load-bearing: the
|
||||
│ │ # SDK's buildDiscoveryUrls derives the
|
||||
│ │ # path-scoped well-known locations from
|
||||
│ │ # that pathname, so reducing it to the
|
||||
│ │ # origin can only ever probe the domain
|
||||
│ │ # root. getAuthorizationServerUrlCandidates
|
||||
│ │ # therefore yields the path-scoped URL
|
||||
│ │ # FIRST and the bare origin second, and
|
||||
│ │ # discoverAuthorizationServerMetadataForServer
|
||||
│ │ # walks them — the second candidate is
|
||||
│ │ # what keeps a server that merely lives
|
||||
│ │ # under a path while publishing metadata
|
||||
│ │ # at the root working, so do not drop it
|
||||
│ │ # in favour of a straight swap — #2110;
|
||||
│ │ # scopes.ts SEP-2350 scope union, oauthUx.ts
|
||||
│ │ # shared copy, mcpAuth.ts force-reauthorization,
|
||||
│ │ # issuerBinding.ts SEP-2352 callback-leg failure
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import {
|
||||
discoverAuthorizationServerMetadataForServer,
|
||||
discoverScopes,
|
||||
getAuthorizationServerUrl,
|
||||
getAuthorizationServerUrlCandidates,
|
||||
} from "@inspector/core/auth/discovery.js";
|
||||
import type { OAuthProtectedResourceMetadata } from "@modelcontextprotocol/client";
|
||||
|
||||
|
|
@ -335,3 +337,172 @@ describe("getAuthorizationServerUrl", () => {
|
|||
expect(captured?.message).toMatch(/Invalid MCP server URL: "" \(.+\)/);
|
||||
});
|
||||
});
|
||||
|
||||
// #2110: an MCP server hosted under a path (Moodle, a WordPress plugin, any
|
||||
// PHP endpoint) publishes its OAuth metadata under that same path. Reducing the
|
||||
// fallback authorization-server URL to the origin threw that path away, so
|
||||
// discovery could only ever probe the domain root and 404'd.
|
||||
describe("path-hosted MCP servers (#2110)", () => {
|
||||
const pathServerUrl = "https://misc.example.com/mod/minilesson/mcp.php";
|
||||
|
||||
describe("getAuthorizationServerUrl", () => {
|
||||
it("keeps the server's path in the fallback URL", () => {
|
||||
expect(getAuthorizationServerUrl(pathServerUrl)).toEqual(
|
||||
new URL(pathServerUrl),
|
||||
);
|
||||
});
|
||||
|
||||
it("strips query and fragment, which an RFC 8414 issuer never carries", () => {
|
||||
expect(
|
||||
getAuthorizationServerUrl(`${pathServerUrl}?session=abc#frag`),
|
||||
).toEqual(new URL(pathServerUrl));
|
||||
});
|
||||
});
|
||||
|
||||
describe("getAuthorizationServerUrlCandidates", () => {
|
||||
it("tries the path-scoped URL before the bare origin", () => {
|
||||
expect(getAuthorizationServerUrlCandidates(pathServerUrl)).toEqual([
|
||||
new URL(pathServerUrl),
|
||||
new URL("https://misc.example.com/"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("offers a single candidate for a root-hosted server", () => {
|
||||
expect(
|
||||
getAuthorizationServerUrlCandidates("https://mcp.example.com"),
|
||||
).toEqual([new URL("https://mcp.example.com/")]);
|
||||
});
|
||||
|
||||
it("does not probe past an authorization server named by resource metadata", () => {
|
||||
const resourceMetadata: OAuthProtectedResourceMetadata = {
|
||||
resource: pathServerUrl,
|
||||
authorization_servers: ["https://auth.example.com/realms/r"],
|
||||
};
|
||||
expect(
|
||||
getAuthorizationServerUrlCandidates(pathServerUrl, resourceMetadata),
|
||||
).toEqual([new URL("https://auth.example.com/realms/r")]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("discoverAuthorizationServerMetadataForServer", () => {
|
||||
const metadata = {
|
||||
issuer: pathServerUrl,
|
||||
authorization_endpoint: "https://misc.example.com/mod/authorize.php",
|
||||
token_endpoint: "https://misc.example.com/mod/token.php",
|
||||
response_types_supported: ["code"],
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("returns the path-scoped result without probing the origin", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/client");
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue(
|
||||
metadata,
|
||||
);
|
||||
|
||||
await expect(
|
||||
discoverAuthorizationServerMetadataForServer(pathServerUrl),
|
||||
).resolves.toEqual(metadata);
|
||||
expect(discoverAuthorizationServerMetadata).toHaveBeenCalledTimes(1);
|
||||
expect(discoverAuthorizationServerMetadata).toHaveBeenCalledWith(
|
||||
new URL(pathServerUrl),
|
||||
{ fetchFn: undefined },
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to the origin when the path-scoped candidate has no metadata", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/client");
|
||||
vi.mocked(discoverAuthorizationServerMetadata)
|
||||
.mockResolvedValueOnce(undefined)
|
||||
.mockResolvedValueOnce(metadata);
|
||||
|
||||
await expect(
|
||||
discoverAuthorizationServerMetadataForServer(pathServerUrl),
|
||||
).resolves.toEqual(metadata);
|
||||
expect(discoverAuthorizationServerMetadata).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
new URL("https://misc.example.com/"),
|
||||
{ fetchFn: undefined },
|
||||
);
|
||||
});
|
||||
|
||||
it("survives a throwing candidate while another remains", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/client");
|
||||
vi.mocked(discoverAuthorizationServerMetadata)
|
||||
.mockRejectedValueOnce(new Error("issuer mismatch"))
|
||||
.mockResolvedValueOnce(metadata);
|
||||
|
||||
await expect(
|
||||
discoverAuthorizationServerMetadataForServer(pathServerUrl),
|
||||
).resolves.toEqual(metadata);
|
||||
});
|
||||
|
||||
it("rethrows the first error when every candidate fails", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/client");
|
||||
vi.mocked(discoverAuthorizationServerMetadata)
|
||||
.mockRejectedValueOnce(new Error("path-scoped failed"))
|
||||
.mockRejectedValueOnce(new Error("origin failed"));
|
||||
|
||||
await expect(
|
||||
discoverAuthorizationServerMetadataForServer(pathServerUrl),
|
||||
).rejects.toThrow("path-scoped failed");
|
||||
});
|
||||
|
||||
it("resolves undefined when every candidate answers with no metadata", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/client");
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue(
|
||||
undefined,
|
||||
);
|
||||
|
||||
await expect(
|
||||
discoverAuthorizationServerMetadataForServer(pathServerUrl),
|
||||
).resolves.toBeUndefined();
|
||||
expect(discoverAuthorizationServerMetadata).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("passes the caller's fetch through to every candidate", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/client");
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue(
|
||||
undefined,
|
||||
);
|
||||
const fetchFn = vi.fn();
|
||||
|
||||
await discoverAuthorizationServerMetadataForServer(
|
||||
pathServerUrl,
|
||||
undefined,
|
||||
fetchFn as unknown as typeof fetch,
|
||||
);
|
||||
|
||||
expect(discoverAuthorizationServerMetadata).toHaveBeenCalledWith(
|
||||
new URL(pathServerUrl),
|
||||
{ fetchFn },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("discoverScopes reaches a path-hosted authorization server", async () => {
|
||||
const { discoverAuthorizationServerMetadata } =
|
||||
await import("@modelcontextprotocol/client");
|
||||
vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({
|
||||
issuer: pathServerUrl,
|
||||
authorization_endpoint: "https://misc.example.com/mod/authorize.php",
|
||||
token_endpoint: "https://misc.example.com/mod/token.php",
|
||||
response_types_supported: ["code"],
|
||||
scopes_supported: ["read"],
|
||||
});
|
||||
|
||||
await expect(discoverScopes(pathServerUrl)).resolves.toBe("read");
|
||||
expect(discoverAuthorizationServerMetadata).toHaveBeenCalledWith(
|
||||
new URL(pathServerUrl),
|
||||
{ fetchFn: undefined },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,9 +1,6 @@
|
|||
import {
|
||||
discoverAuthorizationServerMetadata,
|
||||
discoverOAuthProtectedResourceMetadata,
|
||||
} from "@modelcontextprotocol/client";
|
||||
import { discoverOAuthProtectedResourceMetadata } from "@modelcontextprotocol/client";
|
||||
import type { OAuthClientInformation } from "@modelcontextprotocol/client";
|
||||
import { getAuthorizationServerUrl } from "./discovery.js";
|
||||
import { discoverAuthorizationServerMetadataForServer } from "./discovery.js";
|
||||
import type { BaseOAuthClientProvider } from "./providers.js";
|
||||
|
||||
/**
|
||||
|
|
@ -49,14 +46,14 @@ export async function ensureCimdClientRegistration(params: {
|
|||
resourceMetadata = undefined;
|
||||
}
|
||||
|
||||
const authServerUrl = getAuthorizationServerUrl(
|
||||
// Walks the path-scoped authorization-server URL before the bare origin, so a
|
||||
// server hosted under a path is probed where it actually publishes its
|
||||
// metadata rather than only at the domain root (#2110).
|
||||
const metadata = await discoverAuthorizationServerMetadataForServer(
|
||||
params.serverUrl,
|
||||
resourceMetadata,
|
||||
params.fetchFn,
|
||||
);
|
||||
|
||||
const metadata = await discoverAuthorizationServerMetadata(authServerUrl, {
|
||||
...(params.fetchFn && { fetchFn: params.fetchFn }),
|
||||
});
|
||||
if (!metadata?.client_id_metadata_document_supported) return;
|
||||
|
||||
const clientInformation: OAuthClientInformation = {
|
||||
|
|
|
|||
|
|
@ -2,6 +2,38 @@ import { discoverAuthorizationServerMetadata } from "@modelcontextprotocol/clien
|
|||
import type { OAuthProtectedResourceMetadata } from "@modelcontextprotocol/client";
|
||||
import { parseHttpUrl } from "./utils.js";
|
||||
|
||||
type AuthorizationServerMetadata = Awaited<
|
||||
ReturnType<typeof discoverAuthorizationServerMetadata>
|
||||
>;
|
||||
|
||||
/**
|
||||
* The MCP server's own URL, used as the authorization server when RFC 9728
|
||||
* protected-resource metadata named none.
|
||||
*
|
||||
* The path is kept. Reducing it to the origin (`new URL("/", serverUrl)`)
|
||||
* discards exactly the part that tells discovery where to look when the server
|
||||
* is not hosted at the domain root: the SDK's `buildDiscoveryUrls` derives the
|
||||
* path-scoped well-known locations — `/.well-known/oauth-authorization-server{path}`
|
||||
* and `{path}/.well-known/openid-configuration` — from this URL's pathname, so
|
||||
* an origin-only value can only ever probe the domain root (#2110).
|
||||
*
|
||||
* Query and fragment are stripped: an RFC 8414 issuer identifier carries
|
||||
* neither, and the SDK compares the discovered `issuer` against this URL.
|
||||
*/
|
||||
function serverUrlAsAuthorizationServer(serverUrl: string): URL {
|
||||
try {
|
||||
const url = new URL(serverUrl);
|
||||
url.search = "";
|
||||
url.hash = "";
|
||||
return url;
|
||||
} catch (err) {
|
||||
const detail = err instanceof Error ? err.message : String(err);
|
||||
throw new Error(`Invalid MCP server URL: "${serverUrl}" (${detail})`, {
|
||||
cause: err,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the URL to use for OAuth authorization server metadata discovery.
|
||||
* Uses resource metadata's authorization_servers[0] when present, otherwise the MCP server URL.
|
||||
|
|
@ -15,14 +47,69 @@ export function getAuthorizationServerUrl(
|
|||
if (first) {
|
||||
return parseHttpUrl(first, "protected resource authorization_servers[0]");
|
||||
}
|
||||
try {
|
||||
return new URL("/", serverUrl);
|
||||
} catch (err) {
|
||||
const detail = err instanceof Error ? err.message : String(err);
|
||||
throw new Error(`Invalid MCP server URL: "${serverUrl}" (${detail})`, {
|
||||
cause: err,
|
||||
});
|
||||
return serverUrlAsAuthorizationServer(serverUrl);
|
||||
}
|
||||
|
||||
/**
|
||||
* The authorization-server URLs to try, in order.
|
||||
*
|
||||
* When protected-resource metadata names an authorization server there is
|
||||
* exactly one candidate — the server told us where to look, and probing past it
|
||||
* would be guessing. Otherwise the MCP server URL itself stands in as the
|
||||
* authorization server, and a path-hosted server has two plausible answers: the
|
||||
* full URL, whose path-scoped well-known locations are what a server like
|
||||
* `https://example.com/mod/minilesson/mcp.php` publishes, and the bare origin,
|
||||
* used by a server that merely *lives* under a path while publishing its
|
||||
* metadata at the domain root. Trying the path-scoped form first fixes #2110
|
||||
* without regressing the root-hosted case, which is all the origin-only value
|
||||
* ever served.
|
||||
*/
|
||||
export function getAuthorizationServerUrlCandidates(
|
||||
serverUrl: string,
|
||||
resourceMetadata?: OAuthProtectedResourceMetadata | null,
|
||||
): URL[] {
|
||||
const primary = getAuthorizationServerUrl(serverUrl, resourceMetadata);
|
||||
const namedByMetadata = Boolean(resourceMetadata?.authorization_servers?.[0]);
|
||||
if (namedByMetadata || primary.pathname === "/") return [primary];
|
||||
return [primary, new URL("/", primary)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Discovers authorization server metadata for an MCP server, walking the
|
||||
* candidates above until one answers.
|
||||
*
|
||||
* A candidate that fails — a 5xx, or an RFC 8414 §3.3 issuer mismatch, both of
|
||||
* which the SDK raises rather than returning `undefined` — is not fatal while
|
||||
* another candidate remains. If every candidate fails, the first error is
|
||||
* rethrown, so a caller still sees the original diagnosis rather than a bare
|
||||
* `undefined`.
|
||||
*/
|
||||
export async function discoverAuthorizationServerMetadataForServer(
|
||||
serverUrl: string,
|
||||
resourceMetadata?: OAuthProtectedResourceMetadata | null,
|
||||
fetchFn?: typeof fetch,
|
||||
): Promise<AuthorizationServerMetadata> {
|
||||
const candidates = getAuthorizationServerUrlCandidates(
|
||||
serverUrl,
|
||||
resourceMetadata,
|
||||
);
|
||||
let firstError: unknown;
|
||||
let sawError = false;
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
const metadata = await discoverAuthorizationServerMetadata(candidate, {
|
||||
fetchFn,
|
||||
});
|
||||
if (metadata) return metadata;
|
||||
} catch (err) {
|
||||
if (!sawError) {
|
||||
firstError = err;
|
||||
sawError = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (sawError) throw firstError;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -38,13 +125,11 @@ export const discoverScopes = async (
|
|||
fetchFn?: typeof fetch,
|
||||
): Promise<string | undefined> => {
|
||||
try {
|
||||
const authServerUrl = getAuthorizationServerUrl(
|
||||
const metadata = await discoverAuthorizationServerMetadataForServer(
|
||||
serverUrl,
|
||||
resourceMetadata,
|
||||
);
|
||||
const metadata = await discoverAuthorizationServerMetadata(authServerUrl, {
|
||||
fetchFn,
|
||||
});
|
||||
);
|
||||
|
||||
// Prefer resource metadata scopes, but fall back to OAuth metadata if empty
|
||||
const resourceScopes = resourceMetadata?.scopes_supported;
|
||||
|
|
|
|||
Loading…
Reference in a new issue