Skip to content

feat(keycardai-oauth): device authorization request and single poll - #432

Merged
cmars merged 5 commits into
casey/eco-486-refreshfrom
casey/eco-486-device-request
Nov 17, 2026
Merged

cmars merged 5 commits into
casey/eco-486-refreshfrom
casey/eco-486-device-request

Conversation

@cmars

@cmars cmars commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Adds the device side of the RFC 8628 device authorization grant to AsyncClient, per the Device Authorization Grant spec (spec-version 4). Linear: ECO-486. The polling loop is in #433.

  • request_device_authorization returns a DeviceAuthorization, a pydantic model. expires_at comes from the client's clock.
  • poll_device_token polls the token endpoint once.
  • Each takes exactly one of credential= or a public client_id=, and optional pre-discovered metadata=. The client's auth strategy is not used.
  • AsyncClient(clock=) takes a Clock. SystemClock is the default.
  • AuthorizationServerMetadata.device_authorization_endpoint is parsed from discovery.

Endpoints come from metadata= or discovery. An Endpoints(token=...) override applies to the token endpoint. No endpoint comes from a conventional path. The endpoint an operation sends to must be an http or https URL. When discovered metadata fails that check, the client discovers again once the metadata is older than negative_ttl (60 seconds), so the failure is not remembered for the full discovery_ttl (base spec, Metadata failures are not sticky). If that discovery fails with a transient error, the cached metadata stays for the client's other operations.

Errors

Failure Error
Not exactly one of credential and client_id, an empty client_id, a credential without client authentication, or a WebIdentity without client_id ConfigError, before discovery
An empty authorization.device_code on poll_device_token ConfigError, before discovery
The endpoint is missing or not an http or https URL ConfigError, before the credential is called
Discovered metadata without token_endpoint MissingTokenEndpointError, for every operation on Client and AsyncClient. It is a ConfigError and an AuthorizationServerDiscoveryError.
OAuth error body on a status that is not 2xx DeviceAuthorizationError with the server's code and status_code
Any other status that is not 2xx OAuthHttpError
Malformed 2xx: a missing field (including a 2xx with only an error field), a wrong type, an interval that is not a positive integer, or a body that does not decode DeviceAuthorizationError with code invalid_response
A non-2xx body that does not decode OAuthHttpError for the status
Network failure or timeout NetworkError

Retryability

DeviceAuthorizationError keeps the HTTP status, so a 429 or 5xx is retryable whatever its code (base spec, Retryability, spec-version 7). Otherwise invalid_grant is not retryable, and every other code follows OAuthProtocolError. The base spec records that Python's protocol errors drop the status (SDK-109). This PR fixes it for the device grant, and #431 for the refresh grant.

expired_token joins PERMANENT_ERROR_CODES. Every operation now classifies an expired_token error as not retryable.

Bodies that do not decode

HttpxAsyncTransport.request_raw reads the body itself (build_request, send(stream=True), aread) so it knows the status when httpx raises DecodingError. It raises ResponseBodyDecodeError, a NetworkError subclass with status and headers. Other operations see the same exception type as before. The sync transport is unchanged.

Spec unit test rows covered

In tests/keycardai/oauth/test_device_authorization.py unless noted.

Rows Test
1 test_row_1_credential_scopes_and_two_resources
2 test_row_2_public_client_id
3, 23 test_rows_3_and_23_client_authentication_misconfigured, test_row_3_checks_run_before_discovery
4, 30 test_rows_4_and_30_endpoint_missing_or_not_http, test_row_4_discovered_metadata_without_device_endpoint, test_row_4_failed_endpoint_check_is_remembered_for_negative_ttl, test_row_30_request_checks_only_the_endpoint_it_sends_to, test_row_30_discovered_metadata_without_token_endpoint
5 test_row_5_interval_defaults_and_expires_at_from_clock
6, 25 test_rows_6_and_25_malformed_device_authorization_response
7 test_row_7_poll_once
22 test_row_22_web_identity_signs_a_new_assertion_per_request
24 test_row_24_multi_resource_token_is_not_associated_with_a_resource
29, 31 (poll once) test_error_responses
Discovery 9, 10 test_parse_discovery_http_response_types_device_authorization_endpoint in operations/test_discovery.py

