Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions packages/oauth/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,9 +207,16 @@ async with AsyncClient("https://zone.keycard.cloud") as client:
resources=["https://api.example.com"],
)
print(auth.verification_uri_complete or auth.verification_uri, auth.user_code)
token = await client.poll_device_token(auth, credential=credential)
token = await client.wait_for_device_token(auth, credential=credential)
```

`wait_for_device_token` waits `interval` before each poll and adds 5 seconds
on `slow_down`. It stops with `DeviceAuthorizationError` on `access_denied`,
`expired_token`, or any other OAuth error, and raises `expired_token` without
polling when the code expires before the next poll. A network error, a 429, or
a 5xx stops it with `DevicePollError`. To resume, call it again with
`interval=error.interval`. Cancelling the task stops the loop.

`poll_device_token` polls once. Until the person answers, it raises
`DeviceAuthorizationError` with `authorization_pending` or `slow_down`.

Expand All @@ -220,7 +227,7 @@ Pass `client_id=` in place of `credential=` for a public client. Use the same
client authentication for every request in one flow. `WebIdentity` needs its
`client_id` option for this grant. `DeviceAuthorization` is a pydantic model,
so it can be persisted and polled from another process. The client's `clock`
sets `expires_at`.
sets `expires_at` and runs the waits between polls.

When the device authorization request names more than one resource, the token
is not for any one of them. To get a token for one resource, refresh with that
Expand Down Expand Up @@ -598,6 +605,7 @@ operation unchanged could succeed.
| `RefreshGrantError` | No | `invalid_grant`, or a code in `PERMANENT_ERROR_CODES` |
| `DeviceAuthorizationError` | Yes | HTTP 429 or 5xx, whatever the code |
| `DeviceAuthorizationError` | No | Not 429 or 5xx, and the code is `invalid_grant` or in `PERMANENT_ERROR_CODES` |
| `DevicePollError` | Yes | Always: a network error, a 429, or a 5xx stopped device polling |
| `OAuthProtocolError` / `TokenExchangeError` | Yes | Any other OAuth error code |
| `NetworkError` | Yes | Always: transport faults are transient, permanent failures surface as protocol or HTTP errors |
| `ConfigError` | No | Invalid configuration (requires code fix) |
Expand Down
31 changes: 31 additions & 0 deletions packages/oauth/examples/device_authorization/README.md
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
119 changes: 119 additions & 0 deletions packages/oauth/examples/device_authorization/main.py
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 packages/oauth/examples/device_authorization/pyproject.toml
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 }
2 changes: 2 additions & 0 deletions packages/oauth/src/keycardai/oauth/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
AuthorizationServerDiscoveryError,
ConfigError,
DeviceAuthorizationError,
DevicePollError,
InvalidTokenError,
JWKSError,
JWKSFetchError,
Expand Down Expand Up @@ -92,6 +93,7 @@
"OAuthProtocolError",
"RefreshGrantError",
"DeviceAuthorizationError",
"DevicePollError",
"NetworkError",
"ConfigError",
"AuthenticationError",
Expand Down
132 changes: 131 additions & 1 deletion packages/oauth/src/keycardai/oauth/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,12 @@
from .exceptions import (
AuthorizationServerDiscoveryError,
ConfigError,
DeviceAuthorizationError,
DevicePollError,
MissingTokenEndpointError,
NetworkError,
OAuthHttpError,
_is_transient_status,
)
from .http._context import build_http_context
from .http._transports import (
Expand All @@ -43,6 +48,7 @@
from .operations._device_authorization import (
DEVICE_AUTHORIZATION_OPERATION,
DEVICE_TOKEN_OPERATION,
SLOW_DOWN_INCREMENT,
build_device_authorization_http_request,
build_device_token_http_request,
check_endpoint,
Expand Down Expand Up @@ -366,7 +372,8 @@ def __init__(
config: Client configuration with timeouts, retries, etc.
clock: Gives the current time and waits. The device
authorization grant computes ``expires_at`` from
``clock.now()``. Defaults to SystemClock.
``clock.now()`` and waits between polls with
``clock.sleep()``. Defaults to SystemClock.
"""
self.issuer = _resolve_issuer_arg(issuer, base_url)
self.config = config or ClientConfig()
Expand Down Expand Up @@ -1373,6 +1380,129 @@ async def poll_device_token(
endpoint, authorization.device_code, client_auth, timeout
)

async def wait_for_device_token(
self,
authorization: DeviceAuthorization,
*,
credential: "ClientAuthenticator | ApplicationCredential | None" = None,
client_id: str | None = None,
interval: int | None = None,
metadata: AuthorizationServerMetadata | None = None,
timeout: float | None = None,
) -> TokenResponse:
"""Poll until the person approves or denies (RFC 8628 Section 3.5).

Waits the interval before each poll, including the first. On
``authorization_pending`` it polls again. On ``slow_down`` it adds 5
seconds to the interval for the next poll and every later one. Any other
OAuth error stops the loop. A network error, a 429, or a 5xx stops
the loop with DevicePollError. The loop never repeats a failed poll.

Waits go through the client's clock. Cancelling the task ends the
wait or the request in progress, and the loop does not call the
credential or send another request after it. ``timeout`` is the
httpx timeout of each poll (connect, read, write, and pool), also
when the caller sets a longer deadline on the whole loop. It does
not apply to the waits or the loop.

When the device authorization request named more than one resource,
the token is not for any one of them, even if ``raw["resource"]``
names one. NEVER store it as the token for a single resource. To get
a token for one resource, refresh with that resource.

Args:
authorization: The device authorization response, or one built
from persisted fields.
credential: As for request_device_authorization.
client_id: As for request_device_authorization.
interval: Seconds to wait before the first poll, and the
starting interval. Defaults to ``authorization.interval``.
To resume after DevicePollError, pass its ``interval``.
metadata: Pre-discovered authorization server metadata.
timeout: Timeout for each request. Defaults to the client's
timeout.

Returns:
The token, with ``refresh_token`` and ``id_token`` as received.

Raises:
ConfigError: As for poll_device_token, or
``authorization.device_code`` is empty, or
``authorization.interval`` is not positive, or ``interval``
is not an integer or is below it. No request is sent.
AuthorizationServerDiscoveryError: Discovery failed.
DeviceAuthorizationError: A terminal OAuth error such as
``access_denied``, ``invalid_grant``, or ``expired_token``,
or a malformed response (``invalid_response``).
``expired_token`` is also raised, without sending a poll,
when the next poll would start after ``expires_at``.
DevicePollError: A poll failed with a network error, a 429, or a
5xx, including a 429 or 5xx with an OAuth error body. Its
``interval`` is the interval to resume with.
OAuthHttpError: A 4xx other than 429 without an OAuth error body.
Exception: The credential's client authentication failed. Its
error propagates as is, without ``interval``.
asyncio.CancelledError: The task was cancelled.
"""
authenticator = _device_client_authenticator(credential, client_id)
if not authorization.device_code:
raise ConfigError("authorization.device_code is empty")
if authorization.interval < 1:
raise ConfigError(
f"authorization.interval {authorization.interval} is not positive"
)
if interval is None:
interval = authorization.interval
elif not isinstance(interval, int) or isinstance(interval, bool):
raise ConfigError(f"interval {interval!r} is not an integer")
elif interval < authorization.interval:
raise ConfigError(
f"interval {interval} is below the device authorization "
f"interval {authorization.interval}"
)
issuer, endpoint = await self._resolve_device_endpoint(
metadata, "token_endpoint"
)

def expired(description: str) -> DeviceAuthorizationError:
return DeviceAuthorizationError(
error="expired_token",
error_description=description,
operation=DEVICE_TOKEN_OPERATION,
)

while True:
remaining = (authorization.expires_at - self.clock.now()).total_seconds()
if interval > remaining:
raise expired("The device code expires before the next poll")
await self.clock.sleep(interval)
# asyncio delivers a cancellation only where the task suspends.
# This yield stops the loop here when the task was cancelled as
# the wait ended, before the credential or the transport runs.
await asyncio.sleep(0)
if self.clock.now() > authorization.expires_at:
raise expired("The device code expired during the wait before the next poll")

client_auth = await authenticator.client_authentication(
issuer=issuer, endpoint=endpoint
)
try:
return await self._poll_device_token_once(
endpoint, authorization.device_code, client_auth, timeout
)
except NetworkError as e:
raise DevicePollError(interval * 2, e) from e
except (DeviceAuthorizationError, OAuthHttpError) as e:
if _is_transient_status(e.status_code):
raise DevicePollError(interval, e) from e
if isinstance(e, DeviceAuthorizationError):
if e.error == "authorization_pending":
continue
Comment on lines +1496 to +1500

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.

if e.error == "slow_down":
interval += SLOW_DOWN_INCREMENT
continue
raise

async def impersonate(
self,
*,
Expand Down
Loading
Loading