Skip to content

Commit 545e4d5

Browse files
sdbrother0claude
andauthored
[Feat] Support custom MCP OAuth callback paths and WWW-Authenticate discovery (#2219)
* [Feat] Support custom MCP OAuth callback paths and WWW-Authenticate discovery Some authorization servers register static clients with a callback path other than /callback. The redirectUri option now accepts any path except the root path. The local callback server listens on that path. Some MCP servers host the protected resource metadata outside the RFC 9728 well-known URLs. When the well-known lookup fails, discovery now reads the resource_metadata URL from the 401 WWW-Authenticate header. Co-Authored-By: Claude Opus 5.5 <[email protected]> * [Fix] Give MCP OAuth discovery fallback its own timeout and parse resource_metadata case-insensitively Each protected resource metadata lookup now races its own timeout, so a slow well-known lookup no longer consumes the budget of the WWW-Authenticate fallback. The resource_metadata parameter of the Bearer challenge is matched case-insensitively, as RFC 9110 requires for authentication parameters. The probe test now asserts the initialize payload and MCP headers. Co-Authored-By: Claude Opus 5.5 <[email protected]> * [Fix] Validate MCP protected resource metadata and abort timed-out lookups Protected resource metadata whose resource does not match the server URL is now rejected on both the well-known and the WWW-Authenticate fallback paths (RFC 9728 §3.3), as the SDK does in its own auth flow. The resource is sent as the RFC 8707 resource indicator, so a mismatched value must not be used. Each lookup timeout now aborts the SDK's requests through its fetch hook instead of leaving them running. Co-Authored-By: Claude Opus 5.5 <[email protected]> * [Fix] Keep MCP OAuth when the published resource does not match the server URL A protected resource whose URL did not pass checkResourceAllowed made discovery return null, so the server looked like it had no OAuth. A trailing slash alone was enough: https://x/mcp/ for https://x/mcp. A trailing slash on the published resource is now ignored. Any other mismatch drops only the RFC 8707 resource indicator, and the server still uses OAuth. Co-Authored-By: Claude Opus 5.5 <[email protected]> * [Fix] Find the Bearer resource_metadata after other WWW-Authenticate challenges A 401 header such as `Basic realm="mcp", Bearer resource_metadata="..."` lists the Bearer challenge second. The parser only matched a header that starts with Bearer, so the fallback was skipped. It now also matches a Bearer challenge that follows a comma. Adds a test for a resource with multiple trailing slashes. Co-Authored-By: Claude Opus 5.5 <[email protected]> * [Fix] Read resource_metadata only from the Bearer challenge's own parameters The parser could skip past the Bearer challenge into a later challenge. For `Bearer realm="mcp", Basic resource_metadata="..."` it returned the Basic URL. After Bearer it now skips only auth-params, so a later challenge stops the match. Co-Authored-By: Claude Opus 5.5 <[email protected]> * [Fix] Parse WWW-Authenticate without a backtracking regular expression CodeQL flagged the resource_metadata regular expression: a crafted 401 header could make it backtrack exponentially. The parser now splits the header on commas outside quoted strings and matches each item against a single auth-param pattern, tracking the challenge it belongs to. Behavior is unchanged. Adds the CodeQL example header as a test case. Co-Authored-By: Claude Opus 5.5 <[email protected]> * [Fix] Handle escaped quotes and invalid URLs in WWW-Authenticate parsing A quoted auth-param can contain an escaped quote or a comma (RFC 9110 §5.6.4), which broke the split before a later resource_metadata. The header is now split by a loop that tracks quoted strings and escapes. An invalid resource_metadata URL no longer stops parsing, so a later Bearer challenge with a valid URL is still used. Co-Authored-By: Claude Opus 5.5 <[email protected]> * [Fix] Restrict header-supplied MCP OAuth metadata to the server origin The WWW-Authenticate fallback fetched any resource_metadata URL, so a server could direct the client to a loopback, private, or other host. It now fetches only metadata on the MCP server's own origin. Servers with cross-origin metadata keep the behavior they had before the fallback existed. A well-known lookup that timed out may still be running, so it no longer starts the fallback. Adds tests for a failed probe, a failed or timed-out fallback lookup, no fallback after a timed-out first lookup, and rejected destinations. Co-Authored-By: Claude Opus 5.5 <[email protected]> * [Fix] Do not follow redirects in the MCP OAuth WWW-Authenticate fallback The same-origin check covered only the resource_metadata URL. A 3xx response could still lead the initialize probe or the metadata fetch to a loopback, private, or other host. Both requests now use redirect: "manual", so a redirect fails the fallback. Well-known lookups are unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent c4ed96c commit 545e4d5

6 files changed

Lines changed: 447 additions & 22 deletions

File tree

‎src/services/mcp/McpOAuthClientProvider.ts‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -243,11 +243,12 @@ export class McpOAuthClientProvider implements OAuthClientProvider {
243243

244244
private async _doStartCallbackServer(): Promise<void> {
245245
this._closed = false
246-
const { port: configuredPort, host } = getCallbackAddress(this._configuredRedirectUri)
246+
const { port: configuredPort, host, path } = getCallbackAddress(this._configuredRedirectUri)
247247
const { server, port, result, cancel } = await startCallbackServer(
248248
configuredPort ?? this._port,
249249
this._state,
250250
host,
251+
path,
251252
)
252253
this._server = server
253254
this._port = port
@@ -670,17 +671,22 @@ function resolveResourceIndicator(configured: McpOAuthResource | undefined, disc
670671
return discovered ?? null
671672
}
672673

673-
function getCallbackAddress(redirectUri?: string): { port?: number; host: "localhost" | "127.0.0.1" } {
674-
if (!redirectUri) return { host: "127.0.0.1" }
674+
function getCallbackAddress(redirectUri?: string): {
675+
port?: number
676+
host: "localhost" | "127.0.0.1"
677+
path: string
678+
} {
679+
if (!redirectUri) return { host: "127.0.0.1", path: "/callback" }
675680
const url = new URL(redirectUri)
676681
if (url.hostname !== "localhost" && url.hostname !== "127.0.0.1") {
677682
throw new Error("MCP OAuth redirectUri must use a loopback host")
678683
}
679684
if (url.protocol !== "http:") {
680685
throw new Error("MCP OAuth redirectUri must use HTTP on a loopback host")
681686
}
682-
if (url.pathname !== "/callback") {
683-
throw new Error("MCP OAuth redirectUri path must be /callback")
687+
// Authorization servers with pre-registered clients may require a specific path.
688+
if (url.pathname === "/") {
689+
throw new Error("MCP OAuth redirectUri must specify a callback path")
684690
}
685691
if (url.username || url.password || url.search || url.hash) {
686692
throw new Error("MCP OAuth redirectUri must not contain credentials, a query, or a fragment")
@@ -689,5 +695,5 @@ function getCallbackAddress(redirectUri?: string): { port?: number; host: "local
689695
if (!Number.isInteger(port) || port < 1 || port > 65535) {
690696
throw new Error("MCP OAuth redirectUri must specify a valid port")
691697
}
692-
return { port, host: url.hostname }
698+
return { port, host: url.hostname, path: url.pathname }
693699
}

‎src/services/mcp/__tests__/McpOAuthClientProvider.spec.ts‎

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -231,16 +231,39 @@ describe("McpOAuthClientProvider", () => {
231231
await provider.openBrowser()
232232
const openedUri = vi.mocked(vscode.env.openExternal).mock.calls[0][0].toString()
233233
expect(new URL(openedUri).searchParams.get("scope")).toBe("openid profile offline_access")
234-
expect(startCallbackServer).toHaveBeenCalledWith(33418, expect.any(String), callbackHost)
234+
expect(startCallbackServer).toHaveBeenCalledWith(33418, expect.any(String), callbackHost, "/callback")
235235
await provider.close()
236236
},
237237
)
238238

239+
it("should listen on the configured callback path for a static client", async () => {
240+
setupCallbackServerMock()
241+
const redirectUri = "http://127.0.0.1:19876/mcp/oauth/callback"
242+
const provider = await McpOAuthClientProvider.create(
243+
"https://example.com/mcp",
244+
createMockSecretStorage(),
245+
undefined,
246+
{ clientId: "registered-client", redirectUri },
247+
)
248+
249+
expect(provider.redirectUrl).toBe(redirectUri)
250+
expect(await provider.clientInformation()).toMatchObject({ redirect_uris: [redirectUri] })
251+
252+
await provider.redirectToAuthorization(new URL("https://auth.example.com/authorize"))
253+
expect(startCallbackServer).toHaveBeenCalledWith(
254+
19876,
255+
expect.any(String),
256+
"127.0.0.1",
257+
"/mcp/oauth/callback",
258+
)
259+
await provider.close()
260+
})
261+
239262
it.each([
240263
["https://example.com:33418/callback", "must use a loopback host"],
241264
["http://example.com:33418/callback", "must use a loopback host"],
242265
["https://localhost:33418/callback", "must use HTTP on a loopback host"],
243-
["http://localhost:33418/wrong", "path must be /callback"],
266+
["http://localhost:33418/", "must specify a callback path"],
244267
["http://localhost:33418/callback?x=1", "must not contain credentials, a query, or a fragment"],
245268
["http://localhost:33418/callback#fragment", "must not contain credentials, a query, or a fragment"],
246269
["http://u:p@localhost:33418/callback", "must not contain credentials, a query, or a fragment"],
@@ -563,7 +586,7 @@ describe("McpOAuthClientProvider", () => {
563586
const secretStorage = createMockSecretStorage()
564587
const serverUrl = "https://example.com/mcp"
565588
const clientId = "registered-client"
566-
const discoveredResource = "https://discovered.example.com/"
589+
const discoveredResource = "https://example.com/mcp"
567590
await secretStorage.saveOAuthData(
568591
serverUrl,
569592
{
@@ -614,7 +637,7 @@ describe("McpOAuthClientProvider", () => {
614637
},
615638
clientId,
616639
)
617-
mockOAuthDiscovery("https://discovered.example.com/")
640+
mockOAuthDiscovery("https://example.com/mcp")
618641
const provider = await McpOAuthClientProvider.create(serverUrl, secretStorage, undefined, {
619642
clientId,
620643
resource: explicitResource,
@@ -1398,7 +1421,7 @@ describe("McpOAuthClientProvider", () => {
13981421
// reads redirect_uris, so the advertised URI carries the real port and never :0.
13991422
expect(startCallbackServer).toHaveBeenCalledTimes(1)
14001423
// Port 0 asks the OS for an ephemeral port; the mock binds it to 12345.
1401-
expect(startCallbackServer).toHaveBeenCalledWith(0, expect.any(String), "127.0.0.1")
1424+
expect(startCallbackServer).toHaveBeenCalledWith(0, expect.any(String), "127.0.0.1", "/callback")
14021425
expect(provider.redirectUrl).toBe("http://127.0.0.1:12345/callback")
14031426
expect(provider.redirectUrl).not.toContain(":0/")
14041427
expect(provider.clientMetadata.redirect_uris).toEqual(["http://127.0.0.1:12345/callback"])

‎src/services/mcp/utils/__tests__/callbackServer.spec.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,23 @@ describe("startCallbackServer", () => {
8484
await cancellation
8585
})
8686

87+
it("should resolve only on the configured callback path", async () => {
88+
const mockServer = createMockServer()
89+
90+
vi.mocked(http.createServer).mockReturnValue(mockServer as unknown as http.Server)
91+
92+
const { result } = await startCallbackServer(19876, undefined, "127.0.0.1", "/mcp/oauth/callback")
93+
const requestCall = mockServer.on.mock.calls.find((call) => call[0] === "request")
94+
const requestHandler = requestCall ? requestCall[1] : vi.fn()
95+
96+
const defaultPathRes = createMockResponse()
97+
requestHandler({ url: "/callback?code=wrong-path", method: "GET" }, defaultPathRes)
98+
expect(defaultPathRes.writeHead).toHaveBeenCalledWith(404)
99+
100+
requestHandler({ url: "/mcp/oauth/callback?code=test-code", method: "GET" }, createMockResponse())
101+
expect((await result).code).toBe("test-code")
102+
})
103+
87104
it("should reject invalid state", async () => {
88105
const mockServer = createMockServer()
89106

0 commit comments

Comments
 (0)