Skip to content

Commit 6756e2f

Browse files
sdbrother0claude
andcommitted
[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]>
1 parent a88e728 commit 6756e2f

2 files changed

Lines changed: 35 additions & 12 deletions

File tree

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

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@ describe("fetchOAuthAuthServerMetadata", () => {
7979
expect(probeUrl).toBe("https://example.com/core/mcp")
8080
expect(probeInit).toMatchObject({
8181
method: "POST",
82+
redirect: "manual",
8283
headers: { "Content-Type": "application/json", Accept: "application/json, text/event-stream" },
8384
})
8485
expect(JSON.parse(probeInit.body as string)).toMatchObject({ jsonrpc: "2.0", method: "initialize" })
@@ -163,30 +164,44 @@ describe("fetchOAuthAuthServerMetadata", () => {
163164
expect(mockFetch).toHaveBeenCalledTimes(1)
164165
})
165166

166-
/** Makes the next SDK lookup fetch through its hook and never settle; returns the request signal. */
167+
it("returns null when the probe is redirected", async () => {
168+
vi.mocked(discoverOAuthProtectedResourceMetadata).mockRejectedValueOnce(new Error("not found"))
169+
mockFetch.mockResolvedValueOnce(
170+
new Response(null, { status: 307, headers: { Location: "http://127.0.0.1:8080/mcp" } }),
171+
)
172+
173+
const result = await fetchOAuthAuthServerMetadata("https://example.com/mcp")
174+
175+
expect(result).toBeNull()
176+
expect(mockFetch).toHaveBeenCalledTimes(1)
177+
expect(discoverOAuthProtectedResourceMetadata).toHaveBeenCalledTimes(1)
178+
})
179+
180+
/** Makes the next SDK lookup fetch through its hook and never settle; returns the request init. */
167181
const hangNextLookup = () => {
168-
const signal: { current?: AbortSignal } = {}
182+
const request: { init?: RequestInit } = {}
169183
vi.mocked(discoverOAuthProtectedResourceMetadata).mockImplementationOnce(async (url, _opts, fetchFn) => {
170184
await fetchFn!(url)
171185
throw new Error("unreachable")
172186
})
173187
mockFetch.mockImplementationOnce((_url: string, init: RequestInit) => {
174-
signal.current = init.signal ?? undefined
188+
request.init = init
175189
return new Promise(() => {})
176190
})
177-
return signal
191+
return request
178192
}
179193

180194
it("aborts a timed-out well-known lookup and does not start the fallback", async () => {
181195
vi.useFakeTimers()
182196
try {
183-
const lookupSignal = hangNextLookup()
197+
const lookup = hangNextLookup()
184198

185199
const result = fetchOAuthAuthServerMetadata("https://example.com/mcp")
186200
await vi.advanceTimersByTimeAsync(5_000)
187201

188202
await expect(result).resolves.toBeNull()
189-
expect(lookupSignal.current?.aborted).toBe(true)
203+
expect(lookup.init?.signal?.aborted).toBe(true)
204+
expect(lookup.init?.redirect).toBeUndefined()
190205
expect(mockFetch).toHaveBeenCalledTimes(1)
191206
expect(discoverOAuthProtectedResourceMetadata).toHaveBeenCalledTimes(1)
192207
} finally {
@@ -199,13 +214,14 @@ describe("fetchOAuthAuthServerMetadata", () => {
199214
try {
200215
vi.mocked(discoverOAuthProtectedResourceMetadata).mockRejectedValueOnce(new Error("not found"))
201216
mockFetch.mockResolvedValueOnce(unauthorized('Bearer resource_metadata="https://example.com/metadata"'))
202-
const lookupSignal = hangNextLookup()
217+
const lookup = hangNextLookup()
203218

204219
const result = fetchOAuthAuthServerMetadata("https://example.com/mcp")
205220
await vi.advanceTimersByTimeAsync(5_000)
206221

207222
await expect(result).resolves.toBeNull()
208-
expect(lookupSignal.current?.aborted).toBe(true)
223+
expect(lookup.init?.signal?.aborted).toBe(true)
224+
expect(lookup.init?.redirect).toBe("manual")
209225
expect(discoverOAuthProtectedResourceMetadata).toHaveBeenCalledTimes(2)
210226
} finally {
211227
vi.useRealTimers()

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

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -98,8 +98,10 @@ async function discoverProtectedResourceMetadata(serverUrl: string): Promise<OAu
9898
// Fetch only metadata on the server's own origin, so a 401 header cannot
9999
// direct the client to another host, such as a loopback or private address.
100100
if (resourceMetadataUrl?.origin !== new URL(serverUrl).origin) throw wellKnownError
101-
return withDiscoveryTimeout((fetchFn) =>
102-
discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl }, fetchFn),
101+
// A redirect could still lead off-origin, so the metadata fetch does not follow one.
102+
return withDiscoveryTimeout(
103+
(fetchFn) => discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl }, fetchFn),
104+
{ redirect: "manual" },
103105
)
104106
}
105107
}
@@ -134,12 +136,15 @@ class DiscoveryTimeoutError extends Error {
134136
* the fallback's budget. The timeout aborts the lookup's requests through the
135137
* SDK fetch hook.
136138
*/
137-
async function withDiscoveryTimeout<T>(lookup: (fetchFn: typeof fetch) => Promise<T>): Promise<T> {
139+
async function withDiscoveryTimeout<T>(
140+
lookup: (fetchFn: typeof fetch) => Promise<T>,
141+
requestInit?: RequestInit,
142+
): Promise<T> {
138143
const controller = new AbortController()
139144
let timer: ReturnType<typeof setTimeout> | undefined
140145
try {
141146
return await Promise.race([
142-
lookup((input, init) => fetch(input, { ...init, signal: controller.signal })),
147+
lookup((input, init) => fetch(input, { ...init, ...requestInit, signal: controller.signal })),
143148
new Promise<never>((_, reject) => {
144149
timer = setTimeout(() => {
145150
controller.abort()
@@ -173,6 +178,8 @@ async function probeResourceMetadataUrl(serverUrl: string): Promise<URL | undefi
173178
clientInfo: { name: "oauth-discovery", version: "1.0.0" },
174179
},
175180
}),
181+
// The 401 must come from the configured server itself, not a redirect target.
182+
redirect: "manual",
176183
signal: AbortSignal.timeout(DISCOVERY_TIMEOUT_MS),
177184
})
178185
await response.body?.cancel().catch(() => {})

0 commit comments

Comments
 (0)