Skip to content

Commit a88e728

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

2 files changed

Lines changed: 74 additions & 15 deletions

File tree

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

Lines changed: 62 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,8 @@ describe("fetchOAuthAuthServerMetadata", () => {
100100
],
101101
["a header that backtracks a naive parser", ",bearer\t!=" + "\t,!=".repeat(10_000)],
102102
["an invalid URL", 'Bearer resource_metadata="not a url"'],
103+
["a URL on another origin", 'Bearer resource_metadata="https://other.example.com/metadata"'],
104+
["a loopback URL", 'Bearer resource_metadata="http://127.0.0.1:8080/admin"'],
103105
])("returns null when the 401 response has %s", async (_case, wwwAuthenticate) => {
104106
vi.mocked(discoverOAuthProtectedResourceMetadata).mockRejectedValueOnce(new Error("not found"))
105107
mockFetch.mockResolvedValueOnce(unauthorized(wwwAuthenticate))
@@ -138,26 +140,73 @@ describe("fetchOAuthAuthServerMetadata", () => {
138140
}
139141
})
140142

141-
it("aborts a protected resource metadata lookup that exceeds its timeout", async () => {
143+
it("returns null when the probe request fails", async () => {
144+
vi.mocked(discoverOAuthProtectedResourceMetadata).mockRejectedValueOnce(new Error("not found"))
145+
mockFetch.mockRejectedValueOnce(new Error("connection refused"))
146+
147+
const result = await fetchOAuthAuthServerMetadata("https://example.com/mcp")
148+
149+
expect(result).toBeNull()
150+
expect(discoverOAuthProtectedResourceMetadata).toHaveBeenCalledTimes(1)
151+
})
152+
153+
it("returns null when the fallback lookup fails", async () => {
154+
vi.mocked(discoverOAuthProtectedResourceMetadata)
155+
.mockRejectedValueOnce(new Error("not found"))
156+
.mockRejectedValueOnce(new Error("invalid metadata"))
157+
mockFetch.mockResolvedValueOnce(unauthorized('Bearer resource_metadata="https://example.com/metadata"'))
158+
159+
const result = await fetchOAuthAuthServerMetadata("https://example.com/mcp")
160+
161+
expect(result).toBeNull()
162+
expect(discoverOAuthProtectedResourceMetadata).toHaveBeenCalledTimes(2)
163+
expect(mockFetch).toHaveBeenCalledTimes(1)
164+
})
165+
166+
/** Makes the next SDK lookup fetch through its hook and never settle; returns the request signal. */
167+
const hangNextLookup = () => {
168+
const signal: { current?: AbortSignal } = {}
169+
vi.mocked(discoverOAuthProtectedResourceMetadata).mockImplementationOnce(async (url, _opts, fetchFn) => {
170+
await fetchFn!(url)
171+
throw new Error("unreachable")
172+
})
173+
mockFetch.mockImplementationOnce((_url: string, init: RequestInit) => {
174+
signal.current = init.signal ?? undefined
175+
return new Promise(() => {})
176+
})
177+
return signal
178+
}
179+
180+
it("aborts a timed-out well-known lookup and does not start the fallback", async () => {
142181
vi.useFakeTimers()
143182
try {
144-
vi.mocked(discoverOAuthProtectedResourceMetadata).mockImplementationOnce(async (url, _opts, fetchFn) => {
145-
await fetchFn!(url)
146-
throw new Error("unreachable")
147-
})
148-
let lookupSignal: AbortSignal | undefined
149-
mockFetch
150-
.mockImplementationOnce((_url: string, init: RequestInit) => {
151-
lookupSignal = init.signal ?? undefined
152-
return new Promise(() => {})
153-
})
154-
.mockResolvedValueOnce(new Response(null, { status: 200 }))
183+
const lookupSignal = hangNextLookup()
184+
185+
const result = fetchOAuthAuthServerMetadata("https://example.com/mcp")
186+
await vi.advanceTimersByTimeAsync(5_000)
187+
188+
await expect(result).resolves.toBeNull()
189+
expect(lookupSignal.current?.aborted).toBe(true)
190+
expect(mockFetch).toHaveBeenCalledTimes(1)
191+
expect(discoverOAuthProtectedResourceMetadata).toHaveBeenCalledTimes(1)
192+
} finally {
193+
vi.useRealTimers()
194+
}
195+
})
196+
197+
it("aborts a timed-out fallback lookup", async () => {
198+
vi.useFakeTimers()
199+
try {
200+
vi.mocked(discoverOAuthProtectedResourceMetadata).mockRejectedValueOnce(new Error("not found"))
201+
mockFetch.mockResolvedValueOnce(unauthorized('Bearer resource_metadata="https://example.com/metadata"'))
202+
const lookupSignal = hangNextLookup()
155203

156204
const result = fetchOAuthAuthServerMetadata("https://example.com/mcp")
157205
await vi.advanceTimersByTimeAsync(5_000)
158206

159207
await expect(result).resolves.toBeNull()
160-
expect(lookupSignal?.aborted).toBe(true)
208+
expect(lookupSignal.current?.aborted).toBe(true)
209+
expect(discoverOAuthProtectedResourceMetadata).toHaveBeenCalledTimes(2)
161210
} finally {
162211
vi.useRealTimers()
163212
}

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

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,8 +92,12 @@ async function discoverProtectedResourceMetadata(serverUrl: string): Promise<OAu
9292
discoverOAuthProtectedResourceMetadata(serverUrl, undefined, fetchFn),
9393
)
9494
} catch (wellKnownError) {
95+
// A lookup that timed out may still be running, so do not start another.
96+
if (wellKnownError instanceof DiscoveryTimeoutError) throw wellKnownError
9597
const resourceMetadataUrl = await probeResourceMetadataUrl(serverUrl)
96-
if (!resourceMetadataUrl) throw wellKnownError
98+
// Fetch only metadata on the server's own origin, so a 401 header cannot
99+
// direct the client to another host, such as a loopback or private address.
100+
if (resourceMetadataUrl?.origin !== new URL(serverUrl).origin) throw wellKnownError
97101
return withDiscoveryTimeout((fetchFn) =>
98102
discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl }, fetchFn),
99103
)
@@ -119,6 +123,12 @@ function resourceMatches(serverUrl: string, resource: string): boolean {
119123
return false
120124
}
121125

126+
class DiscoveryTimeoutError extends Error {
127+
constructor() {
128+
super("OAuth discovery timeout")
129+
}
130+
}
131+
122132
/**
123133
* Gives each lookup its own timeout, so a slow well-known lookup cannot consume
124134
* the fallback's budget. The timeout aborts the lookup's requests through the
@@ -133,7 +143,7 @@ async function withDiscoveryTimeout<T>(lookup: (fetchFn: typeof fetch) => Promis
133143
new Promise<never>((_, reject) => {
134144
timer = setTimeout(() => {
135145
controller.abort()
136-
reject(new Error("OAuth discovery timeout"))
146+
reject(new DiscoveryTimeoutError())
137147
}, DISCOVERY_TIMEOUT_MS)
138148
}),
139149
])

0 commit comments

Comments
 (0)