Skip to content

fix(keycardai-oauth): the request timeout bounds the credential call too - #437

Open
cmars wants to merge 1 commit into
mainfrom
casey/eco-524-python-device-grant-bound-the-credential-call
Open

cmars wants to merge 1 commit into
mainfrom
casey/eco-524-python-device-grant-bound-the-credential-call

Conversation

@cmars

@cmars cmars commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

The device grant's timeout now bounds the credential's client authentication and the request together. Linear: ECO-524. Follows the review of keycard-sdk-spec #109.

request_device_authorization, poll_device_token, and each poll of wait_for_device_token run both steps under one asyncio.wait_for. Go does the same with one context.WithTimeout. Before this change, the timeout went only to httpx, which applies it to each phase of a request, and the credential call had no bound.

Failure Error
The credential call and the request together outlast timeout NetworkError. wait_for_device_token stops with DevicePollError and a doubled interval.
The credential raises, including its own TimeoutError or NetworkError That exception, unchanged (device spec unit row 27)

Tests

  • A credential that hangs, a request that hangs, and both together, where each step alone fits in the 0.2 second timeout. Each case runs for the device authorization request and for poll once, and each fails without this change.
  • A credential's own TimeoutError or NetworkError comes back unchanged from poll once, the device authorization request, and the loop.
  • In the loop, a credential that hangs gives DevicePollError with interval 10.
  • Row 28 accepts httpx.ReadTimeout or asyncio.TimeoutError as the cause, because both timeouts are 0.2 seconds.

🤖 Generated with Claude Code

request_device_authorization, poll_device_token, and each poll of
wait_for_device_token run the credential's client authentication and
the request under one asyncio.wait_for, so the timeout bounds the whole
round trip, as Go does with one context.WithTimeout. httpx's timeout
alone applies to each phase of the request, and the credential call had
no bound. Running out of time raises NetworkError, so poll until done
stops with DevicePollError and a doubled interval. An exception the
credential raises propagates unchanged (unit row 27).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@claude claude Bot 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.

Findings marked 🟡 are optional suggestions and need no follow-up push.

