Repository navigation
feat(keycardai-oauth): poll until done for the device grant #433
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
cmars
merged 4 commits into
casey/eco-486-device-request
from
casey/eco-486-device-loop
Nov 17, 2026
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
a243a18
feat(keycardai-oauth): poll until done for the device grant
cmars 11f10a3
test(keycardai-oauth): slow_down increases accumulate across polls
cmars 259e817
refactor(keycardai-oauth): poll until done uses _is_transient_status
cmars fe64f22
fix(keycardai-oauth): the expiry error after the wait says the code e…
cmars File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| # Device Authorization Grant Example | ||
|
|
||
| Runs the OAuth 2.0 device authorization grant (RFC 8628) from the device's | ||
| side. The example asks the zone for a user code, prints the verification URL | ||
| and the code, and polls until a person approves or denies the request in a | ||
| browser on another device. | ||
|
|
||
| ## Usage | ||
|
|
||
| ```bash | ||
| uv sync | ||
| KEYCARD_ZONE_URL=https://your-zone.keycard.cloud \ | ||
| KEYCARD_CLIENT_ID=your-client-id \ | ||
| uv run python main.py | ||
| ``` | ||
|
|
||
| The OAuth client needs the device code grant enabled. Set | ||
| `KEYCARD_CLIENT_SECRET` for a confidential client. Without it, the example | ||
| runs as a public client. `KEYCARD_SCOPES` and `KEYCARD_RESOURCES` take | ||
| space-separated lists. The docstring at the top of `main.py` lists what to | ||
| configure in Keycard. | ||
|
|
||
| After a network error, a 429, or a 5xx, the example resumes polling at the | ||
| interval from `DevicePollError`, at most three times. With more than one | ||
| resource, it refreshes the token for the first resource. | ||
|
|
||
| ## Requirements | ||
|
|
||
| - Python 3.10+ | ||
| - keycardai-oauth package | ||
| - A Keycard zone with an OAuth client that has the device code grant enabled |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| """Device authorization grant (RFC 8628) example. | ||
|
|
||
| A process with no browser asks the zone for a user code, prints it, and polls | ||
| until a person approves the request on another device. | ||
|
|
||
| Configure in Keycard before running: | ||
|
|
||
| - A zone (KEYCARD_ZONE_URL), for example https://your-zone.keycard.cloud. | ||
| - An OAuth client (KEYCARD_CLIENT_ID) with the device code grant enabled. For | ||
| a confidential client, also set KEYCARD_CLIENT_SECRET. Without it the | ||
| example runs as a public client and sends only client_id. | ||
| - Optional: KEYCARD_SCOPES, space-separated (default "openid"). With openid, | ||
| the zone adds its userinfo resource, so policy must allow it for this | ||
| client. | ||
| - Optional: KEYCARD_RESOURCES, space-separated resource URLs. Each must be a | ||
| Resource in the zone, or the request fails with invalid_target. With more | ||
| than one, the example refreshes the token for the first resource. | ||
|
|
||
| Run: | ||
|
|
||
| KEYCARD_ZONE_URL=... KEYCARD_CLIENT_ID=... uv run python main.py | ||
| """ | ||
|
|
||
| import asyncio | ||
| import os | ||
| import sys | ||
|
|
||
| from keycardai.oauth import ( | ||
| AsyncClient, | ||
| DeviceAuthorization, | ||
| DeviceAuthorizationError, | ||
| DevicePollError, | ||
| TokenResponse, | ||
| ) | ||
| from keycardai.oauth.pkce import refresh_authorization | ||
| from keycardai.oauth.server.credentials import ClientSecret | ||
|
|
||
| MAX_RESUMES = 3 | ||
|
|
||
|
|
||
| async def wait_for_token( | ||
| client: AsyncClient, auth: DeviceAuthorization, client_auth: dict | ||
| ) -> TokenResponse: | ||
| """Poll until the person approves or denies. | ||
|
|
||
| After a network error, a 429, or a 5xx, resume at the interval from the | ||
| error, at most MAX_RESUMES times. | ||
| """ | ||
| interval = None | ||
| for attempt in range(MAX_RESUMES + 1): | ||
| try: | ||
| return await client.wait_for_device_token( | ||
| auth, interval=interval, **client_auth | ||
| ) | ||
| except DevicePollError as e: | ||
| if attempt == MAX_RESUMES: | ||
| raise | ||
| print(f"Poll failed ({e.cause}); resuming in {e.interval}s.") | ||
| interval = e.interval | ||
| raise AssertionError("unreachable") | ||
|
|
||
|
|
||
| async def main() -> None: | ||
| zone_url = os.environ.get("KEYCARD_ZONE_URL") | ||
| client_id = os.environ.get("KEYCARD_CLIENT_ID") | ||
| if not zone_url or not client_id: | ||
| sys.exit("KEYCARD_ZONE_URL and KEYCARD_CLIENT_ID are required") | ||
| scopes = os.environ.get("KEYCARD_SCOPES", "openid").split() | ||
| resources = os.environ.get("KEYCARD_RESOURCES", "").split() | ||
|
|
||
| # Every request in the flow, and the refresh, authenticates the same way. | ||
| secret = os.environ.get("KEYCARD_CLIENT_SECRET") | ||
| if secret: | ||
| client_auth: dict = {"credential": ClientSecret((client_id, secret))} | ||
| else: | ||
| client_auth = {"client_id": client_id} | ||
|
|
||
| async with AsyncClient(zone_url) as client: | ||
| auth = await client.request_device_authorization( | ||
| scopes=scopes, resources=resources, **client_auth | ||
| ) | ||
| print("On another device, open:\n") | ||
| print(f" {auth.verification_uri_complete or auth.verification_uri}\n") | ||
| print("and confirm the code:\n") | ||
| print(f" {auth.user_code}\n") | ||
| expires_at = auth.expires_at.astimezone() | ||
| print(f"Waiting for approval (expires at {expires_at:%H:%M:%S %Z})...") | ||
|
|
||
| try: | ||
| token = await wait_for_token(client, auth, client_auth) | ||
| except DeviceAuthorizationError as e: | ||
| if e.error == "access_denied": | ||
| sys.exit("The request was denied.") | ||
| if e.error == "expired_token": | ||
| sys.exit("The code expired before anyone approved it. Run again.") | ||
| raise | ||
|
|
||
| print( | ||
| f"Approved. Token type {token.token_type}, expires in {token.expires_in}s, " | ||
| f"scopes {token.scope}." | ||
| ) | ||
| print(f"refresh_token returned: {token.refresh_token is not None}") | ||
| print(f"id_token returned: {token.id_token is not None}") | ||
|
|
||
| # With more than one resource, the token is not for any one of them. | ||
| # Refresh with one resource to get a token for it. | ||
| if len(resources) < 2 or token.refresh_token is None: | ||
| return | ||
| narrowed = await refresh_authorization( | ||
| issuer=zone_url, | ||
| refresh_token=token.refresh_token, | ||
| resources=resources[:1], | ||
| **client_auth, | ||
| ) | ||
| print(f"Token for {resources[0]}: expires in {narrowed.expires_in}s.") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| asyncio.run(main()) |
12 changes: 12 additions & 0 deletions
12
packages/oauth/examples/device_authorization/pyproject.toml
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| [project] | ||
| name = "device-authorization" | ||
| version = "0.1.0" | ||
| description = "Device authorization grant (RFC 8628) example" | ||
| readme = "README.md" | ||
| requires-python = ">=3.10" | ||
| dependencies = [ | ||
| "keycardai-oauth", | ||
| ] | ||
|
|
||
| [tool.uv.sources] | ||
| keycardai-oauth = { path = "../../", editable = true } |
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
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
Oops, something went wrong.
Oops, something went wrong.
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.
There was a problem hiding this comment.
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_downwith 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 theslow_downbranch. It raisesDevicePollError(interval)without addingSLOW_DOWN_INCREMENT, soerror.intervaldrops the server's request to slow down. Fix: when the error is a DeviceAuthorizationError witherror == "slow_down", addSLOW_DOWN_INCREMENTbefore 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). Inwait_for_device_token,_is_transient_status(e.status_code)at client.py:1487 is true, so the loop raisesDevicePollError(interval, e)at client.py:1488. Theinterval += SLOW_DOWN_INCREMENTbranch at client.py:1493 never runs. A caller that resumes withinterval=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 aslow_downbody: 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. Inwait_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, andDevicePollError.intervallacks the +5. No test pins this case.