Repository navigation
Validate the authorization server metadata issuer on every discovery path - #3398
Conversation
📚 Documentation preview
|
There was a problem hiding this comment.
Beyond the inline findings, I also examined the sibling failure path at src/mcp/client/auth/oauth2.py:711 — when all protected-resource-metadata fetches fail, credentials bound to a different issuer are discarded before any metadata is fetched. That is the deliberate SEP-2352 fail-closed behavior (the flow re-registers on the next pass), so it is not the same transient-wipe problem as the ASM-metadata case flagged inline.
Extended reasoning...
Two confirmed findings are posted inline (the ASM-rediscovery metadata wipe at oauth2.py:737 and the identity-assertion step-up scope union), so approval is ruled out. Of the three ruled-out candidates, two duplicate the confirmed findings; the third (oauth2.py:711, PRM-failure credential discard) is genuinely distinct and adjacent to the line-737 finding, so recording that it was checked and judged intentional adds information a reader would otherwise have to re-derive. I verified against the diff that _discard_credentials_bound_elsewhere runs before metadata fetch by design, with an in-code comment stating credentials bound to another server are dropped "whatever the rest of discovery does" per SEP-2352, and that a configured-issuer mismatch raises OAuthFlowError before any discard.
Additional findings (outside the current diff — GitHub can't attach inline comments there):
-
🟣
src/mcp/client/auth/extensions/identity_assertion.py— pre-existing: the step-up union drops previously escalated grants because it never folds in the granted token's scope. On a 403 insufficient_scope,scope_to_request = union_scopes(self._scope, challenged)uses only the constructor scope, andself._scopeis never updated after an exchange, so a client whose ops need disjoint step-up scopes thrashes: each step-up mints a token missing the other op's earlier escalation, re-triggering a 403/exchange on every alternate call (worse after restart, where the stored token's scope is the only record). oauth2.py fixes exactly this by foldingcurrent_tokens.scopeinto the SEP-2350 union (lines 673, 752-753); mirror it here by unioningself._tokens.scope(recorded at lines 210-212) intoscope_to_request.Extended reasoning...
Path: IdentityAssertionOAuthProvider.async_auth_flow. First step-up: op A 403s with scope="extra1"; line 179 requests union(constructor "read", "extra1") -> token granted read extra1; lines 210-215 record scope on the token and persist it, but self._scope stays "read". Second step-up: op B 403s with scope="extra2"; line 179 again unions from self._scope only -> requests "read extra2", and the newly minted token no longer carries extra1. Op A now 403s again, re-minting a token without extra2, and so on: every alternate call is a full jwt-bearer exchange (assertion_provider call + token POST). After a process restart the same line makes the stored token's escalations unrecoverable in one step. This PR added the equivalent safeguard to OAuthClientProvider (src/mcp/client/auth/oauth2.py lines 671-673 read granted_scope from current_tokens before discovery and lines 748-753 fold it into the step-up union, per the SEP-2350 comment) but did not apply it to identity_assertion.py, which the diff otherwise touches (lines 196-205). Fix: include self._tokens.scope (when self._tokens
Verification: pre-existing — src/mcp/client/auth/extensions/identity_assertion.py:179
scope_to_request = union_scopes(self._scope, extract_scope_from_www_auth(response))unions only the constructor scope (self._scope, set once at line 126 and never updated) with the challenged scope; the granted token's scope (self._tokens.scope, recorded at lines 210-212 and persisted at line 215) is never folded in. So
The OAuth client now decides which issuer it expects before it fetches any authorization server metadata, and checks what follows against that one value: the metadata's
issuer(RFC 8414 section 3.3) on the legacy no-PRM path as well as the PRM path, the SEP-2352 binding of stored credentials, and the issuer recorded on a new registration. A 403 scope step-up goes through the same discovery when it holds no metadata yet, and the two machine-to-machine providers gain an optionalissuer=so pre-provisioned credentials can be tied to their authorization server.Motivation and Context
issuerwas not checked, and the credential binding was re-evaluated afterwards against whatever issuer the document named. RFC 8414 section 3.3 says such metadata must not be used, and the TypeScript client applies the check on every path. Discovery now computes the expected issuer once (the PRM-advertised server, else the resource server's origin written the way metadata issuers are), validates metadata against it unconditionally (a root issuer served with its trailing slash still names the origin), and evaluates the binding against it before the metadata is fetched, which also covers the case where no metadata is served at all and the default endpoints are used. The post-fetch special case goes away. When none of the resource metadata locations answers and one of them failed with a server error (or 429), the flow now stops instead of reading that as "no resource metadata", so a transient failure cannot send a client with a bound registration down the legacy path.403 insufficient_scopere-authorized with whatever metadata was in memory, and with none after a restart, in which case it used the default/authorizeand/tokenon the resource server's origin even for servers that publish metadata, and never consulted the binding. It now takes the 401 path: discover first when nothing is held (reading aresource_metadatahint from the challenge too), then re-authorize with the SEP-2350 union; metadata already discovered in the process is reused as before. A 403 that is not a scope challenge is returned to the caller instead of being retried unchanged, asIdentityAssertionOAuthProvideralready does.issuer=onClientCredentialsOAuthProviderandPrivateKeyJWTOAuthProvider. These providers carry a fixedclient_id(and a secret, or a signed assertion) and used whichever authorization server discovery produced; nothing else in the flow can say which server issued those credentials. The optional keyword names it: when the resource advertises several servers the matching one is used, and the token request is only built from metadata for that issuer; otherwise the flow stops withOAuthFlowErrorand drops the metadata and token it was holding, so the next request starts discovery afresh rather than refreshing against them. Same model asIdentityAssertionOAuthProvider; omitting it keeps today's behaviour.How Has This Been Tested?
New and updated tests in
tests/client/test_auth.pyandtests/client/auth/extensions/test_client_credentials.py: legacy metadata naming another issuer is refused; aserver_urlwith an upper-case host or explicit port, and a root issuer served with a trailing slash, still match the origin; a registration bound elsewhere is dropped before the metadata request and also when no metadata is served, from a 401 or a 403 challenge; a 5xx/429 on the resource metadata request stops the flow with stored credentials intact; the root-slash tolerance and its limit; a step-up after a restart discovers first and targets the advertised server; a non-challenge 403 ends the flow;issuer=on both providers (matching metadata with either root spelling, other issuer, no metadata, the configured server listed second, a non-URL value, and that a refusal leaves nothing behind to refresh with). Each new flow test fails againstmain'ssrc/. I also drove the provider throughhttpx2.AsyncClient(auth=...)andstreamable_http_clientagainst local test servers (PRM and legacy paths, with and without metadata, 401-first and 403-first, client-credentials with and withoutissuer=). Full suite, coverage,strict-no-cover, pyright and ruff pass locally.Breaking Changes
No API removals or signature changes; the new keyword is optional and last, and
mcp.client.auth.utilsgainsissuers_match. These are fixes that bring the client in line with specified behaviour; the observable differences:issuerother than its own origin now getsOAuthFlowError: Authorization server metadata issuer mismatch. As on the PRM path since 2.0 there is no client-side override (the TypeScript client has one; adding it here would be a separate decision).OAuthFlowErrorinstead of moving on to the legacy path.credentials_match_issuertreatshttps://hostandhttps://host/as the same issuer, so a record stamped in either form keeps matching on both paths.insufficient_scopeis no longer retried.Types of changes
Checklist
help wanted, or I'm a maintainer)Additional context
Two commits: the discovery change (expected issuer, binding before the fetch, step-up), then the
issuer=keyword. The discovery block inasync_auth_flowis re-indented under one new condition, so the whitespace-insensitive view is the easier read there. Two things are unchanged frommainand left for a separate change: how discovery state is carried between passes (metadata held from an earlier pass while a later one selects a different server), and the fallback to the 2025-03-26 default endpoints when an advertised authorization server's metadata cannot be fetched.AI Disclaimer