Additional findings (outside the current diff — GitHub can't attach inline comments there):

  • 🟡 packages/oauth/src/keycardai/oauth/client.py — nit: The wait_for_device_token docstring now misdescribes timeouts. It still calls timeout only "the httpx timeout of each poll". It also says any credential failure "propagates as is", but a credential hang now raises DevicePollError. Fix: say that timeout bounds the credential call plus the request for each poll. Also add a credential timeout to the DevicePollError entry, and limit the Exception entry to errors the credential itself raises.

    Why this was flagged

    The docstring at client.py:1469-1472 says timeout is the httpx per-phase timeout of each poll. Args at 1488 says "Timeout for each request". Raises at 1509-1510 says the credential's failure "propagates as is, without interval". After this change, _authenticate_and_send runs the credential inside asyncio.wait_for(run(), limit) (client.py:1294). When the credential outlasts the limit, the loop gets NetworkError and the except NetworkError branch at client.py:1558 raises DevicePollError(interval * 2, e). The PR updated the sibling docstrings for request_device_authorization and poll_device_token but not this one. Callers reading it would expect a slow credential to propagate unchanged, but they get DevicePollError instead.

    Verification: Lines 1469-1472 still say "timeout is the httpx timeout of each poll (connect, read, write, and pool)". But _authenticate_and_send runs the credential call and the send inside asyncio.wait_for(run(), limit) and turns a timeout into NetworkError, which line 1558 re-raises as DevicePollError. So a hanging credential raises DevicePollError, which the Raises entries at 1505-1510 leave out.

Comment on lines +1294 to +1296
try:
return await asyncio.wait_for(run(), limit)
except asyncio.TimeoutError as e:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔴 On Python 3.10 and 3.11, a cancellation that lands just as a device request finishes is silently lost. The polling loop then keeps calling the credential and sending polls. asyncio.wait_for on those versions returns the inner result when the inner task is already done at cancel time, which swallows the CancelledError. Fix: bound the call so outer cancellation always propagates, for example with asyncio.timeout on 3.11+ and a cancel-aware fallback on 3.10. This covers request_device_authorization, poll_device_token and each wait_for_device_token poll.

Why this was flagged

pyproject.toml sets requires-python = ">=3.10". In CPython 3.10 and 3.11, asyncio.wait_for catches CancelledError and, when fut.done(), does return fut.result() without re-raising. That code was rewritten only in 3.12. _authenticate_and_send (client.py:1294-1296) now wraps every device request in asyncio.wait_for. Suppose a caller cancels wait_for_device_token, for example through asyncio.timeout or a TaskGroup, in the same loop iteration the poll response completes with authorization_pending. The cancellation is consumed, the loop takes the continue path, and it sleeps, calls the credential and polls again. The docstring at client.py:1467-1469 promises it will not do that. The caller's deadline is missed until the device code expires or the user approves. On the base branch the credential and _send_device_request were awaited directly, so the CancelledError always reached the caller. The await asyncio.sleep(0) guard at client.py:1548 does not help, because the cancellation was already swallowed.

Verification: On 3.10 and 3.11, wait_for runs fut as a separate task. Its except CancelledError: if fut.done(): return fut.result() path returns the result without re-raising, which drops the cancellation (bpo-42130 / gh-86296). The diff adds return await asyncio.wait_for(run(), limit) at client.py:1295. This is a regression. The base had no wait_for anywhere in packages/oauth/src.

Comment on lines +1283 to +1295
limit = timeout or self.config.timeout

async def run() -> "HttpResponse | _ClientAuthenticationFailure":
try:
client_auth = await authenticator.client_authentication(
issuer=issuer, endpoint=endpoint
)
except Exception as e:
return _ClientAuthenticationFailure(e)
return await self._send_device_request(build(client_auth), limit, operation)

try:
return await asyncio.wait_for(run(), limit)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 (optional) Callers whose timeout is an httpx.Timeout object, not a float, now get a TypeError from every device grant call. On the base branch those calls work. limit = timeout or self.config.timeout now goes to asyncio.wait_for, which compares it with 0, while the base passed it only to httpx, which accepts httpx.Timeout. Fix: reduce limit to a number before wait_for, for example by taking the largest phase of an httpx.Timeout or by validating the value up front with a ConfigError, so the httpx transport still gets the original value.

Why this was flagged

I could not list who sets the timeout. ClientConfig (types/models.py:491) is a plain dataclass with timeout: float = 30.0 and does no validation. HttpxAsyncTransport passes the value straight to httpx at _transports.py:143 and :182, and httpx accepts httpx.Timeout(10, connect=2). So a config that sets one works for every other AsyncClient operation (for example client.py:863 and :1089). After this change, _authenticate_and_send (client.py:1283-1295) calls asyncio.wait_for(run(), limit). On 3.12+ that evaluates timeout <= 0, and on 3.10/3.11 it adds the timeout to loop.time(). Both raise TypeError before any credential call or request, and leave run() un-awaited, which emits a RuntimeWarning. request_device_authorization and poll_device_token raise that bare TypeError. wait_for_device_token raises it too, not DevicePollError. The float annotation does not prevent this, because nothing checks it at runtime.

Verification: Trigger: a caller passes a value the public API does not declare, an httpx.Timeout object, as ClientConfig.timeout or as the per-call timeout. client.py:1294 calls await asyncio.wait_for(run(), limit). With an httpx.Timeout, wait_for raises TypeError. The except asyncio.TimeoutError at 1295 does not catch that TypeError. On the base, httpx accepts httpx.Timeout.

@github-actions

Copy link
Copy Markdown
Contributor

Release preview

keycardai-oauth 0.35.2 → 0.36.0 (minor)

  • fix(keycardai-oauth): the request timeout bounds the credential call too
  • request_device_authorization, poll_device_token, and each poll of
    wait_for_device_token run the credential's client authentication and
    the request under one asyncio.wait_for, so the timeout bounds the whole
    round trip, as Go does with one context.WithTimeout. httpx's timeout
    alone applies to each phase of the request, and the credential call had
    no bound. Running out of time raises NetworkError, so poll until done
    stops with DevicePollError and a doubled interval. An exception the
    credential raises propagates unchanged (unit row 27).
  • feat(keycardai-oauth): poll until done for the device grant (feat(keycardai-oauth): poll until done for the device grant #433)
    • feat(keycardai-oauth): poll until done for the device grant
  • Adds AsyncClient.wait_for_device_token, which polls until the person
    approves or denies the request, per RFC 8628 Section 3.5 and the spec's
    poll-until-done rules.
  • It waits the interval before each poll, including the first, through
    the client's clock. On authorization_pending it polls again, and on
    slow_down it adds 5 seconds to the interval for the next poll and every
    later one. When the next poll would start after expires_at, it raises
    an expired_token DeviceAuthorizationError without polling. It checks
    expires_at before and after each wait.
  • A network error, a 429, or a 5xx stops the loop with DevicePollError.
    Its interval is the wait the loop would have used next, doubled after
    a network error. Its cause is the original failure, including the
    DeviceAuthorizationError of a 429 or 5xx with an OAuth error body. To
    resume, call wait_for_device_token again with interval=error.interval.
    Any other failure returns as is, including a credential whose client
    authentication fails.
  • Task cancellation ends the wait or the request in flight. After it, the
    loop does not call the credential or send another request. The
    client's timeout applies to each poll, also under a longer caller
    deadline. An empty device_code, a non-positive authorization.interval,
    or an interval argument that is not an integer is a ConfigError.
  • examples/device_authorization runs the flow against a zone.
    • test(keycardai-oauth): slow_down increases accumulate across polls
  • Row 9 is a table. The new rows send two slow_down responses, in a row
    and with a pending between them, and expect the interval to rise by 5
    each time (RFC 8628 Section 3.5). A loop that resets to
    authorization.interval + 5 fails them.
    • refactor(keycardai-oauth): poll until done uses _is_transient_status
  • The loop stops with DevicePollError on the same 429 or 5xx rule that
    RefreshGrantError and DeviceAuthorizationError use for retryable.
    • fix(keycardai-oauth): the expiry error after the wait says the code expired
  • poll until done checks expires_at before and after each wait. The
    check before the wait says the code expires before the next poll. The
    check after the wait says it expired during the wait. Both raise
    expired_token.

  • feat(keycardai-oauth): device authorization request and single poll (feat(keycardai-oauth): device authorization request and single poll #432)
    • feat(keycardai-oauth): device authorization request and single poll
  • Adds the device side of the RFC 8628 device authorization grant on
    AsyncClient, per the Device Authorization Grant spec. The polling loop
    follows in the next change.
    • request_device_authorization returns a DeviceAuthorization, a
      pydantic model whose expires_at comes from the client's clock.
  • poll_device_token polls the token endpoint once.
  • Each takes exactly one of credential= (a ClientAuthenticator) or a
    public client_id=, and optional pre-discovered metadata=.
  • The endpoint an operation sends to must be an http or https URL. The
    token endpoint comes from metadata, the client's endpoint overrides,
    or discovery, never from a conventional path. When discovered
    metadata fails this check, the client discovers again after
    negative_ttl.
  • Only a 2xx is a success. DeviceAuthorizationError keeps the
    response's status_code. A 429 or 5xx is retryable whatever the code.
    Otherwise invalid_grant is not retryable and every other code
    follows OAuthProtocolError.
  • expired_token joins PERMANENT_ERROR_CODES, so every operation
    classifies an expired_token error as not retryable.
  • A body that does not decode is invalid_response on a 2xx and the HTTP
    error for the status otherwise. HttpxAsyncTransport reads the body
    itself and raises ResponseBodyDecodeError, a NetworkError with the
    status, so other operations see the same exception type.
  • AsyncClient(clock=) takes a Clock. SystemClock is the default.
  • AuthorizationServerMetadata has device_authorization_endpoint.
    • fix(keycardai-oauth): a missing token_endpoint is a ConfigError, and rediscovery keeps the cache
    • Discovered metadata without token_endpoint raises
      MissingTokenEndpointError on Client and AsyncClient. It subclasses
      both AuthorizationServerDiscoveryError and ConfigError, so device
      grant unit row 30 holds for discovered metadata as well as for
      metadata=. Existing except AuthorizationServerDiscoveryError blocks
      still catch it. ConfigError takes an optional cause.
  • When discovered metadata fails a device endpoint check and is older
    than negative_ttl, AsyncClient discovers again without emptying the
    cache first. A transient failure leaves the cached metadata for the
    client's other operations. A deterministic failure replaces it for
    negative_ttl, as before.
  • MetadataCache.invalidate is removed. Nothing calls it.
    • fix(keycardai-oauth): a 2xx device response is a success, and poll once checks device_code
    • A 2xx from the device authorization endpoint or the token endpoint is
      a success response, whatever its fields. One with an error field and
      without the required fields is invalid_response. Only a status other
      than 2xx gives a typed OAuth error. RFC 6749 Section 5.2 sends OAuth
      errors with 400, or 401 for invalid_client.
  • poll_device_token raises ConfigError for an empty
    authorization.device_code, before discovery or the credential call.
  • DeviceAuthorizationError and RefreshGrantError share one rule for a
    429 or 5xx.
    • fix(keycardai-oauth): DeviceAuthorization repr leaves out device_code
  • A public client redeems device_code with client_id alone (RFC 8628
    Section 3.4), so logging the value leaked a working credential.
    device_code now uses Field(repr=False). model_dump() and
    model_dump_json() still include it, so a persisted value can poll.
    • fix(keycardai-oauth): device requests use overrides and configured headers
    • A token endpoint override wins over metadata= as it does over
      discovered metadata. poll_device_token sent to the metadata's
      token_endpoint, or raised ConfigError when it had none.
  • Both device requests send config.user_agent and config.custom_headers,
    as every other operation does. The request's own headers, including
    client authentication, win over both.
  • check_endpoint raises ConfigError for an endpoint that is not a string
    or that urlsplit cannot parse, as spec row 30 requires. It raised
    ValueError, AttributeError, or TypeError, which also skipped the
    rediscovery after negative_ttl.

  • feat(keycardai-oauth): refresh with a credential (feat(keycardai-oauth): refresh with a credential #431)
    • feat(keycardai-oauth): refresh with a credential
  • Adds the credential option to the refresh step in Authorization Code
    with PKCE (spec-version 5). AsyncClient.refresh_token_grant and
    refresh_authorization take credential=. The credential's client
    authentication is called with the token endpoint, and its headers and
    form fields go on the request in place of the client's auth strategy
    and the body client_id.
  • credential together with client_id (or client_secret on
    refresh_authorization), or a credential without client authentication,
    raises ConfigError before any request. refresh_authorization's client_id
    is optional and required only without credential.
  • The sync Client does not take a credential, because credentials are
    async only.
    • fix(keycardai-oauth): refresh classifies by status first and never guesses the token endpoint
    • RefreshGrantError keeps the response's status_code. A 429 or 5xx is
      retryable whatever the code, as base.md Retryability requires.
      Otherwise invalid_grant is not retryable, and every other code
      follows OAuthProtocolError.
  • refresh_authorization with metadata whose token_endpoint is absent or
    empty raises ConfigError before any request. An empty value no longer
    falls through to a convention-derived endpoint. It raised ValueError
    for an absent value before.
  • The discovered-metadata check that discovery already enforces is
    removed, and the docstrings name the errors raised: discovery
    failures, and ConfigError for an unknown ClientSecret zone.
    • fix(keycardai-oauth): a token response classifies by status first
  • Authorization-code exchange and refresh now classify a token endpoint
    response the way the device grant does. A 2xx is a success and must
    have access_token, so a 2xx with an error member is invalid_response.
    Any other status is an error: the grant's OAuth error class when the
    body is an OAuth error (RFC 6749 Section 5.2), OAuthHttpError
    otherwise. A 3xx was parsed as a success before.

  • feat(keycardai-oauth): client authentication on credentials (feat(keycardai-oauth): client authentication on credentials #430)
    • feat(keycardai-oauth): client authentication on credentials
  • Adds the client-authentication operation from the base spec's
    Credential operations section. ClientSecret, WebIdentity, and
    WorkloadIdentity implement ClientAuthenticator:
    • client_authentication(issuer=, endpoint=) returns a
      ClientAuthentication with the headers and form fields that
      authenticate one request. It never includes a grant parameter.
  • ClientSecret returns the Basic header for the issuer's zone. A
    multi-zone credential raises KeyError for an unknown zone.
  • WebIdentity signs a new assertion per call, with aud set to the
    endpoint and iss and sub set to the new client_id option.
    audience_config does not apply. Without client_id it raises
    ConfigError.
  • WorkloadIdentity returns the source's token, and client_id when
    configured.
  • ClientAuthenticator is a runtime-checkable Protocol separate from
    ApplicationCredential, so credentials implemented outside the SDK keep
    working. require_client_authenticator raises ConfigError for a
    credential without it.
  • WebIdentity token exchange and set_client_config use the auth
    context's resource_client_id when present, and the client_id option
    otherwise.
    • fix(keycardai-oauth): ClientAuthentication repr leaves out its secrets
  • headers and form_fields hold a Basic header or a client assertion.
    repr() printed both, so a traceback that captures locals showed the
    client secret. Both fields now use field(repr=False).

  • fix(keycardai-oauth): percent-encode the client ID and secret in HTTP Basic (fix(keycardai-oauth): percent-encode the client ID and secret in HTTP Basic #429)
  • RFC 6749 Section 2.3.1 requires the client ID and secret to be encoded
    before they go into the HTTP Basic credential. BasicAuth.apply_headers
    encodes each one with urllib.parse.quote(value, safe=""). A space
    becomes %20, which form decoders and decodeURIComponent both read as a
    space.
  • Keycard zones percent-decode each half (svc-sts
    packages/w3/src/auth/basic.js), so a client ID with a colon or a secret
    with a percent sign now authenticates. A server that does not decode
    the Basic credential rejects a client ID or secret with a character
    outside A-Z a-z 0-9 - . _ ~.
  • Every Basic header in the SDK comes from BasicAuth, including
    MultiZoneBasicAuth, ClientSecret, and the PKCE helpers.
  • Follows typescript-sdk bump: keycardai-oauth → 0.32.0 #338 and go-sdk docs(mcp,mcp-fastmcp): add hello world server examples #59. ECO-486.

No other package releases.


This comment was automatically generated by the release preview workflow.

This branch has not been deployed

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

1 participant