Repository navigation
feat(keycardai-oauth): device authorization request and single poll - #432
Conversation
bbe2a7f to
c21c6a9
Compare
c21c6a9 to
50efaa8
Compare
Release previewkeycardai-oauth 0.35.2 → 0.36.0 (minor)
No other package releases. This comment was automatically generated by the release preview workflow. |
There was a problem hiding this comment.
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 rawValueError,AttributeErrororTypeErrorinstead of the documentedConfigErrorwhen an advertised endpoint is malformed or not a string.check_endpointonly catches empty values before callingurlsplit(url). That call raises for values like"https://[bad",123or a list. Discovery stores such values without type checks. Fix: insidecheck_endpoint, reject any non-strvalue and catchValueErrorfromurlsplit, raisingConfigErrorin 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(ortoken_endpoint) to a valueurlsplitcannot parse. Examples are an unclosed IPv6 bracket such as"https://[::1", or a non-string like a number or list.parse_discovery_http_responsecopies the field as is (_discovery.py:135). A caller-suppliedmetadata=can carry the same value.request_device_authorizationandpoll_device_tokencallcheck_endpoint(_device_authorization.py:827-829). It tests onlyif not urland then callsurlsplit(url), which raisesValueError("Invalid IPv6 URL") orAttributeError/TypeErrorfor non-str input. The caller therefore gets an uncaught builtin exception instead of theConfigErrorboth 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 fulldiscovery_ttl. The device grant is new code, so this path does not exist on the base branch.Verification:
check_endpointin packages/oauth/src/keycardai/oauth/operations/_device_authorization.py:38-40 only doesif not url: raise ConfigError(...)and then callsparts = urlsplit(url)with no type check and no try/except. client.py:1204 catches onlyexcept ConfigError:, so theValueErrorescapes before_resolve_metadata(refresh=True).
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>
50efaa8 to
d09d07d
Compare
There was a problem hiding this comment.
Still open from earlier reviews (1):
- 🔴
packages/oauth/src/keycardai/oauth/client.py:1198—Callers who set Endpoints(token=...) and pass metadata= to poll_device_token have the override ignored. The device code…
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>
Larry-Osakwe
left a comment
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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() |
There was a problem hiding this comment.
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() |
There was a problem hiding this comment.
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?
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_authorizationreturns aDeviceAuthorization, a pydantic model.expires_atcomes from the client's clock.poll_device_tokenpolls the token endpoint once.credential=or a publicclient_id=, and optional pre-discoveredmetadata=. The client's auth strategy is not used.AsyncClient(clock=)takes aClock.SystemClockis the default.AuthorizationServerMetadata.device_authorization_endpointis parsed from discovery.Endpoints come from
metadata=or discovery. AnEndpoints(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 thannegative_ttl(60 seconds), so the failure is not remembered for the fulldiscovery_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
credentialandclient_id, an emptyclient_id, a credential without client authentication, or aWebIdentitywithoutclient_idConfigError, before discoveryauthorization.device_codeonpoll_device_tokenConfigError, before discoveryConfigError, before the credential is calledtoken_endpointMissingTokenEndpointError, for every operation onClientandAsyncClient. It is aConfigErrorand anAuthorizationServerDiscoveryError.DeviceAuthorizationErrorwith the server's code andstatus_codeOAuthHttpErrorerrorfield), a wrong type, anintervalthat is not a positive integer, or a body that does not decodeDeviceAuthorizationErrorwith codeinvalid_responseOAuthHttpErrorfor the statusNetworkErrorRetryability
DeviceAuthorizationErrorkeeps the HTTP status, so a429or5xxis retryable whatever its code (base spec, Retryability, spec-version 7). Otherwiseinvalid_grantis not retryable, and every other code followsOAuthProtocolError. 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_tokenjoinsPERMANENT_ERROR_CODES. Every operation now classifies anexpired_tokenerror as not retryable.Bodies that do not decode
HttpxAsyncTransport.request_rawreads the body itself (build_request,send(stream=True),aread) so it knows the status when httpx raisesDecodingError. It raisesResponseBodyDecodeError, aNetworkErrorsubclass withstatusandheaders. 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.pyunless noted.test_row_1_credential_scopes_and_two_resourcestest_row_2_public_client_idtest_rows_3_and_23_client_authentication_misconfigured,test_row_3_checks_run_before_discoverytest_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_endpointtest_row_5_interval_defaults_and_expires_at_from_clocktest_rows_6_and_25_malformed_device_authorization_responsetest_row_7_poll_oncetest_row_22_web_identity_signs_a_new_assertion_per_requesttest_row_24_multi_resource_token_is_not_associated_with_a_resourcetest_error_responsestest_parse_discovery_http_response_types_device_authorization_endpointinoperations/test_discovery.pytest_exceptions.pychecks thatPERMANENT_ERROR_CODESand the typed classification agree on every protocol error code, and that the status decides first forDeviceAuthorizationError.http/test_transports.pychecks the decode error against real httpx.Stack
Replaces #427. Merge in order:
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, andjust validate-commitspass locally on each branch.🤖 Generated with Claude Code