Skip to content

feat(keycardai-oauth): poll until done for the device grant - #433

Merged
cmars merged 4 commits into
casey/eco-486-device-requestfrom
casey/eco-486-device-loop
Nov 17, 2026
Merged

cmars merged 4 commits into
casey/eco-486-device-requestfrom
casey/eco-486-device-loop

Conversation

@cmars

@cmars cmars commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Adds AsyncClient.wait_for_device_token, which polls until the person approves or denies the request, per RFC 8628 §3.5 and the spec's poll-until-done rules. Linear: ECO-486.

It waits the interval before each poll, including the first, through the client's clock. On authorization_pending it polls again. 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 before and after each wait, so a wait that runs long, as across a host suspend, does not send a poll after expires_at.

Errors

Failure Error
A network error or request timeout DevicePollError, interval doubled
A 429 or 5xx, with or without an OAuth error body, or with a body that does not decode DevicePollError, interval not doubled
Any other OAuth error, including access_denied, expired_token, invalid_grant, and invalid_response DeviceAuthorizationError, as is
A 4xx without an OAuth error body OAuthHttpError, as is
The credential's client authentication fails its error, as is
An empty device_code, an authorization.interval below 1, or an interval argument that is not an integer or is below authorization.interval ConfigError, before any request

DevicePollError.interval is the wait the loop would have used next, with every slow_down increase. Its cause is the original failure. retryable is always True. To resume, call wait_for_device_token again with interval=error.interval. examples/device_authorization shows how.

Task cancellation ends the wait or the request in flight. After it, the loop does not call the credential or send another request. asyncio delivers a cancellation only where a task suspends, so the loop awaits asyncio.sleep(0) after each wait. The client's timeout is the httpx timeout of each poll, also under a longer caller deadline such as asyncio.wait_for.

Example

examples/device_authorization runs the flow with a public client or a ClientSecret, resumes after DevicePollError up to three times, and refreshes the token for one resource when the request named more than one. I ran it against a local fake zone that answers pending, then 503, then a token. It resumed once and the refresh sent one resource.

Spec unit test rows covered

In tests/keycardai/oauth/test_device_authorization.py.

Rows Test
8 test_row_8_pending_twice_then_token
9 test_row_9_slow_down_adds_five_seconds_for_every_later_poll
10, 12 test_rows_10_and_12_terminal_oauth_error_stops_the_loop
11 test_row_11_clock_passes_expires_at_while_pending, test_row_11_expiry_boundary, test_row_11_expiry_is_checked_again_after_the_wait
13, 17, 26, 29, 32 test_rows_13_17_26_29_32_failure_stops_with_interval, test_row_13_network_error_then_5xx_on_a_second_call
14 test_row_14_cancelled_during_wait
15 test_row_15_persisted_authorization
16 test_row_16_slow_down_then_network_error
18 test_row_18_resume_with_the_reported_interval
19 test_row_19_interval_misconfigured, test_row_19_interval_equal_to_the_authorization_interval
20 test_row_20_cancelled_while_a_poll_is_in_flight
21 test_row_21_interval_longer_than_time_left
22 test_row_22_one_flow_with_poll_until_done
27 test_row_27_credential_failure_returns_as_is
28 test_row_28_request_timeout_holds_under_a_longer_caller_deadline (a local server that never answers)
31 test_row_31_other_failures_return_as_is
33 test_row_33_cancelled_when_the_wait_ends
3, 23, 30 the poll-until-done cases of the #432 tables

I broke each of these on purpose and checked that a test fails: the yield after the wait, the doubling, the status check, the expiry check before and after the wait, and the > and < boundaries.

Stack

Replaces #427. Merge in order:

  1. fix(keycardai-oauth): percent-encode the client ID and secret in HTTP Basic #429
  2. feat(keycardai-oauth): client authentication on credentials #430
  3. feat(keycardai-oauth): refresh with a credential #431
  4. feat(keycardai-oauth): device authorization request and single poll #432
  5. feat(keycardai-oauth): poll until done for the device grant #433 (this PR)