test_exceptions.py checks that PERMANENT_ERROR_CODES and the typed classification agree on every protocol error code, and that the status decides first for DeviceAuthorizationError. http/test_transports.py checks the decode error against real httpx.

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 (this PR)
  5. feat(keycardai-oauth): poll until done for the device grant #433

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): 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 marked this pull request as ready for review November 17, 2026 16:56

@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/operations/_device_authorization.py — Callers get a raw ValueError, AttributeError or TypeError instead of the documented ConfigError when an advertised endpoint is malformed or not a string. check_endpoint only catches empty values before calling urlsplit(url). That call raises for values like "https://[bad", 123 or a list. Discovery stores such values without type checks. Fix: inside check_endpoint, reject any non-str value and catch ValueError from urlsplit, raising ConfigError in both cases. That keeps the rediscovery fallback and the documented error contract.

    Why this was flagged

    An authorization server's discovery document sets device_authorization_endpoint (or token_endpoint) to a value urlsplit cannot parse. Examples are an unclosed IPv6 bracket such as "https://[::1", or a non-string like a number or list. parse_discovery_http_response copies the field as is (_discovery.py:135). A caller-supplied metadata= can carry the same value. request_device_authorization and poll_device_token call check_endpoint (_device_authorization.py:827-829). It tests only if not url and then calls urlsplit(url), which raises ValueError ("Invalid IPv6 URL") or AttributeError/TypeError for non-str input. The caller therefore gets an uncaught builtin exception instead of the ConfigError both methods' Raises sections promise. In _resolve_device_endpoint (client.py), except ConfigError: does not catch these, so the negative_ttl rediscovery never runs and the bad cached metadata stays for the full discovery_ttl. The device grant is new code, so this path does not exist on the base branch.

    Verification: check_endpoint in packages/oauth/src/keycardai/oauth/operations/_device_authorization.py:38-40 only does if not url: raise ConfigError(...) and then calls parts = urlsplit(url) with no type check and no try/except. client.py:1204 catches only except ConfigError:, so the ValueError escapes before _resolve_metadata(refresh=True).

cmars and others added 4 commits November 17, 2026 11:59
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.

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@cmars
cmars force-pushed the casey/eco-486-device-request branch from 50efaa8 to d09d07d Compare November 17, 2026 18:30

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

Still open from earlier reviews (1):

If you have decided not to act on one of these findings, resolve its thread (a reply alone leaves it open) and the next review stops counting it. To review this commit again now, use Re-run on its "Claude Code Review" check.

…aders

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

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.

No new blocking issues. 1 optional suggestion (a nit or a note on pre-existing code) was found and not posted.

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

Contract checks out against rows 1-7, 22-25 and 29-31. One real concern inline about the shared metadata cache, plus two small ones.

age = self._metadata_cache.success_age()
if age is None or age < self.config.negative_ttl:
raise
discovered = await self._resolve_metadata(refresh=True)

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.

If this forced rediscovery fails deterministically (a 404, or metadata now missing token_endpoint), store_failure drops the fresh cached metadata, so exchange_token on the same client fails for negative_ttl because of a device call. Base says a deterministic failure MAY be recorded, so could this path raise without recording it when a fresh success is cached? test_deterministic_rediscovery_failure_replaces_cached_metadata would flip to assert exchange_token still works.

request, timeout, DEVICE_AUTHORIZATION_OPERATION
)
return parse_device_authorization_http_response(
response, received_at=self.clock.now()

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.

A custom Clock that returns a naive datetime fails pydantic's AwareDatetime check here, after the server already issued the code. Checking tzinfo when the client is built, or raising ConfigError, would fail earlier and with our error type.

url = self._device_grant_endpoint(metadata, name)
return metadata.issuer, check_endpoint(metadata.issuer, name, url)

discovered = await self._resolve_metadata()

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.

With discovery off and no metadata=, this says the server doesn't advertise the endpoint, but nothing was discovered. Could it say to pass metadata= instead?

@cmars
cmars merged commit e4556f5 into main Nov 17, 2026
16 checks passed
@cmars
cmars deleted the casey/eco-486-device-request 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