Skip to content

Commit 8341345

Browse files
sdbrother0claude
andcommitted
[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]>
1 parent b0b86af commit 8341345

3 files changed

Lines changed: 89 additions & 15 deletions

File tree

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -586,7 +586,7 @@ describe("McpOAuthClientProvider", () => {
586586
const secretStorage = createMockSecretStorage()
587587
const serverUrl = "https://example.com/mcp"
588588
const clientId = "registered-client"
589-
const discoveredResource = "https://discovered.example.com/"
589+
const discoveredResource = "https://example.com/mcp"
590590
await secretStorage.saveOAuthData(
591591
serverUrl,
592592
{
@@ -637,7 +637,7 @@ describe("McpOAuthClientProvider", () => {
637637
},
638638
clientId,
639639
)
640-
mockOAuthDiscovery("https://discovered.example.com/")
640+
mockOAuthDiscovery("https://example.com/mcp")
641641
const provider = await McpOAuthClientProvider.create(serverUrl, secretStorage, undefined, {
642642
clientId,
643643
resource: explicitResource,

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

Lines changed: 47 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -75,9 +75,11 @@ describe("fetchOAuthAuthServerMetadata", () => {
7575
headers: { "Content-Type": "application/json", Accept: "application/json, text/event-stream" },
7676
})
7777
expect(JSON.parse(probeInit.body as string)).toMatchObject({ jsonrpc: "2.0", method: "initialize" })
78-
expect(discoverOAuthProtectedResourceMetadata).toHaveBeenLastCalledWith("https://example.com/core/mcp", {
79-
resourceMetadataUrl: new URL("https://example.com/core/.well-known/oauth-protected-resource/mcp"),
80-
})
78+
expect(discoverOAuthProtectedResourceMetadata).toHaveBeenLastCalledWith(
79+
"https://example.com/core/mcp",
80+
{ resourceMetadataUrl: new URL("https://example.com/core/.well-known/oauth-protected-resource/mcp") },
81+
expect.any(Function),
82+
)
8183
expect(result).toEqual({ authServerMeta: meta, resourceIndicator: "https://example.com/core/mcp" })
8284
})
8385

@@ -124,21 +126,60 @@ describe("fetchOAuthAuthServerMetadata", () => {
124126
}
125127
})
126128

127-
it("returns null when a protected resource metadata lookup exceeds its timeout", async () => {
129+
it("aborts a protected resource metadata lookup that exceeds its timeout", async () => {
128130
vi.useFakeTimers()
129131
try {
130-
vi.mocked(discoverOAuthProtectedResourceMetadata).mockImplementationOnce(() => new Promise(() => {}))
131-
mockFetch.mockResolvedValueOnce(new Response(null, { status: 200 }))
132+
vi.mocked(discoverOAuthProtectedResourceMetadata).mockImplementationOnce(async (url, _opts, fetchFn) => {
133+
await fetchFn!(url)
134+
throw new Error("unreachable")
135+
})
136+
let lookupSignal: AbortSignal | undefined
137+
mockFetch
138+
.mockImplementationOnce((_url: string, init: RequestInit) => {
139+
lookupSignal = init.signal ?? undefined
140+
return new Promise(() => {})
141+
})
142+
.mockResolvedValueOnce(new Response(null, { status: 200 }))
132143

133144
const result = fetchOAuthAuthServerMetadata("https://example.com/mcp")
134145
await vi.advanceTimersByTimeAsync(5_000)
135146

136147
await expect(result).resolves.toBeNull()
148+
expect(lookupSignal?.aborted).toBe(true)
137149
} finally {
138150
vi.useRealTimers()
139151
}
140152
})
141153

154+
it("rejects well-known metadata whose resource does not match the server URL", async () => {
155+
vi.mocked(discoverOAuthProtectedResourceMetadata).mockResolvedValueOnce({
156+
resource: "https://other.example.com/mcp",
157+
authorization_servers: ["https://auth.example.com"],
158+
})
159+
mockFetch.mockResolvedValueOnce(new Response(null, { status: 200 }))
160+
161+
const result = await fetchOAuthAuthServerMetadata("https://example.com/mcp")
162+
163+
expect(result).toBeNull()
164+
expect(mockFetch).toHaveBeenCalledTimes(1)
165+
})
166+
167+
it("rejects fallback metadata whose resource does not match the server URL", async () => {
168+
vi.mocked(discoverOAuthProtectedResourceMetadata)
169+
.mockRejectedValueOnce(new Error("not found"))
170+
.mockResolvedValueOnce({
171+
resource: "https://example.com/other",
172+
authorization_servers: ["https://auth.example.com"],
173+
})
174+
mockFetch.mockResolvedValueOnce(unauthorized('Bearer resource_metadata="https://example.com/metadata"'))
175+
176+
const result = await fetchOAuthAuthServerMetadata("https://example.com/mcp")
177+
178+
expect(result).toBeNull()
179+
expect(discoverOAuthProtectedResourceMetadata).toHaveBeenCalledTimes(2)
180+
expect(mockFetch).toHaveBeenCalledTimes(1)
181+
})
182+
142183
it("constructs the RFC 8414 discovery URL correctly for an issuer with a path", async () => {
143184
;(discoverOAuthProtectedResourceMetadata as any).mockResolvedValue({
144185
resource: "https://mcp.kapa.ai/",

‎src/services/mcp/utils/oauth.ts‎

Lines changed: 40 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { discoverOAuthProtectedResourceMetadata } from "@modelcontextprotocol/sdk/client/auth.js"
2+
import { checkResourceAllowed } from "@modelcontextprotocol/sdk/shared/auth-utils.js"
23
import type { OAuthProtectedResourceMetadata } from "@modelcontextprotocol/sdk/shared/auth.js"
34

45
/**
@@ -85,25 +86,57 @@ export async function fetchOAuthAuthServerMetadata(serverUrl: string): Promise<O
8586

8687
async function discoverProtectedResourceMetadata(serverUrl: string): Promise<OAuthProtectedResourceMetadata> {
8788
try {
88-
return await withDiscoveryTimeout(discoverOAuthProtectedResourceMetadata(serverUrl))
89+
return assertResourceMatches(
90+
serverUrl,
91+
await withDiscoveryTimeout((fetchFn) =>
92+
discoverOAuthProtectedResourceMetadata(serverUrl, undefined, fetchFn),
93+
),
94+
)
8995
} catch (wellKnownError) {
9096
const resourceMetadataUrl = await probeResourceMetadataUrl(serverUrl)
9197
if (!resourceMetadataUrl) throw wellKnownError
92-
return withDiscoveryTimeout(discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl }))
98+
return assertResourceMatches(
99+
serverUrl,
100+
await withDiscoveryTimeout((fetchFn) =>
101+
discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl }, fetchFn),
102+
),
103+
)
93104
}
94105
}
95106

96107
/**
97-
* The SDK does not accept an AbortSignal, so each lookup races its own timeout.
98-
* A slow well-known lookup therefore cannot consume the fallback's budget.
108+
* RFC 9728 §3.3: the metadata must describe the resource it was fetched for.
109+
* Its `resource` is later sent as the RFC 8707 resource indicator.
99110
*/
100-
async function withDiscoveryTimeout<T>(promise: Promise<T>): Promise<T> {
111+
function assertResourceMatches(
112+
serverUrl: string,
113+
metadata: OAuthProtectedResourceMetadata,
114+
): OAuthProtectedResourceMetadata {
115+
if (
116+
metadata.resource &&
117+
!checkResourceAllowed({ requestedResource: serverUrl, configuredResource: metadata.resource })
118+
) {
119+
throw new Error(`Protected resource metadata for ${metadata.resource} does not match ${serverUrl}`)
120+
}
121+
return metadata
122+
}
123+
124+
/**
125+
* Gives each lookup its own timeout, so a slow well-known lookup cannot consume
126+
* the fallback's budget. The timeout aborts the lookup's requests through the
127+
* SDK fetch hook.
128+
*/
129+
async function withDiscoveryTimeout<T>(lookup: (fetchFn: typeof fetch) => Promise<T>): Promise<T> {
130+
const controller = new AbortController()
101131
let timer: ReturnType<typeof setTimeout> | undefined
102132
try {
103133
return await Promise.race([
104-
promise,
134+
lookup((input, init) => fetch(input, { ...init, signal: controller.signal })),
105135
new Promise<never>((_, reject) => {
106-
timer = setTimeout(() => reject(new Error("OAuth discovery timeout")), DISCOVERY_TIMEOUT_MS)
136+
timer = setTimeout(() => {
137+
controller.abort()
138+
reject(new Error("OAuth discovery timeout"))
139+
}, DISCOVERY_TIMEOUT_MS)
107140
}),
108141
])
109142
} finally {

0 commit comments

Comments
 (0)