🛤️ fix: Base URL Fallback for Path-based OAuth Discovery in Token Refresh (#12164)

* fix: add base URL fallback for path-based OAuth discovery in token refresh

The two `refreshOAuthTokens` paths in `MCPOAuthHandler` were missing the
origin-URL fallback that `initiateOAuthFlow` already had. With MCP SDK
1.27.1, `buildDiscoveryUrls` appends the server path to the
`.well-known` URL (e.g. `/.well-known/oauth-authorization-server/mcp`),
which returns 404 for servers like Sentry that only expose the root
discovery endpoint (`/.well-known/oauth-authorization-server`).

Without the fallback, discovery returns null during refresh, the token
endpoint resolves to the wrong URL, and users are prompted to
re-authenticate every time their access token expires instead of the
refresh token being exchanged silently.

Both refresh paths now mirror the `initiateOAuthFlow` pattern: if
discovery fails and the server URL has a non-root path, retry with just
the origin URL.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor: extract discoverWithOriginFallback helper; add tests

Extract the duplicated path-based URL retry logic from both
`refreshOAuthTokens` branches into a single private static helper
`discoverWithOriginFallback`, reducing the risk of the two paths
drifting in the future.

Add three tests covering the new behaviour:
- stored clientInfo path: asserts discovery is called twice (path then
  origin) and that the token endpoint from the origin discovery is used
- auto-discovered path: same assertions for the branchless path
- root URL: asserts discovery is called only once when the server URL
  already has no path component

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor: use discoverWithOriginFallback in discoverMetadata too

Remove the inline duplicate of the origin-fallback logic from
`discoverMetadata` and replace it with a call to the shared
`discoverWithOriginFallback` helper, giving all three discovery
sites a single implementation.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* test: use mock.calls + .href/.toString() for URL assertions

Replace brittle `toHaveBeenNthCalledWith(new URL(...))` comparisons
with `expect.any(URL)` matchers and explicit `.href`/`.toString()`
checks on the captured call args, consistent with the existing
mock.calls pattern used throughout handler.test.ts.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Oreon Lothamer 2026-03-10 09:04:35 -10:00 committed by GitHub
parent ad5c51f62b
commit eb6328c1d9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 191 additions and 20 deletions

View file

@ -161,20 +161,7 @@ export class MCPOAuthHandler {
logger.debug(
`[MCPOAuth] Discovering OAuth metadata from ${sanitizeUrlForLogging(authServerUrl)}`,
);
let rawMetadata = await discoverAuthorizationServerMetadata(authServerUrl, {
fetchFn,
});
// If discovery failed and we're using a path-based URL, try the base URL
if (!rawMetadata && authServerUrl.pathname !== '/') {
const baseUrl = new URL(authServerUrl.origin);
logger.debug(
`[MCPOAuth] Discovery failed with path, trying base URL: ${sanitizeUrlForLogging(baseUrl)}`,
);
rawMetadata = await discoverAuthorizationServerMetadata(baseUrl, {
fetchFn,
});
}
const rawMetadata = await this.discoverWithOriginFallback(authServerUrl, fetchFn);
if (!rawMetadata) {
/**
@ -221,6 +208,27 @@ export class MCPOAuthHandler {
};
}
/**
* Discovers OAuth authorization server metadata with origin-URL fallback.
* If discovery fails for a path-based URL, retries with just the origin.
* Mirrors the fallback behavior in `discoverMetadata` and `initiateOAuthFlow`.
*/
private static async discoverWithOriginFallback(
serverUrl: URL,
fetchFn: FetchLike,
): ReturnType<typeof discoverAuthorizationServerMetadata> {
const metadata = await discoverAuthorizationServerMetadata(serverUrl, { fetchFn });
// If discovery failed and we're using a path-based URL, try the base URL
if (!metadata && serverUrl.pathname !== '/') {
const baseUrl = new URL(serverUrl.origin);
logger.debug(
`[MCPOAuth] Discovery failed with path, trying base URL: ${sanitizeUrlForLogging(baseUrl)}`,
);
return discoverAuthorizationServerMetadata(baseUrl, { fetchFn });
}
return metadata;
}
/**
* Registers an OAuth client dynamically
*/
@ -735,9 +743,10 @@ export class MCPOAuthHandler {
throw new Error('No token URL available for refresh');
} else {
/** Auto-discover OAuth configuration for refresh */
const oauthMetadata = await discoverAuthorizationServerMetadata(metadata.serverUrl, {
fetchFn: this.createOAuthFetch(oauthHeaders),
});
const serverUrl = new URL(metadata.serverUrl);
const fetchFn = this.createOAuthFetch(oauthHeaders);
const oauthMetadata = await this.discoverWithOriginFallback(serverUrl, fetchFn);
if (!oauthMetadata) {
/**
* No metadata discovered - use fallback /token endpoint.
@ -911,9 +920,9 @@ export class MCPOAuthHandler {
}
/** Auto-discover OAuth configuration for refresh */
const oauthMetadata = await discoverAuthorizationServerMetadata(metadata.serverUrl, {
fetchFn: this.createOAuthFetch(oauthHeaders),
});
const serverUrl = new URL(metadata.serverUrl);
const fetchFn = this.createOAuthFetch(oauthHeaders);
const oauthMetadata = await this.discoverWithOriginFallback(serverUrl, fetchFn);
let tokenUrl: URL;
if (!oauthMetadata?.token_endpoint) {