Skip to content

[P8] oauth: issuer checks, application_type, AS migration (SEP-2468/837/2352) - #363

Merged
jeanmatthieu merged 4 commits into
rel/1.0.0from
conformance/p8-oauth
Nov 25, 2026
Merged

jeanmatthieu merged 4 commits into
rel/1.0.0from
conformance/p8-oauth

Conversation

@jeanmatthieu

@jeanmatthieu jeanmatthieu commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor
Part P8 of P0–P35, merged into rel/1.0.0 in order (previous: P7 (#364) · next: P10 (#362))
Branch conformance/p8-oauth
Base conformance/p7-mrtr (stacked: GitHub retargets this PR to rel/1.0.0 when the previous part merges)
Commits 4f1f67d oauth: issuer checks, application_type, AS migration (SEP-2468/837/2352)
82ab1d5 oauth: review fixes
c6762d9 oauth: compute the PKCE S256 challenge with swift-crypto
78cb7d3 oauth: third-pass review fixes
Size 21 files, +1748 / -222

Summary

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. 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

  • SEP-2468 / RFC 8414 §3.3: the client must reject authorization server metadata whose issuer differs from the issuer it asked for, and must compare the iss authorization response parameter (RFC 9207) without normalization. OAuthDiscoveryClient accepted the first valid metadata from any issuer and used its issuer as the server identity, and compared case-insensitively.
  • SEP-837: dynamic client registration must send the OpenID Connect application_type. Every 2026-07-28 auth scenario that registers failed sep-837-application-type-present.
  • SEP-2352: when a resource moves to another authorization server, the client must rediscover, drop credentials bound to the old server and register again.
  • Known issue from P0: auth/2025-03-26-oauth-endpoint-fallback failed 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 when OAuthIssuer.matches(issuer, candidate). Metadata with another issuer, or none, is skipped; if only such metadata was found, it throws authorizationServerIssuerMismatch(expected:actual:), otherwise authorizationServerMetadataDiscoveryFailed. The old "first valid response" fallback is removed.
  • New internal OAuthIssuer.matches(_:_:): exact string comparison, except that a root issuer with and without its trailing slash (https://as.example and https://as.example/) match, as Python's issuers_match.
  • OAuthAuthorizationServerMetadata decodes authorization_response_iss_parameter_supported into authorizationResponseIssParameterSupported.

Authorization response iss (OAuthAuthorizationCodeFlow.swift, OAuthConstants.swift, OAuthErrors.swift)

  • New OAuthAuthorizationCodeFlow.ExpectedIssuer (issuer, isRequired).
  • perform(...) and extractCode(...) take a defaulted issuer: / expectedIssuer: parameter. An iss must equal issuer exactly; a missing iss throws when isRequired.
  • OAuthAuthorizer builds the expected issuer from asMetadata.issuer ?? selectedAuthorizationServer, with isRequired set from authorization_response_iss_parameter_supported.
  • New errors authorizationResponseIssuerMismatch(expected:actual:) and authorizationResponseMissingIssuer.

application_type (OAuthConfiguration.swift, OAuthClientRegistrar.swift)

  • New OAuthConfiguration.ApplicationType (.native, .web) and applicationType (nil by default).
  • Internal registrationApplicationType: the configured value, else .web for the authorizationCode grant with an https redirect URI on a non-loopback host, else .native.
  • The registration payload includes application_type.

Authorization server migration (OAuthAuthorizer.swift)

  • On a 401 with a stored token, the cached protected resource metadata (PRM) and its URL are cleared and read again (after a refresh attempt).
  • When the new PRM no longer lists the selected authorization server, selectedAuthorizationServer and authorizationServerMetadata are reset.
  • A refresh is attempted only when the rejected token's authorizationServer matches the selected server (or the token records none).
  • New configuredAuthentication, registrationIssuer and registrationAttemptIssuer. Registered credentials are bound to the server that issued them; on a server change they are replaced by configuredAuthentication and 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)

  • The synthetic PRM built when the server publishes none has isFallback = true.
  • For such a PRM, when authorization server discovery fails (every URL answers 404 or 410) and no endpointOverrides.authorizationServerURL is set, OAuthAuthorizationServerMetadata.defaultEndpoints(issuer:) supplies /authorize, /token, /register at the origin, with S256.

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)

  • OAuthAuthorizer documented 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, and handleChallenge and prepareAuthorization run one at a time through an internal AsyncGate. 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.
  • InMemoryTokenStorage was unsynchronized; it now uses a lock. TokenStorage documents that implementations must be safe to call from several tasks.

Rejected tokens (OAuthAuthorizer.swift)

  • A 401 cleared the token and the cached PRM before reading the PRM again, so a failed read lost both. Now a refreshable token is refreshed first at the server that issued it, when the challenge names the same metadata URL and the token is not the one the last refresh returned. Otherwise the PRM is read again before the token is cleared; a failed read falls back to the cached copy, and with none it throws and the token is kept (README and the comment in handleChallengeAlone say so).
  • A failed PRM read keeps the cached copy (except when the challenge names another metadata URL, or on cancellation). Synthesized fallback metadata is used only on first discovery, never in place of a fetched copy.
  • A token with a recorded server is refreshed only at the matching selected server. A token without one was refreshed at any discovered server; it is now refreshed only when endpointOverrides.authorizationServerURL or tokenEndpoint is set.
  • When the PRM no longer lists the selected server, or discovery selects another server, the stored token is cleared, so its refresh token never reaches the new server.

Discovery (OAuthDiscoveryClient.swift)

  • Any failed metadata GET (network error, timeout, 5xx, bad body) counted as "no metadata", which triggered the 2025-03-26 default endpoints at the MCP origin. Each GET is now classified: found, absent (404 or 410), or unavailable. The fallback PRM and the default endpoints apply only when every candidate is absent; otherwise discovery throws the internal OAuthMetadataUnavailable (LocalizedError). Cancellation (URLError.cancelled included) is rethrown as CancellationError.
  • fetchAuthorizationServerMetadata(candidates:trustedIssuer:session:): metadata for an issuer set in endpointOverrides.authorizationServerURL is accepted whatever issuer it 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, TokenStorage thread 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 token
Loading

A 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"]
Loading

API changes

Added

Symbol Notes
OAuthAuthorizationCodeFlow.ExpectedIssuer issuer: String, isRequired: Bool, init(issuer:isRequired:); Hashable, Sendable
OAuthConfiguration.ApplicationType .native, .web; String raw values
OAuthConfiguration.applicationType ApplicationType?, nil infers from the redirect URI
OAuthAuthorizationError.authorizationResponseIssuerMismatch(expected:actual:) breaking for exhaustive switch statements
OAuthAuthorizationError.authorizationResponseMissingIssuer breaking for exhaustive switch statements

Changed

Symbol Change
OAuthAuthorizationCodeFlow.perform(authorizationURL:redirectURI:state:issuer:delegate:session:) new issuer: ExpectedIssuer? = nil; source compatible
OAuthAuthorizationCodeFlow.extractCode(from:expectedRedirectURI:expectedState:expectedIssuer:) new expectedIssuer: ExpectedIssuer? = nil; source compatible
OAuthConfiguration.init(...) new applicationType: ApplicationType? = nil after clientName; source compatible
TokenStorage documented requirement: implementations must be safe to call from several tasks at once; no signature change
InMemoryTokenStorage guarded by a lock

Removed

None.

Behavior changes

  • Authorization server metadata whose issuer differs from the candidate, or that has no issuer, is no longer used. The comparison is case-sensitive; before, a case-insensitive match or a missing issuer was accepted, and metadata from another issuer was used as a last resort. Servers whose metadata names another issuer now fail with authorizationServerIssuerMismatch.
  • An authorization response whose iss differs from the metadata issuer fails; a response without iss fails when the server advertises authorization_response_iss_parameter_supported.
  • Registration requests carry application_type: native for the default loopback redirect, web for an https redirect on a non-loopback host.
  • On a 401 with a refreshable token, the client refreshes at the issuing server first; when that is not possible or fails, or the refreshed token is rejected too, it requests the protected resource metadata again. The token is cleared only after that read; a failed read keeps the cached metadata.
  • A refresh token is no longer sent to an authorization server other than the one that issued it. A token without a recorded server is refreshed only at a configured server or token endpoint. A change of authorization server clears the stored token.
  • A server that publishes no PRM and no authorization server metadata is now usable: the client registers, authorizes and requests tokens at its origin. Before, the flow failed with a metadata discovery error. This applies only when every metadata URL answers 404 or 410; a network error, timeout, cancellation or other status fails the request (OAuthMetadataUnavailable or CancellationError).
  • Metadata of the issuer in endpointOverrides.authorizationServerURL is used whatever issuer it names.
  • Concurrent requests that get a 401 wait for the first challenge and retry with the token it obtained; concurrent proactive refreshes run one refresh.

Conformance

Baseline entries (server / client), alpha.11:

Leg Before (P7) After (P8)
2025-11-25 0 / 0 0 / 0
2026-07-28 0 / 26 0 / 0
default 25 / 30 25 / 11
  • 2026-07-28 client: every sep-837-application-type-present entry, sep-2468-* (no normalization, missing iss, iss compared when advertised or not, metadata issuer validation) and auth/authorization-server-migration:sep-2352-reregister-on-as-change pass.
  • Default client: auth/2025-03-26-oauth-endpoint-fallback (3 entries) passes.
  • The default leg keeps only extension scenarios, which are not scored: tasks-* (server, 25 entries), auth/dpop, auth/dpop-nonce, auth/enterprise-managed-authorization and auth/wif-jwt-bearer (client, 11 entries).
  • Tier score: 100% for client and server at 2025-11-25 and 2026-07-28.

Tests

  • New Tests/MCPTests/OAuthIssuerTests.swift ("OAuth issuer, application type and authorization server changes"):
    • RFC 9207: a matching iss is accepted whether advertised or not; a different iss (other host, trailing slash, case, explicit default port) is rejected; a missing iss is rejected when advertised; the authorizer passes the metadata issuer and its iss support to the flow.
    • SEP-837: native for loopback, localhost and custom schemes and for clientCredentials; web for an https host; an explicit value wins.
    • SEP-2352: a second 401 whose PRM names another server re-reads the PRM and registers again from the configured credentials; without a server change no second registration happens.
  • OAuthDiscoveryClientTests: metadata with another issuer now throws authorizationServerIssuerMismatch; new issuer comparison test (root trailing slash only, no case or port normalization); the fallback PRM has isFallback.
  • HTTPClientTransportTests / OAuthTestScenarios: without any metadata, the flow now reaches https://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.
  • Review fixes:
    • New 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; InMemoryTokenStorage is 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 another issuer.
    • OAuthAuthorizerTests: the mock discovery client can fail the next PRM fetch and records trustedIssuer.
  • 783 swift-testing tests pass, plus XCTest.

Review notes

  • The two comparisons differ on purpose: metadata issuers allow a root trailing slash (as Python), the iss parameter is compared byte for byte (RFC 9207 §2.4).
  • A 401 with a token that cannot be refreshed, or whose refresh fails, costs a PRM request. This is what lets the client notice an authorization server change; a refreshable token reaches it only when the refreshed token is rejected too.
  • A token without a recorded authorizationServer (stored before this change) is refreshed only when an authorization server URL or token endpoint is configured; otherwise the client authorizes again.
  • On a server change, credentials configured at creation (configuredAuthentication) are restored, so pre-registered credentials are kept and only DCR results are dropped.
  • The origin fallback applies only to the synthetic PRM, only without an authorization server URL override, and only when every metadata URL answers 404 or 410.
  • OAuthMetadataUnavailable is internal; callers see it only as an Error (LocalizedError), not as an OAuthAuthorizationError case.
  • OAuthAuthorizer still serves one resource; sharing it between transports for different servers is unsupported.
  • OAuthAuthorizationError is a public non-frozen enum; the two new cases break exhaustive switch statements. The migration guide (P10 ([P10] docs: go-sdk layout, feature guides, design notes and process docs #362)) lists this.
  • The README section added here is replaced by docs/protocol.md in P10 ([P10] docs: go-sdk layout, feature guides, design notes and process docs #362).
  • Deferred, not scored (extensions): DPoP (SEP-1932, P13 ([P13] oauth: DPoP-bound tokens (RFC 9449, SEP-1932) #358)), enterprise-managed authorization and WIF jwt-bearer (P12 ([P12] oauth: jwt-bearer grant, token exchange, enterprise-managed authorization #359)).

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.

swift build
swift test
swift test --filter OAuthIssuerTests
export npm_config_registry=https://registry.npmjs.org
BIN=$(swift build --show-bin-path)
scripts/run-conformance.sh --spec-version 2026-07-28 --mode client --bin-path "$BIN"
scripts/run-conformance.sh --spec-version 2025-11-25 --bin-path "$BIN"
scripts/run-conformance.sh --bin-path "$BIN"
scripts/run-conformance.sh --requirements 2025-11-25 --bin-path "$BIN"
scripts/run-conformance.sh --requirements 2026-07-28 --bin-path "$BIN"

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.

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.
canarik
canarik previously approved these changes Nov 25, 2026

@canarik canarik left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you @jeanmatthieu

Base automatically changed from conformance/p7-mrtr to rel/1.0.0 November 25, 2026 12:37
@jeanmatthieu
jeanmatthieu dismissed canarik’s stale review November 25, 2026 12:37

The base branch was changed.

@jeanmatthieu
jeanmatthieu merged commit 32a3679 into rel/1.0.0 Nov 25, 2026
@jeanmatthieu
jeanmatthieu deleted the conformance/p8-oauth branch November 25, 2026 12:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants