Skip to content

[P14] Fix four client auth findings from testing against independent servers - #357

Merged
jeanmatthieu merged 8 commits into
rel/1.0.0from
conformance/oauth-dpop-validation
Nov 25, 2026
Merged

jeanmatthieu merged 8 commits into
rel/1.0.0from
conformance/oauth-dpop-validation

Conversation

@jeanmatthieu

@jeanmatthieu jeanmatthieu commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor
Part P14 of P0–P35, merged into rel/1.0.0 in order (previous: P13 (#358) · next: P15 (#356))
Branch conformance/oauth-dpop-validation
Base conformance/p13-dpop (stacked: GitHub retargets this PR to rel/1.0.0 when the previous part merges)
Commits d0945a8 fix: Don't count authorization time against discoveryTimeout
457a3d2 fix: Throw registrationInformationRequired without a client ID
3d412ef fix: Report refused authorization servers instead of missing metadata
d0d369f fix: Don't warn about the content type of a 202 Accepted
4b8ed7e oauth: second-pass review fixes (DPoP)
03785b1 fix: second-pass review fixes
0a51625 fix: third-pass review fixes
b94f8db fix: fourth-pass review fixes
Size 23 files, +874 / -120

Summary

Stacked on P13 (#358) (conformance/p13-dpop), the earliest branch that has all the code these fixes touch. P15 (#356) builds on this branch.

Four fixes, one commit each. All four are in the client's HTTP and OAuth path.

Commit Finding Fix
d0945a8 A sign-in longer than discoveryTimeout (10 s) is cancelled. The user is asked to sign in again, and the session silently falls back to 2025-11-25. Time spent in the authorizer doesn't count. The timeout starts again when authorization ends.
457a3d2 No client ID and no registration_endpoint sends client_id= (empty) to /authorize. Throw the existing, never-thrown OAuthAuthorizationError.registrationInformationRequired.
3d412ef An authorization server refused by URL validation (insecure, private IP) is reported as "Failed to discover authorization server metadata". When no candidate was fetched, throw the refusal (insecureAuthorizationServerEndpoint with the URL, or privateIPAddressBlocked).
d0d369f Every spec-correct 202 Accepted logs "Unexpected content type:". No warning for 202.

No public API changes. The authorization tracking in HTTPClientTransport is internal. No CHANGELOG entry, because discovery is new in the unreleased 1.0.0. The doc comment on discoveryTimeout and the client, protocol and protocol_versions guides are updated and re-woven.

The main fix (d0945a8) changes connect like this:

 Client.connect (.automatic)
   send server/discover, start the discoveryTimeout timer
     HTTPClientTransport.post
       401 -> authorizer.handleChallenge   # OAuth: the user signs in at a browser
-  timer fires mid sign-in -> cancel the POST (and the sign-in)
-    -> fall back to initialize -> 401 -> second sign-in -> 2025-11-25
+  timer fires mid sign-in -> wait for authorization to end
+    -> restart the full timeout for the authorized POST
+    -> 2026-07-28 (fall back only if the server stays silent after that)

How we found these

We asked an Inspector maintainer whether there is a conformant authorization server to test OAuth 2.1, enterprise-managed authorization and DPoP against. There isn't one. He pointed us to the modelcontextprotocol/conformance auth suites and to Inspector's configurable test servers. We already run conformance, so we used this as a chance to test against implementations we didn't write:

Experiment What we ran Result
E1 Conformance built from upstream main (one commit past our pin, 0.2.0-alpha.12), --suite auth and --suite extensions All pass: 20 scenarios and 283 checks, including auth/dpop, auth/dpop-nonce and auth/enterprise-managed-authorization. Nothing unreleased for client auth.
E2 Our client against Inspector's composable test servers (test-servers/configs/oauth-*.json): a combined authorization server and resource server written in TS, with a consent page Found all four findings. See below.
E5 Our BearerTokenValidator and ProtectedResourceMetadataValidator behind Keycloak 26.4 (ES256 JWTs), driven by our client and by the TS SDK 2.4 client Pass: 401 with resource_metadata, invalid_token, wrong-audience rejection, 403 insufficient_scope and step-up, on both wires.
E4 DPoP against Keycloak, with a software P-256 key and a Secure Enclave key Pass: Keycloak accepted the token-request proofs, token_type=DPoP, and cnf.jkt equals our RFC 7638 thumbprint. An independent RFC 9449 §7 check on the resource server accepted every proof, and DPoP plus step-up works.

How each finding showed up in E2:

  • d0945a8. Against oauth-stalled-token-http.json, the interactive authorization ran twice for one connect. A logging stub showed why: the probe timed out ("server/discover timed out; falling back to initialize") while the token request was pending, and the initialize fallback started a new flow. We then reproduced it against a healthy dual-era server (transport.modern: true) by delaying the consent step by 15 seconds, to simulate a person signing in. The result was two consent prompts and protocolVersion=2025-11-25. With an instant consent, the same server negotiates 2026-07-28.
  • 457a3d2. Against oauth-cimd-http.json (DCR off) with no client ID, the authorization request carried client_id= and the server answered invalid_client.
  • 3d412ef. Against oauth-insecure-token-endpoint-http.json (issuer http://localhost.:8091), the client correctly refused the issuer, but the error said metadata discovery failed. The debug log had no reason.
  • d0d369f. The warning appeared on every successful connection in the driver logs.

Why our testing missed them

  • The conformance authorization server answers at once. No client scenario holds the authorization step open, so nothing measured discoveryTimeout against authorization. All our auth unit tests answer instantly too.
  • No fixture combined DCR off with no client ID. Conformance gives the client a client ID or a registration endpoint in every scenario, and our registrar test only covered a plain client ID with no endpoint.
  • Refused candidates were only asserted as "some OAuthAuthorizationError". The private-IP test passed with the generic error.
  • The interop matrix has no auth. No other SDK's client or server exercises ours with authorization.
  • Logs aren't asserted. The 202 warning was visible but never checked.

Limits of this round:

  • Enterprise-managed authorization is covered only by conformance's mock. A real IdP (xaa.dev, via Inspector's xaa-ema-http.json) needs credentials we didn't have.
  • DPoP server nonces are covered only by auth/dpop-nonce, because Keycloak doesn't issue them.
  • The SDK has no resource-server DPoP check, which is documented. E4 used a throwaway verifier.
  • Inspector's built-in authorization server is a test fixture, not certified. Passing against it, or against Keycloak, isn't a conformance claim.

The experiment harness (driver, resource server, Keycloak realm) was scratch work outside the repo and isn't part of this PR.

Evidence

Each new test fails with its source fix reverted (stashed) and passes with it:

  • Before:

    ✘ "Signing in does not count against the discovery timeout"
        result.protocolVersion == 2026-07-28   -> 2025-11-25
        authorizer.challenges == 1              -> 2
    ✘ "The discovery timeout starts again after signing in"   challenges == 1 -> 2
    ✘ "Throws registrationInformationRequired without a client ID or a registration endpoint"
        [authorization_code, client_credentials]   no error thrown, nil returned
    ✘ "Skips private IP candidates without making HTTP calls"        authorizationServerMetadataDiscoveryFailed
    ✘ "An insecure issuer is reported as insecure, not as missing metadata"   authorizationServerMetadataDiscoveryFailed
    ✘ "A 202 Accepted without a body logs no warning; ..."   ["Unexpected content type: "]
    

    After: all pass. "The discovery timeout starts again after signing in" takes 0.42 s, the 300 ms sign-in plus the 100 ms timeout, which shows the timer restarts rather than being disabled. The guard test "A refused candidate next to one without metadata still reports missing metadata" passes before and after, so the 2025-03-26 fallback trigger is unchanged.

  • swift test: 990 tests in 94 suites pass, and the 102 snippet tests.

  • Linux (scripts/ci-linux.sh, Swift 6.1, RHEL UBI 9): swift build --build-tests and swift test pass (953 tests).

  • swift scripts/weave.swift --check and generate-documentation --warnings-as-errors pass. (scripts/doc-coverage.swift arrives later in the stack.)

  • Conformance, all legs, with no baseline changes:

    Leg Client Server
    --spec-version 2025-11-25 225 / 0 failed 84 / 0 failed
    --spec-version 2026-07-28 384 / 0 failed 151 / 0 failed
    default (extensions, including DPoP and enterprise-managed) 465 / 0 failed 204 / 25 failed, all in the baseline
    --requirements 2025-11-25 280 / 0 failed 84 / 0 failed
    --requirements 2026-07-28 437 / 0 failed 168 / 25 failed

    The 25 server failures are gaps that P13 ([P13] oauth: DPoP-bound tokens (RFC 9449, SEP-1932) #358) already has (the default leg's baseline lists them); later PRs in the stack fix them. At the top of the stack every leg passes with empty baselines.

  • The interop matrix (scripts/run-interop.sh) arrives in P15 ([P15] interop: matrix against the Go and Python SDKs #356), above this PR.

Merge Danger

Door: two-way

Each commit reverts on its own.

Blast Radius: client-connect

  • d0945a81: with an authorizer, an .automatic connect now waits as long as authorization takes before the timeout starts again. An authorizer that never returns now holds connect open, where the timer used to cancel it. That matches the documented "connect as a whole has no timeout".
  • 457a3d29: an app that relied on sending an empty client_id now gets registrationInformationRequired locally instead of invalid_client from the server.
  • 3d412ef1: when every candidate is refused, discovery throws a different code than authorizationServerMetadataDiscoveryFailed. Code that matched on that exact code for this case sees the specific one instead.
  • 4b8ed7e6: with dpop configured, a Bearer token for a protected resource whose metadata sets dpop_bound_access_tokens_required is now refused before it is stored. A grant fails with OAuthAuthorizationError.dpopRequired, and a refresh that returns Bearer falls through to a full grant. Before, the token was stored and sent, and the resource rejected it.

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. One review-fix commit (0a51625) was also written with Gemini, as its Assisted-by trailer says.

Client.connect in .automatic mode sends server/discover and gives the
server discoveryTimeout (10 seconds) to answer before it falls back to
initialize. The timer started when the request was dispatched, so it
also ran while HTTPClientTransport was inside the authorizer for that
request: a 401 on server/discover starts the OAuth flow, and for the
authorization_code grant that is a user signing in at a browser.

A sign-in longer than 10 seconds was therefore cancelled when the timer
fired. The client fell back to initialize, which was challenged again
and started a second authorization flow, and the session was pinned to
2025-11-25 even when the server serves 2026-07-28. Found by driving the
client against an Inspector test server that serves both eras, with a
consent step delayed by 15 seconds; a stalled token endpoint triggers
the same path.

The timeout exists to detect a server that never answers server/discover
(SEP-2575 discovery, falling back to the handshake). Time the client
spends authorizing says nothing about that. HTTPClientTransport now
records the authorizer calls (prepareAuthorization and handleChallenge)
of each request's POST, and Client waits for an authorization in
progress and starts the full timeout again when it ends. A server that
stays silent after authorization still gets the fallback. Authorization
failures are rethrown as before. No public API changes.
With authentication .none(clientID: "") the authorizer registers the
client dynamically (RFC 7591) or uses a Client ID Metadata Document
(SEP-991). When the authorization server offers neither, because it has
no registration_endpoint and CIMD does not apply, OAuthClientRegistrar
returned nil as if no registration were needed. The flow then went on
with the empty client ID: the authorization request carried client_id=
and the server answered invalid_client, an error that does not say the
client needs pre-registered credentials.

OAuthAuthorizationError.registrationInformationRequired already
describes this case ("No supported client registration mechanism was
available; provide pre-registered client credentials") but nothing
threw it. The registrar now throws it when the client ID is empty and
there is no registration endpoint. A pre-registered client ID is still
used as is, and the jwt-bearer grant, which skips registration, is not
affected.

Found by driving the client against the Inspector test server
oauth-cimd-http.json, which turns dynamic registration off, without a
client ID.
OAuthDiscoveryClient.fetchAuthorizationServerMetadata skips a candidate
authorization server that fails URL validation (not https and not an
allowed loopback host) or whose host is a private address. It skipped
them silently: when every candidate was refused, discovery threw
authorizationServerMetadataDiscoveryFailed ("Failed to discover
authorization server metadata"), which reads as if the server serves no
metadata and hides that the client refused the URL before sending any
request.

When no candidate was fetched, discovery now throws the error that
refused the first one: insecureAuthorizationServerEndpoint with the URL,
or privateIPAddressBlocked. When any candidate was fetched, the errors
are unchanged, so the 2025-03-26 fallback, which keys on
authorizationServerMetadataDiscoveryFailed, still runs. The refusal
itself is unchanged.

Found by driving the client against the Inspector test server
oauth-insecure-token-endpoint-http.json, whose issuer is
http://localhost.:8091.
Streamable HTTP: a server that accepts a JSON-RPC notification or
response "MUST return HTTP status code 202 Accepted with no body"
(basic/transports, Sending Messages to the Server). Such a response has
no Content-Type, so HTTPClientTransport.processResponse fell through to
logger.warning("Unexpected content type: "), and every connection to a
compliant server logged a warning, for example after
notifications/initialized.

A 202 now ends the response quietly. A 202 that does carry JSON or SSE
is still read as before, and any other 2xx with an unexpected content
type still logs the warning.

Noticed in the client logs while driving the auth experiments against
the Inspector test servers.
- A Bearer token for a protected resource whose metadata sets
  dpop_bound_access_tokens_required fails with dpopRequired instead of
  being stored. RFC 9728 §2: such a resource always requires DPoP-bound
  tokens, so it would reject every request and the client would
  re-authorize until maxAuthorizationAttempts. Other Bearer answers stay a
  downgrade (RFC 9449 §5). The dpopRequired docs, its message, the
  troubleshooting row and the protocol guide say so.
- The protocol guide's SSRF section says that discovery follows a
  redirect to a loopback host only from a loopback host, and checks each
  hop against the previous one. The code change is in
  conformance/p11-fixes; this line was last changed here, so the guide
  edit would conflict lower in the stack.
- A refresh that returns a Bearer token for a resource requiring DPoP now
  returns false instead of throwing dpopRequired before tokenStorage.clear(),
  so answerChallenge clears the stale token and tries a full grant.
- Keep the 2025-03-26 defaultEndpoints fallback when a synthesized fallback
  origin is loopback HTTP or a private IP, preserving tokenEndpoint overrides
  with client credentials while still validating default endpoints on use.
- Share OAuthURLValidating private-IP/AS helpers and Authorization.resumeWaiters().
- Widen signInOutlastsDiscoveryTimeout to 1 s / 2 s with per-test hosts and a
  suite time limit, and add tests for failed sign-in past the deadline,
  cancelling connect during sign-in, and two refused AS candidates.
- Sync docs in OAuthTokenExchange, OAuthClientRegistrar, design/auth.md, and
  docs/protocol.md.

Assisted-by: Gemini
- A 202 Accepted without JSON or SSE still logs "Unexpected content
  type" when it answers a request, in both processResponse copies: only
  a notification or a response is accepted with 202 (Streamable HTTP,
  Sending Messages to the Server); a request is owed JSON or SSE, and
  without the warning it waits with no hint.
- OAuthDiscoveryFetching requires the reportRefused variant of
  fetchAuthorizationServerMetadata; the variant without it forwards
  reportRefused: true. The old default dropped the flag, so
  MockDiscoveryClient never saw it.
- cancellingConnectDuringSignIn waits on the transport's waiter count
  instead of a fixed 100 ms, and its sign-in ignores cancellation until
  released, so only the discovery timer's cancellation handler
  (stopWaitingForAuthorization) can end the wait.
  failedSignInAfterDeadlineThrows and timeoutAfterSignIn use the 1 s
  timeout and 2 s sign-in of signInOutlastsDiscoveryTimeout, so a slow
  401 cannot beat the timer.
- Tests: a 202 for a request logs the warning; with the mock, a
  2025-03-26 fallback origin is fetched with reportRefused false and
  falls back to default endpoints, and a listed server's refusal is
  thrown; with OAuthURLValidator, private-address resource_metadata,
  token and authorization endpoints are refused before any request.
- Docs: design/auth.md on refused candidates, the refused-origin
  fallback, Bearer answers for a DPoP-required resource, and
  registration errors thrown without a registration endpoint; the
  refreshAccessToken and tokenEndpoint(issuer:) doc comments; the catch
  comment in maybeRegisterClient; registrationInformationRequired in the
  protocol guide.
@jeanmatthieu
jeanmatthieu requested a review from a team as a code owner November 25, 2026 11:22
Base automatically changed from conformance/p13-dpop to rel/1.0.0 November 25, 2026 12:40

@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

@jeanmatthieu
jeanmatthieu merged commit af4b353 into rel/1.0.0 Nov 25, 2026
@jeanmatthieu
jeanmatthieu deleted the conformance/oauth-dpop-validation branch November 25, 2026 12:41
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