Repository navigation
[P14] Fix four client auth findings from testing against independent servers - #357
Merged
Merged
Conversation
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.
This was referenced 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: P13 (#358) · next: P15 (#356))conformance/oauth-dpop-validationconformance/p13-dpop(stacked: GitHub retargets this PR torel/1.0.0when the previous part merges)d0945a8fix: Don't count authorization time against discoveryTimeout457a3d2fix: Throw registrationInformationRequired without a client ID3d412effix: Report refused authorization servers instead of missing metadatad0d369ffix: Don't warn about the content type of a 202 Accepted4b8ed7eoauth: second-pass review fixes (DPoP)03785b1fix: second-pass review fixes0a51625fix: third-pass review fixesb94f8dbfix: fourth-pass review fixesSummary
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.
d0945a8discoveryTimeout(10 s) is cancelled. The user is asked to sign in again, and the session silently falls back to2025-11-25.457a3d2registration_endpointsendsclient_id=(empty) to/authorize.OAuthAuthorizationError.registrationInformationRequired.3d412efinsecureAuthorizationServerEndpointwith the URL, orprivateIPAddressBlocked).d0d369f202 Acceptedlogs "Unexpected content type:".No public API changes. The authorization tracking in
HTTPClientTransportis internal. No CHANGELOG entry, because discovery is new in the unreleased 1.0.0. The doc comment ondiscoveryTimeoutand theclient,protocolandprotocol_versionsguides are updated and re-woven.The main fix (
d0945a8) changesconnectlike 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/conformanceauth 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:main(one commit past our pin,0.2.0-alpha.12),--suite authand--suite extensionsauth/dpop,auth/dpop-nonceandauth/enterprise-managed-authorization. Nothing unreleased for client auth.test-servers/configs/oauth-*.json): a combined authorization server and resource server written in TS, with a consent pageBearerTokenValidatorandProtectedResourceMetadataValidatorbehind Keycloak 26.4 (ES256 JWTs), driven by our client and by the TS SDK 2.4 clientresource_metadata,invalid_token, wrong-audience rejection, 403insufficient_scopeand step-up, on both wires.token_type=DPoP, andcnf.jktequals 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. Againstoauth-stalled-token-http.json, the interactive authorization ran twice for oneconnect. A logging stub showed why: the probe timed out ("server/discover timed out; falling back to initialize") while the token request was pending, and theinitializefallback 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 andprotocolVersion=2025-11-25. With an instant consent, the same server negotiates2026-07-28.457a3d2. Againstoauth-cimd-http.json(DCR off) with no client ID, the authorization request carriedclient_id=and the server answeredinvalid_client.3d412ef. Againstoauth-insecure-token-endpoint-http.json(issuerhttp://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
discoveryTimeoutagainst authorization. All our auth unit tests answer instantly too.OAuthAuthorizationError". The private-IP test passed with the generic error.Limits of this round:
xaa-ema-http.json) needs credentials we didn't have.auth/dpop-nonce, because Keycloak doesn't issue them.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:
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-testsandswift testpass (953 tests).swift scripts/weave.swift --checkandgenerate-documentation --warnings-as-errorspass. (scripts/doc-coverage.swiftarrives later in the stack.)Conformance, all legs, with no baseline changes:
--spec-version 2025-11-25--spec-version 2026-07-28--requirements 2025-11-25--requirements 2026-07-28The 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.automaticconnect now waits as long as authorization takes before the timeout starts again. An authorizer that never returns now holdsconnectopen, where the timer used to cancel it. That matches the documented "connectas a whole has no timeout".457a3d29: an app that relied on sending an emptyclient_idnow getsregistrationInformationRequiredlocally instead ofinvalid_clientfrom the server.3d412ef1: when every candidate is refused, discovery throws a different code thanauthorizationServerMetadataDiscoveryFailed. Code that matched on that exact code for this case sees the specific one instead.4b8ed7e6: withdpopconfigured, aBearertoken for a protected resource whose metadata setsdpop_bound_access_tokens_requiredis now refused before it is stored. A grant fails withOAuthAuthorizationError.dpopRequired, and a refresh that returnsBearerfalls 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 itsAssisted-bytrailer says.