Repository navigation
[P8] oauth: issuer checks, application_type, AS migration (SEP-2468/837/2352) - #363
Merged
Merged
Conversation
Brings the OAuth client in line with the 2026-07-28 authorization requirements. Authorization server metadata is used only when its `issuer` matches the issuer the well-known URL was built from, the `iss` of the authorization response is checked (RFC 9207), dynamic registration sends `application_type`, and a rejected token triggers a fresh read of the protected resource metadata so the client follows a resource to a new authorization server. A 2025-03-26 server without any metadata gets the default `/authorize`, `/token` and `/register` endpoints at its origin. A rejected token is refreshed at its issuing server before the metadata is read again; a transient discovery failure keeps the cached state instead of falling back to default endpoints; concurrent challenges run one flow. With it, the 2026-07-28 baseline is empty and the tier score is 100% for client and server at 2025-11-25 and 2026-07-28.
- Pass the Authorization value of the challenged request to the authorizer (new HTTPClientAuthorizer requirement with a default that calls the existing method; POST and GET paths), so a late 401 for a token another request already replaced retries with the new token instead of clearing it and starting a new authorization. - Refresh a refreshed token again after re-reading the resource metadata when the resource still names the same server; previously a token obtained by refresh was never refreshed and its refresh token was deleted on the next 401. The refresh-first step still skips a refreshed token, so the metadata is read again first. - Fail the challenge and keep the stored tokens when the authorization server metadata is unavailable (network error, unexpected status) or the read is cancelled, instead of clearing them. - Fail challenges that waited for a challenge that ended with an error and left no usable token with that error, instead of starting the same flow again (one prompt for a cancelled authorization); a 403 that waited for a token with the required scopes retries with it. - Reset the dynamic client registration attempt when registration throws, so the next flow registers again. - Make waiters of the authorizer gate cancellable, and document that an access token provider or authorization delegate must not send requests through the transport it authorizes.
PKCE.makeChallenge(from:) hashed with CryptoKit and threw pkceS256Unavailable where CryptoKit is missing, so on Linux every authorization_code flow failed before it started. Three tests fail on Linux because of it: "The authorizer passes the metadata issuer and its iss support to the flow" with pkceS256Unavailable, and two OAuthAuthorizerStateTests that wait for the flow to start and hit their one-minute limit. The MCP target already depends on swift-crypto, whose SHA256 has the same API on every platform, so makeChallenge uses it. It keeps `throws` for source compatibility and no longer throws; the doc comments of makeChallenge and pkceS256Unavailable say so. The authorization_code challenge test in OAuthAuthorizerTests, gated on CryptoKit, now runs on Linux too.
- Fail a challenge that waited for one that ended with an error when the only stored token is the one the challenged request carried, not only when no unexpired token is stored. A failed 403 insufficient_scope step-up keeps the narrower token, so a waiting 403 for the same token presented a second authorization prompt after the user cancelled the first; a 401 whose handler threw before clearing the token repeated the failing calls. - Keep the selected authorization server, its metadata and the stored token when re-read resource metadata lists another server but endpointOverrides.authorizationServerURL configures the server. The override decides the server whatever the resource lists, so the SEP-2352 migration check does not apply; it cleared the token before a 403 step-up read the granted scopes, and before a 401 could refresh it. - Reject an authorization response whose iss is given more than once or without a value (RFC 9207 §2.4; RFC 6749 §3.1 sends a parameter at most once). The first iss alone was checked, and a valueless iss counted as absent. - Compare a root issuer with and without its trailing slash by checking that the shorter one is a bare origin, instead of rebuilding the origin from percentEncodedHost, whose spelling of an IPv6 host depends on the Foundation version (RFC 8414 §3.3). - Give operationKey a nil default on the sentAuthorization overload of OAuthAuthorizer.handleChallenge, as on the other overload (additive). - Wait for the authorizer gate to hold the expected waiters in the OAuthAuthorizerStateTests waiter tests instead of fixed sleeps.
This was referenced Nov 25, 2026
Merged
canarik
approved these changes
Nov 25, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
rel/1.0.0in order (previous: P7 (#364) · next: P10 (#362))conformance/p8-oauthconformance/p7-mrtr(stacked: GitHub retargets this PR torel/1.0.0when the previous part merges)4f1f67doauth: issuer checks, application_type, AS migration (SEP-2468/837/2352)82ab1d5oauth: review fixesc6762d9oauth: compute the PKCE S256 challenge with swift-crypto78cb7d3oauth: third-pass review fixesSummary
Brings the OAuth client in line with the 2026-07-28 authorization requirements. Authorization server metadata is used only when its
issuermatches the issuer the well-known URL was built from, theissof the authorization response is checked (RFC 9207), dynamic registration sendsapplication_type, and a rejected token triggers a fresh read of the protected resource metadata so the client follows a resource to a new authorization server. A 2025-03-26 server without any metadata gets the default/authorize,/tokenand/registerendpoints at its origin. A rejected token is refreshed at its issuing server before the metadata is read again; a transient discovery failure keeps the cached state instead of falling back to default endpoints; concurrent challenges run one flow. After this PR the 2026-07-28 baseline is empty and the tier score is 100% for client and server at 2025-11-25 and 2026-07-28.Motivation
issuerdiffers from the issuer it asked for, and must compare theissauthorization response parameter (RFC 9207) without normalization.OAuthDiscoveryClientaccepted the first valid metadata from any issuer and used itsissueras the server identity, and compared case-insensitively.application_type. Every 2026-07-28 auth scenario that registers failedsep-837-application-type-present.auth/2025-03-26-oauth-endpoint-fallbackfailed in the default leg (Python passes). The client gave up when no metadata existed.Changes
Issuer checks (
Sources/MCP/Base/Authorization/OAuthDiscoveryClient.swift,OAuthModels.swift)fetchAuthorizationServerMetadata(candidates:session:)returns metadata only whenOAuthIssuer.matches(issuer, candidate). Metadata with another issuer, or none, is skipped; if only such metadata was found, it throwsauthorizationServerIssuerMismatch(expected:actual:), otherwiseauthorizationServerMetadataDiscoveryFailed. The old "first valid response" fallback is removed.OAuthIssuer.matches(_:_:): exact string comparison, except that a root issuer with and without its trailing slash (https://as.exampleandhttps://as.example/) match, as Python'sissuers_match.OAuthAuthorizationServerMetadatadecodesauthorization_response_iss_parameter_supportedintoauthorizationResponseIssParameterSupported.Authorization response
iss(OAuthAuthorizationCodeFlow.swift,OAuthConstants.swift,OAuthErrors.swift)OAuthAuthorizationCodeFlow.ExpectedIssuer(issuer,isRequired).perform(...)andextractCode(...)take a defaultedissuer:/expectedIssuer:parameter. Anissmust equalissuerexactly; a missingissthrows whenisRequired.OAuthAuthorizerbuilds the expected issuer fromasMetadata.issuer ?? selectedAuthorizationServer, withisRequiredset fromauthorization_response_iss_parameter_supported.authorizationResponseIssuerMismatch(expected:actual:)andauthorizationResponseMissingIssuer.application_type(OAuthConfiguration.swift,OAuthClientRegistrar.swift)OAuthConfiguration.ApplicationType(.native,.web) andapplicationType(nilby default).registrationApplicationType: the configured value, else.webfor theauthorizationCodegrant with anhttpsredirect URI on a non-loopback host, else.native.application_type.Authorization server migration (
OAuthAuthorizer.swift)selectedAuthorizationServerandauthorizationServerMetadataare reset.authorizationServermatches the selected server (or the token records none).configuredAuthentication,registrationIssuerandregistrationAttemptIssuer. Registered credentials are bound to the server that issued them; on a server change they are replaced byconfiguredAuthenticationand registration runs again. A registration that was not possible at the previous server is retried at the new one. Pre-registered credentials are kept (Python behaviour).2025-03-26 fallback (
OAuthDiscoveryClient.swift,OAuthModels.swift,OAuthAuthorizer.swift)isFallback = true.endpointOverrides.authorizationServerURLis set,OAuthAuthorizationServerMetadata.defaultEndpoints(issuer:)supplies/authorize,/token,/registerat the origin, withS256.Baselines and docs
conformance-baseline.2026-07-28.yml: client entries removed (26 to 0).conformance-baseline.yml: 19 client entries removed; the extension scenarios remain.README.md: the authorization section lists the five behaviours above.Review fixes
Concurrency (
OAuthAuthorizer.swift,TokenStorage.swift)OAuthAuthorizerdocumented that the transport serialized every call, but requests of one transport run concurrently, so its state was mutated without synchronization and concurrent 401s each ran a flow. Every stored property is now read and written under a lock, andhandleChallengeandprepareAuthorizationrun one at a time through an internalAsyncGate. A challenge that waited retries at once when another challenge replaced the token it was sent with; a proactive refresh that waited reads the token again.InMemoryTokenStoragewas unsynchronized; it now uses a lock.TokenStoragedocuments that implementations must be safe to call from several tasks.Rejected tokens (
OAuthAuthorizer.swift)handleChallengeAlonesay so).endpointOverrides.authorizationServerURLortokenEndpointis set.Discovery (
OAuthDiscoveryClient.swift)OAuthMetadataUnavailable(LocalizedError). Cancellation (URLError.cancelledincluded) is rethrown asCancellationError.fetchAuthorizationServerMetadata(candidates:trustedIssuer:session:): metadata for an issuer set inendpointOverrides.authorizationServerURLis accepted whateverissuerit names.Docs
README.md: refresh-first order, kept state on failed reads, refresh binding, 404/410-only fallback, trusted override issuer, one challenge at a time,TokenStoragethread safety.Diagram
Discovery, registration and the two issuer checks:
sequenceDiagram participant C as OAuthAuthorizer participant R as MCP server participant A as Authorization server C->>R: request R-->>C: 401 with resource_metadata C->>R: GET protected resource metadata R-->>C: authorization_servers C->>A: GET well-known metadata for each candidate A-->>C: metadata with issuer Note over C: issuer must match the candidate, else skip it C->>A: POST register with application_type A-->>C: client_id C->>A: authorization request with PKCE A-->>C: redirect with code, state and iss Note over C: iss must equal the metadata issuer exactly C->>A: POST tokenA rejected token (SEP-2352):
flowchart TD A["401 with a stored token"] --> W{"token replaced by a concurrent challenge?"} W -->|yes| OK["retry with the new token"] W -->|no| E{"refresh token, same metadata URL, not just refreshed, issued by the selected AS?"} E -->|yes| F["refresh"] F -->|ok| OK F -->|fails| B E -->|no| B["read the PRM again, keep the token; a failed read keeps the cached PRM"] B --> C{"selected AS still listed?"} C -->|no| D["reset AS selection and metadata, drop the token"] C -->|yes| X{"refresh not tried yet and possible?"} X -->|yes| F2["refresh"] F2 -->|ok| OK F2 -->|fails| G["drop the token, authorize again"] X -->|no| G D --> G G --> H{"registered credentials bound to another AS?"} H -->|yes| I["restore configured authentication and register again"] H -->|no| J["reuse credentials"]API changes
Added
OAuthAuthorizationCodeFlow.ExpectedIssuerissuer: String,isRequired: Bool,init(issuer:isRequired:);Hashable,SendableOAuthConfiguration.ApplicationType.native,.web;Stringraw valuesOAuthConfiguration.applicationTypeApplicationType?,nilinfers from the redirect URIOAuthAuthorizationError.authorizationResponseIssuerMismatch(expected:actual:)switchstatementsOAuthAuthorizationError.authorizationResponseMissingIssuerswitchstatementsChanged
OAuthAuthorizationCodeFlow.perform(authorizationURL:redirectURI:state:issuer:delegate:session:)issuer: ExpectedIssuer? = nil; source compatibleOAuthAuthorizationCodeFlow.extractCode(from:expectedRedirectURI:expectedState:expectedIssuer:)expectedIssuer: ExpectedIssuer? = nil; source compatibleOAuthConfiguration.init(...)applicationType: ApplicationType? = nilafterclientName; source compatibleTokenStorageInMemoryTokenStorageRemoved
None.
Behavior changes
issuerdiffers from the candidate, or that has noissuer, is no longer used. The comparison is case-sensitive; before, a case-insensitive match or a missingissuerwas accepted, and metadata from another issuer was used as a last resort. Servers whose metadata names another issuer now fail withauthorizationServerIssuerMismatch.issdiffers from the metadata issuer fails; a response withoutissfails when the server advertisesauthorization_response_iss_parameter_supported.application_type:nativefor the default loopback redirect,webfor anhttpsredirect on a non-loopback host.OAuthMetadataUnavailableorCancellationError).endpointOverrides.authorizationServerURLis used whateverissuerit names.Conformance
Baseline entries (server / client), alpha.11:
sep-837-application-type-presententry,sep-2468-*(no normalization, missingiss,isscompared when advertised or not, metadata issuer validation) andauth/authorization-server-migration:sep-2352-reregister-on-as-changepass.auth/2025-03-26-oauth-endpoint-fallback(3 entries) passes.tasks-*(server, 25 entries),auth/dpop,auth/dpop-nonce,auth/enterprise-managed-authorizationandauth/wif-jwt-bearer(client, 11 entries).Tests
Tests/MCPTests/OAuthIssuerTests.swift("OAuth issuer, application type and authorization server changes"):issis accepted whether advertised or not; a differentiss(other host, trailing slash, case, explicit default port) is rejected; a missingissis rejected when advertised; the authorizer passes the metadata issuer and itsisssupport to the flow.nativefor loopback,localhostand custom schemes and forclientCredentials;webfor anhttpshost; an explicit value wins.OAuthDiscoveryClientTests: metadata with another issuer now throwsauthorizationServerIssuerMismatch; new issuer comparison test (root trailing slash only, no case or port normalization); the fallback PRM hasisFallback.HTTPClientTransportTests/OAuthTestScenarios: without any metadata, the flow now reacheshttps://localhost:8080/register(the mock answers 400) instead of failing at discovery.OAuthAuthorizerTests: the mocks record the expected issuer and the authentication each registration started from.Tests/MCPTests/OAuthAuthorizerStateTests.swift("OAuthAuthorizer state"): a 401 refreshes at the token's server before reading the metadata again; a transient metadata failure keeps the token's server and sends nothing to the MCP origin; a token rejected right after its refresh makes the next challenge read the metadata again; a new authorization server drops the stored token; a token without a recorded server is not refreshed at a discovered one; concurrent challenges run one token request; concurrent proactive refreshes run one refresh;InMemoryTokenStorageis safe from several tasks.OAuthDiscoveryClientTests: discovery failed only when every candidate answers 404; 500, 503 and 429 are not an absence; the PRM fallback needs every candidate absent; a network error is not an absence; a trusted issuer's metadata is accepted with anotherissuer.OAuthAuthorizerTests: the mock discovery client can fail the next PRM fetch and recordstrustedIssuer.Review notes
issparameter is compared byte for byte (RFC 9207 §2.4).authorizationServer(stored before this change) is refreshed only when an authorization server URL or token endpoint is configured; otherwise the client authorizes again.configuredAuthentication) are restored, so pre-registered credentials are kept and only DCR results are dropped.OAuthMetadataUnavailableis internal; callers see it only as anError(LocalizedError), not as anOAuthAuthorizationErrorcase.OAuthAuthorizerstill serves one resource; sharing it between transports for different servers is unsupported.OAuthAuthorizationErroris a public non-frozen enum; the two new cases break exhaustiveswitchstatements. The migration guide (P10 ([P10] docs: go-sdk layout, feature guides, design notes and process docs #362)) lists this.docs/protocol.mdin P10 ([P10] docs: go-sdk layout, feature guides, design notes and process docs #362).Verification
Every branch of the stack builds and passes
swift test; all conformance legs pass at their baselines. On this branch, 783 swift-testing tests plus XCTest, all passed.AI usage disclosure: the changes, the tests, the commit messages and this description were written with Claude Opus 5.5 and reviewed by the authors.