The PR workflow runs only on pull requests to main, so #430 to #433 show no CI until their base merges. just check, just typecheck, just test-coverage, just test-release-tooling, and just validate-commits pass locally on each branch.

🤖 Generated with Claude Code

@github-actions

github-actions Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Release preview

keycardai-oauth 0.35.2 → 0.36.0 (minor)

  • 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.
  • 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.
  • 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.
  • 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.
  • 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.
  • 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): 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): 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.
  • 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 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.
  • 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.
  • 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): 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).
  • 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): percent-encode the client ID and secret in HTTP Basic
  • 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.

@cmars
cmars force-pushed the casey/eco-486-device-loop branch from 7e8c8c3 to 99bc4fe Compare November 17, 2026 18:30
@cmars
cmars marked this pull request as ready for review November 17, 2026 18:45

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

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Comment on lines +1486 to +1490
if _is_transient_status(e.status_code):
raise DevicePollError(interval, e) from e
if isinstance(e, DeviceAuthorizationError):
if e.error == "authorization_pending":
continue

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) When a server answers slow_down with HTTP 429, callers who resume polling keep the old rate, breaking RFC 8628's MUST to add 5 seconds. The transient-status check at client.py:1487 runs before the slow_down branch. It raises DevicePollError(interval) without adding SLOW_DOWN_INCREMENT, so error.interval drops the server's request to slow down. Fix: when the error is a DeviceAuthorizationError with error == "slow_down", add SLOW_DOWN_INCREMENT before raising DevicePollError on a 429 or 5xx, while still raising DevicePollError for those statuses.

Why this was flagged

This needs a zone or a rate-limiting proxy in front of it that returns {"error":"slow_down"} with HTTP 429, a pairing this checkout cannot rule out. _json_object (operations/_device_authorization.py:152-161) turns that response into DeviceAuthorizationError(error="slow_down", status_code=429). In wait_for_device_token, _is_transient_status(e.status_code) at client.py:1487 is true, so the loop raises DevicePollError(interval, e) at client.py:1488. The interval += SLOW_DOWN_INCREMENT branch at client.py:1493 never runs. A caller that resumes with interval=error.interval, as the docstring, README and examples/device_authorization/main.py:58-59 all advise, polls at the same rate the server just asked it to slow. If the server keeps answering 429 slow_down, every resume returns the same interval until the caller gives up or the code expires. Nothing in the tests covers 429 with a slow_down body: row-17-429 at test_device_authorization.py:1102 sends a non-OAuth body.

Verification: Trigger: a zone, or a proxy in front of it, answers a poll with {"error":"slow_down"} on HTTP 429. In wait_for_device_token (client.py), _is_transient_status (exceptions.py:337-340) returns True for a 429, so the slow_down branch is never reached, and DevicePollError.interval lacks the +5. No test pins this case.

cmars and others added 3 commits November 17, 2026 12:52
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.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The loop stops with DevicePollError on the same 429 or 5xx rule that
RefreshGrantError and DeviceAuthorizationError use for retryable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@cmars
cmars force-pushed the casey/eco-486-device-loop branch from 99bc4fe to 259e817 Compare November 17, 2026 18:53

@Larry-Osakwe Larry-Osakwe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Loop order, slow_down, the doubling and cancellation all match the spec, and the tests ran green for me. The recheck after the wait is a good catch: Java and TS #343 don't do it, and the spec has no row for it yet. I'll take a spec row and the Java fix (SDK-119).

…xpired

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.

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.

Code review found no issues

No high-confidence issues detected in this change.

Still open from earlier reviews (1):

  • Unresolved: 1 minor or pre-existing.

@cmars
cmars merged commit a0cd63e into main Nov 17, 2026
16 checks passed
@cmars
cmars deleted the casey/eco-486-device-loop branch November 17, 2026 23:32
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