diff --git a/packages/oauth/README.md b/packages/oauth/README.md index 40c48c18..1d351e8a 100644 --- a/packages/oauth/README.md +++ b/packages/oauth/README.md @@ -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`. @@ -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 @@ -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) | diff --git a/packages/oauth/examples/device_authorization/README.md b/packages/oauth/examples/device_authorization/README.md new file mode 100644 index 00000000..10d6d00a --- /dev/null +++ b/packages/oauth/examples/device_authorization/README.md @@ -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 diff --git a/packages/oauth/examples/device_authorization/main.py b/packages/oauth/examples/device_authorization/main.py new file mode 100644 index 00000000..1be1f82f --- /dev/null +++ b/packages/oauth/examples/device_authorization/main.py @@ -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()) diff --git a/packages/oauth/examples/device_authorization/pyproject.toml b/packages/oauth/examples/device_authorization/pyproject.toml new file mode 100644 index 00000000..2bafb153 --- /dev/null +++ b/packages/oauth/examples/device_authorization/pyproject.toml @@ -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 } diff --git a/packages/oauth/src/keycardai/oauth/__init__.py b/packages/oauth/src/keycardai/oauth/__init__.py index d5fad893..4dc32f33 100644 --- a/packages/oauth/src/keycardai/oauth/__init__.py +++ b/packages/oauth/src/keycardai/oauth/__init__.py @@ -42,6 +42,7 @@ AuthorizationServerDiscoveryError, ConfigError, DeviceAuthorizationError, + DevicePollError, InvalidTokenError, JWKSError, JWKSFetchError, @@ -92,6 +93,7 @@ "OAuthProtocolError", "RefreshGrantError", "DeviceAuthorizationError", + "DevicePollError", "NetworkError", "ConfigError", "AuthenticationError", diff --git a/packages/oauth/src/keycardai/oauth/client.py b/packages/oauth/src/keycardai/oauth/client.py index 421155dc..d301f507 100644 --- a/packages/oauth/src/keycardai/oauth/client.py +++ b/packages/oauth/src/keycardai/oauth/client.py @@ -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 ( @@ -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, @@ -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() @@ -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 + if e.error == "slow_down": + interval += SLOW_DOWN_INCREMENT + continue + raise + async def impersonate( self, *, diff --git a/packages/oauth/src/keycardai/oauth/exceptions.py b/packages/oauth/src/keycardai/oauth/exceptions.py index ff1266f7..8edf6bd4 100644 --- a/packages/oauth/src/keycardai/oauth/exceptions.py +++ b/packages/oauth/src/keycardai/oauth/exceptions.py @@ -406,6 +406,32 @@ def retryable(self) -> bool: return super().retryable +class DevicePollError(OAuthError): + """Device token polling stopped on a network error, a 429, or a 5xx. + + ``interval`` is the wait in seconds to resume with: the interval the + loop would have waited before its next poll, with every ``slow_down`` + increase. After a network error it is doubled (RFC 8628 Section 3.5). + To resume, call ``wait_for_device_token`` again with the same + DeviceAuthorization and ``interval=interval``, until its ``expires_at``. + + ``cause`` and ``__cause__`` are the original failure: a NetworkError, an + OAuthHttpError, or the DeviceAuthorizationError of a 429 or 5xx with an + OAuth error body. ``retryable`` is always True. + """ + + def __init__(self, interval: int, cause: OAuthError): + super().__init__( + f"Device token polling stopped, resume with interval {interval}s: {cause}", + cause, + ) + self.interval = interval + + @property + def retryable(self) -> bool: + return True + + class JWKSError(OAuthError): """Base class for JWKS key-resolution failures (fetch and key lookup). diff --git a/packages/oauth/src/keycardai/oauth/operations/_device_authorization.py b/packages/oauth/src/keycardai/oauth/operations/_device_authorization.py index ba1825a9..9e922883 100644 --- a/packages/oauth/src/keycardai/oauth/operations/_device_authorization.py +++ b/packages/oauth/src/keycardai/oauth/operations/_device_authorization.py @@ -25,6 +25,7 @@ DEVICE_AUTHORIZATION_OPERATION = "POST /device_authorization" DEVICE_TOKEN_OPERATION = "POST /token (device_code)" DEFAULT_POLL_INTERVAL = 5 +SLOW_DOWN_INCREMENT = 5 _REQUIRED_STRINGS = ("device_code", "user_code", "verification_uri") diff --git a/packages/oauth/tests/keycardai/oauth/test_device_authorization.py b/packages/oauth/tests/keycardai/oauth/test_device_authorization.py index b5473543..78af840a 100644 --- a/packages/oauth/tests/keycardai/oauth/test_device_authorization.py +++ b/packages/oauth/tests/keycardai/oauth/test_device_authorization.py @@ -1,9 +1,9 @@ """Device authorization grant (RFC 8628) on AsyncClient. Test names start with the row of the unit test table in the Keycard SDK spec -(specs/oauth-client/device-authorization.md). Every test runs against a fake -transport and a fake clock, so no test sends a real request or waits in real -time. The fake clock records each wait and advances its time by it. +(specs/oauth-client/device-authorization.md). The tests run against a fake +transport and a fake clock. The fake clock records each wait and advances its +time by it. Row 28 alone uses a real local server and httpx. """ import asyncio @@ -26,14 +26,17 @@ ConfigError, DeviceAuthorization, DeviceAuthorizationError, + DevicePollError, Endpoints, MissingTokenEndpointError, + NetworkError, OAuthHttpError, TokenResponse, ) from keycardai.oauth.http._transports import ResponseBodyDecodeError from keycardai.oauth.http._wire import HttpRequest, HttpResponse from keycardai.oauth.server.credentials import WebIdentity +from keycardai.oauth.server.exceptions import WorkloadIdentityRuntimeError ISSUER = "https://zone.example.com" DISCOVERY_URL = f"{ISSUER}/.well-known/oauth-authorization-server" @@ -199,15 +202,23 @@ def poll_once_op(client: AsyncClient, metadata=METADATA, **auth): return client.poll_device_token(authorization(), metadata=metadata, **auth) +def poll_until_done_op(client: AsyncClient, metadata=METADATA, **auth): + return client.wait_for_device_token(authorization(), metadata=metadata, **auth) + + OPERATION_NAMES = { request_op: "POST /device_authorization", poll_once_op: "POST /token (device_code)", } -OPERATIONS = [ +SINGLE_REQUEST_OPERATIONS = [ pytest.param(request_op, id="request"), pytest.param(poll_once_op, id="poll-once"), ] +OPERATIONS = [ + *SINGLE_REQUEST_OPERATIONS, + pytest.param(poll_until_done_op, id="poll-until-done"), +] FORM_HEADERS = { @@ -278,11 +289,13 @@ async def test_row_2_public_client_id(): @pytest.mark.parametrize("operation", OPERATIONS) async def test_rows_3_and_23_client_authentication_misconfigured(operation, auth, message): transport = FakeTransport() + clock = FakeClock() with pytest.raises(ConfigError, match=exactly(message)): - await operation(make_client(transport), **auth) + await operation(make_client(transport, clock), **auth) assert transport.requests == [] + assert clock.sleeps == [] @pytest.mark.parametrize("operation", OPERATIONS) @@ -316,6 +329,22 @@ def metadata(**endpoints) -> AuthorizationServerMetadata: f"Authorization server {ISSUER} does not advertise a token_endpoint", id="row-30-no-token-endpoint", ), + pytest.param( + poll_until_done_op, + metadata(device_authorization_endpoint=DEVICE_ENDPOINT), + f"Authorization server {ISSUER} does not advertise a token_endpoint", + id="row-30-no-token-endpoint-poll-until-done", + ), + pytest.param( + poll_until_done_op, + metadata( + token_endpoint="file:///etc/token", + device_authorization_endpoint=DEVICE_ENDPOINT, + ), + f"Authorization server {ISSUER} has a token_endpoint that is not an " + "http or https URL: 'file:///etc/token'", + id="row-30-token-endpoint-not-http-poll-until-done", + ), pytest.param( request_op, metadata( @@ -363,13 +392,15 @@ def metadata(**endpoints) -> AuthorizationServerMetadata: ) async def test_rows_4_and_30_endpoint_missing_or_not_http(operation, bad_metadata, message): transport = FakeTransport() + clock = FakeClock() credential = FakeCredential() with pytest.raises(ConfigError, match=exactly(message)): - await operation(make_client(transport), bad_metadata, credential=credential) + await operation(make_client(transport, clock), bad_metadata, credential=credential) assert transport.requests == [] assert credential.calls == [] + assert clock.sleeps == [] async def test_row_30_request_checks_only_the_endpoint_it_sends_to(): @@ -845,7 +876,7 @@ async def test_poll_once_rejects_an_empty_device_code(): @pytest.mark.parametrize( ("response", "error_type", "status", "code", "retryable"), ERROR_RESPONSES ) -@pytest.mark.parametrize("operation", OPERATIONS) +@pytest.mark.parametrize("operation", SINGLE_REQUEST_OPERATIONS) async def test_error_responses(operation, response, error_type, status, code, retryable): transport = FakeTransport(response) @@ -934,7 +965,11 @@ async def test_poll_once_malformed_token_response(body): @pytest.mark.parametrize("operation", OPERATIONS) async def test_timeout_argument_bounds_the_request(operation): - responses = {request_op: device_response(), poll_once_op: respond(200, TOKEN_BODY)} + responses = { + request_op: device_response(), + poll_once_op: respond(200, TOKEN_BODY), + poll_until_done_op: respond(200, TOKEN_BODY), + } transport = FakeTransport(responses[operation]) await operation(make_client(transport), client_id="public-app", timeout=2.5) @@ -982,3 +1017,535 @@ async def test_row_24_multi_resource_token_is_not_associated_with_a_resource(): assert "resource" not in {f.name for f in dataclasses.fields(TokenResponse)} assert "resources" not in DeviceAuthorization.model_fields assert token.raw == body + + +# Poll until done + + +def wait(client: AsyncClient, auth: DeviceAuthorization | None = None, **kwargs): + kwargs.setdefault("client_id", "public-app") + kwargs.setdefault("metadata", METADATA) + return client.wait_for_device_token(auth or authorization(), **kwargs) + + +async def test_row_8_pending_twice_then_token(): + transport = FakeTransport( + respond(400, PENDING), respond(400, PENDING), respond(200, TOKEN_BODY) + ) + clock = FakeClock() + + token = await wait(make_client(transport, clock)) + + assert len(transport.requests) == 3 + assert all(form(r) == { + "grant_type": [DEVICE_GRANT], + "device_code": ["dc"], + "client_id": ["public-app"], + } for r in transport.requests) + assert transport.timeouts == [7.0, 7.0, 7.0] + assert clock.sleeps == [5, 5, 5] + assert (token.access_token, token.refresh_token, token.id_token) == ( + "at", + "rt", + "header.claims.sig", + ) + + +# Each slow_down adds 5 seconds to the interval in force, so the increases +# accumulate (RFC 8628 Section 3.5). +@pytest.mark.parametrize( + ("responses", "sleeps"), + [ + pytest.param([SLOW_DOWN, PENDING], [5, 10, 10], id="row-9-slow_down-then-pending"), + pytest.param([SLOW_DOWN, SLOW_DOWN], [5, 10, 15], id="two-slow_down-in-a-row"), + pytest.param( + [SLOW_DOWN, PENDING, SLOW_DOWN, PENDING], + [5, 10, 10, 15, 15], + id="slow_down-after-pending", + ), + ], +) +async def test_row_9_slow_down_adds_five_seconds_for_every_later_poll(responses, sleeps): + transport = FakeTransport( + *[respond(400, body) for body in responses], respond(200, TOKEN_BODY) + ) + clock = FakeClock() + + await wait(make_client(transport, clock)) + + assert clock.sleeps == sleeps + assert len(transport.requests) == len(sleeps) + + +@pytest.mark.parametrize( + ("expires_in", "polls"), + [ + pytest.param(10, 2, id="row-11-poll-at-expires_at-is-sent"), + pytest.param(9, 1, id="row-11-poll-after-expires_at-is-not-sent"), + ], +) +async def test_row_11_expiry_boundary(expires_in, polls): + transport = FakeTransport(*[respond(400, PENDING)] * polls) + clock = FakeClock() + + with pytest.raises(DeviceAuthorizationError) as exc: + await wait(make_client(transport, clock), authorization(expires_in=expires_in)) + + assert exc.value.error == "expired_token" + assert len(transport.requests) == polls + assert clock.sleeps == [5] * polls + + +class SuspendingClock(FakeClock): + """A wait that takes longer than asked, as across a host suspend.""" + + async def sleep(self, seconds: float) -> None: + await super().sleep(seconds) + self.current += timedelta(seconds=600) + + +async def test_row_11_expiry_is_checked_again_after_the_wait(): + transport = FakeTransport() + clock = SuspendingClock() + + with pytest.raises(DeviceAuthorizationError) as exc: + await wait(make_client(transport, clock)) + + assert exc.value.error == "expired_token" + assert exc.value.error_description == ( + "The device code expired during the wait before the next poll" + ) + assert clock.sleeps == [5] + assert transport.requests == [] + + +@pytest.mark.parametrize( + "code", + [ + pytest.param("access_denied", id="row-10-access_denied"), + pytest.param("expired_token", id="row-12-expired_token"), + pytest.param("invalid_grant", id="row-12-invalid_grant"), + pytest.param("invalid_client", id="invalid_client"), + ], +) +async def test_rows_10_and_12_terminal_oauth_error_stops_the_loop(code): + transport = FakeTransport(respond(400, PENDING), respond(400, {"error": code})) + + with pytest.raises(DeviceAuthorizationError) as exc: + await wait(make_client(transport)) + + assert type(exc.value) is DeviceAuthorizationError + assert (exc.value.error, exc.value.status_code) == (code, 400) + assert exc.value.retryable is False + assert len(transport.requests) == 2 + + +async def test_row_11_clock_passes_expires_at_while_pending(): + transport = FakeTransport(respond(400, PENDING), respond(400, PENDING)) + clock = FakeClock() + + with pytest.raises(DeviceAuthorizationError) as exc: + await wait(make_client(transport, clock), authorization(expires_in=12)) + + assert exc.value.error == "expired_token" + assert exc.value.error_description == "The device code expires before the next poll" + assert exc.value.retryable is False + assert len(transport.requests) == 2 + assert clock.sleeps == [5, 5] + + +def network_failure() -> NetworkError: + return NetworkError( + cause=httpx.ConnectTimeout("timed out"), operation="POST", retriable=False + ) + + +@pytest.mark.parametrize( + ("failure", "cause_type", "status", "interval"), + [ + pytest.param(network_failure(), NetworkError, None, 10, id="row-13-network"), + pytest.param(respond(503, b"unavailable"), OAuthHttpError, 503, 5, id="row-13-5xx"), + pytest.param(respond(429, b"slow"), OAuthHttpError, 429, 5, id="row-17-429"), + pytest.param( + respond(503, {"error": "temporarily_unavailable"}), + DeviceAuthorizationError, + 503, + 5, + id="row-26-503-with-oauth-body", + ), + pytest.param( + respond(503, {"error": "access_denied"}), + DeviceAuthorizationError, + 503, + 5, + id="row-29-503-with-permanent-code", + ), + pytest.param( + respond(429, {"error": "invalid_grant"}), + DeviceAuthorizationError, + 429, + 5, + id="429-with-invalid_grant", + ), + pytest.param(undecodable(503), OAuthHttpError, 503, 5, id="row-32-503-not-gzip"), + ], +) +async def test_rows_13_17_26_29_32_failure_stops_with_interval( + failure, cause_type, status, interval +): + transport = FakeTransport(respond(400, PENDING), failure) + clock = FakeClock() + + with pytest.raises(DevicePollError) as exc: + await wait(make_client(transport, clock)) + + assert len(transport.requests) == 2 + assert clock.sleeps == [5, 5] + assert exc.value.retryable is True + assert exc.value.interval == interval + cause = exc.value.__cause__ + assert type(cause) is cause_type + assert exc.value.cause is cause + assert cause.retryable is True + assert getattr(cause, "status_code", None) == status + if isinstance(failure, NetworkError) and not isinstance(failure, ResponseBodyDecodeError): + assert cause is failure + if isinstance(cause, DeviceAuthorizationError): + assert cause.error == json.loads(failure.body)["error"] + + +async def test_slow_down_then_5xx_reports_the_raised_interval_not_doubled(): + transport = FakeTransport(respond(400, SLOW_DOWN), respond(503, b"unavailable")) + + with pytest.raises(DevicePollError) as exc: + await wait(make_client(transport)) + + assert exc.value.interval == 5 + 5 + + +async def test_row_13_network_error_then_5xx_on_a_second_call(): + transport = FakeTransport(network_failure(), respond(503, b"unavailable")) + client = make_client(transport) + + with pytest.raises(DevicePollError) as first: + await wait(client) + with pytest.raises(DevicePollError) as second: + await wait(client) + + assert (first.value.interval, second.value.interval) == (10, 5) + assert isinstance(first.value.cause, NetworkError) + assert isinstance(second.value.cause, OAuthHttpError) + assert len(transport.requests) == 2 + + +@pytest.mark.parametrize( + ("response", "error_type", "status", "code"), + [ + pytest.param( + respond(404, b"not found"), OAuthHttpError, 404, None, id="4xx-without-oauth-body" + ), + pytest.param( + undecodable(200), + DeviceAuthorizationError, + 200, + "invalid_response", + id="row-31-200-not-gzip", + ), + pytest.param( + respond(200, b""), + DeviceAuthorizationError, + 200, + "invalid_response", + id="200-not-json", + ), + ], +) +async def test_row_31_other_failures_return_as_is(response, error_type, status, code): + transport = FakeTransport(response) + + with pytest.raises(error_type) as exc: + await wait(make_client(transport)) + + assert type(exc.value) is error_type + assert exc.value.status_code == status + assert getattr(exc.value, "error", None) == code + assert len(transport.requests) == 1 + + +async def test_row_14_cancelled_during_wait(): + block = asyncio.Event() + transport = FakeTransport(respond(200, TOKEN_BODY)) + clock = FakeClock(block=block) + task = asyncio.create_task(wait(make_client(transport, clock))) + while not clock.sleeps: + await asyncio.sleep(0) + + task.cancel() + block.set() + + with pytest.raises(asyncio.CancelledError): + await task + assert transport.requests == [] + + +async def test_row_15_persisted_authorization(): + original = authorization() + original.device_code = "persisted-device-code" + restored = DeviceAuthorization.model_validate_json(original.model_dump_json()) + transport = FakeTransport(respond(200, TOKEN_BODY)) + + await wait(make_client(transport), restored) + + assert restored == original + assert form(transport.requests[0])["device_code"] == ["persisted-device-code"] + + +async def test_row_16_slow_down_then_network_error(): + failure = network_failure() + transport = FakeTransport(respond(400, SLOW_DOWN), failure) + + with pytest.raises(DevicePollError) as exc: + await wait(make_client(transport)) + + assert exc.value.retryable is True + assert exc.value.interval == 2 * (5 + 5) + assert exc.value.__cause__ is failure + + +async def test_row_18_resume_with_the_reported_interval(): + transport = FakeTransport(respond(400, SLOW_DOWN), network_failure()) + clock = FakeClock() + client = make_client(transport, clock) + with pytest.raises(DevicePollError) as exc: + await wait(client) + transport.responses.append(respond(200, TOKEN_BODY)) + clock.sleeps.clear() + + await wait(client, interval=exc.value.interval) + + assert clock.sleeps == [20] + + +@pytest.mark.parametrize( + ("auth", "interval", "message"), + [ + pytest.param( + authorization(), + 3, + "interval 3 is below the device authorization interval 5", + id="row-19", + ), + pytest.param(authorization(), 7.5, "interval 7.5 is not an integer", id="float"), + pytest.param(authorization(), "10", "interval '10' is not an integer", id="string"), + pytest.param( + authorization(interval=0), + None, + "authorization.interval 0 is not positive", + id="persisted-interval-zero", + ), + pytest.param( + authorization(interval=-5), + None, + "authorization.interval -5 is not positive", + id="persisted-interval-negative", + ), + ], +) +async def test_row_19_interval_misconfigured(auth, interval, message): + transport = FakeTransport() + clock = FakeClock() + + with pytest.raises(ConfigError, match=exactly(message)): + await wait(make_client(transport, clock), auth, interval=interval) + + assert transport.requests == [] + assert clock.sleeps == [] + + +async def test_row_19_interval_equal_to_the_authorization_interval(): + transport = FakeTransport(respond(200, TOKEN_BODY)) + clock = FakeClock() + + await wait(make_client(transport, clock), interval=5) + + assert clock.sleeps == [5] + + +async def test_empty_device_code_is_a_config_error(): + transport = FakeTransport() + auth = authorization() + auth.device_code = "" + + with pytest.raises(ConfigError, match=exactly("authorization.device_code is empty")): + await wait(make_client(transport), auth) + + assert transport.requests == [] + + +async def test_row_20_cancelled_while_a_poll_is_in_flight(): + block = asyncio.Event() + transport = FakeTransport(respond(400, PENDING), respond(200, TOKEN_BODY), block=block) + credential = FakeCredential() + task = asyncio.create_task( + wait(make_client(transport), client_id=None, credential=credential) + ) + while not transport.requests: + await asyncio.sleep(0) + + task.cancel() + block.set() + + with pytest.raises(asyncio.CancelledError): + await task + assert len(transport.requests) == 1 + assert len(credential.calls) == 1 + + +async def test_row_21_interval_longer_than_time_left(): + transport = FakeTransport() + clock = FakeClock() + + with pytest.raises(DeviceAuthorizationError) as exc: + await wait(make_client(transport, clock), authorization(expires_in=10), interval=15) + + assert type(exc.value) is DeviceAuthorizationError + assert (exc.value.error, exc.value.status_code) == ("expired_token", None) + assert exc.value.error_description == "The device code expires before the next poll" + assert exc.value.retryable is False + assert transport.requests == [] + assert clock.sleeps == [] + + +async def test_row_22_one_flow_with_poll_until_done(tmp_path): + credential = WebIdentity( + server_name="device", storage_dir=str(tmp_path), client_id="registered-client" + ) + transport = FakeTransport( + device_response(), respond(400, PENDING), respond(200, TOKEN_BODY) + ) + client = make_client(transport) + + auth = await client.request_device_authorization( + credential=credential, metadata=METADATA + ) + await client.wait_for_device_token(auth, credential=credential, metadata=METADATA) + + claims = [jwt_claims(form(r)["client_assertion"][0]) for r in transport.requests] + assert [c["aud"] for c in claims] == [DEVICE_ENDPOINT, TOKEN_ENDPOINT, TOKEN_ENDPOINT] + assert len({c["jti"] for c in claims}) == 3 + + +class FailingCredential(FakeCredential): + """Authenticates the first poll, then raises ``error`` on the next one.""" + + def __init__(self, error: Exception): + super().__init__() + self.error = error + + async def client_authentication( + self, *, issuer: str, endpoint: str + ) -> ClientAuthentication: + if self.calls: + raise self.error + return await super().client_authentication(issuer=issuer, endpoint=endpoint) + + +@pytest.mark.parametrize( + "error", + [ + pytest.param( + WorkloadIdentityRuntimeError("token source failed", source="custom"), + id="row-27-source-error", + ), + pytest.param(ConfigError("no zone"), id="row-27-config-error"), + pytest.param( + NetworkError(cause=httpx.ConnectError("refused"), retriable=False), + id="row-27-network-error-from-the-credential", + ), + ], +) +async def test_row_27_credential_failure_returns_as_is(error): + transport = FakeTransport(respond(400, PENDING)) + credential = FailingCredential(error) + + with pytest.raises(type(error)) as exc: + await wait(make_client(transport), client_id=None, credential=credential) + + assert exc.value is error + assert len(transport.requests) == 1 + + +@pytest.mark.parametrize( + ("deadline", "expected"), + [ + pytest.param(30.0, DevicePollError, id="row-28-longer-deadline"), + # A caller deadline shorter than the request timeout ends the loop + # with the caller's own TimeoutError, not a DevicePollError. + pytest.param(0.05, asyncio.TimeoutError, id="shorter-deadline"), + ], +) +async def test_row_28_request_timeout_holds_under_a_longer_caller_deadline(deadline, expected): + # A local server that accepts each connection and never answers. The + # client's real httpx transport has a 0.2 second request timeout, so the + # poll ends at 0.2 seconds whatever the caller's deadline. + writers: list[asyncio.StreamWriter] = [] + + async def never_respond(reader, writer): + writers.append(writer) + await reader.read(65536) + + server = await asyncio.start_server(never_respond, "127.0.0.1", 0) + port = server.sockets[0].getsockname()[1] + token_endpoint = f"http://127.0.0.1:{port}/oauth/token" + client = AsyncClient( + ISSUER, + clock=FakeClock(), + config=ClientConfig( + enable_metadata_discovery=False, auto_register_client=False, timeout=0.2 + ), + ) + + try: + with pytest.raises(expected) as exc: + await asyncio.wait_for( + wait(client, metadata=metadata(token_endpoint=token_endpoint)), deadline + ) + finally: + await client.aclose() + for writer in writers: + writer.close() + server.close() + await server.wait_closed() + + if expected is DevicePollError: + assert exc.value.interval == 2 * 5 + assert exc.value.retryable is True + assert type(exc.value.__cause__) is NetworkError + assert isinstance(exc.value.__cause__.cause, httpx.ReadTimeout) + + +class CancelAtWaitEnd(FakeClock): + """Cancels the polling task as the wait ends, then returns normally.""" + + async def sleep(self, seconds: float) -> None: + await super().sleep(seconds) + task = asyncio.current_task() + assert task is not None + task.cancel() + + +async def test_row_33_cancelled_when_the_wait_ends(): + transport = FakeTransport(respond(200, TOKEN_BODY)) + clock = CancelAtWaitEnd() + credential = FakeCredential() + + task = asyncio.create_task( + wait(make_client(transport, clock), client_id=None, credential=credential) + ) + + with pytest.raises(asyncio.CancelledError): + await task + + assert clock.sleeps == [5] + assert credential.calls == [] + assert transport.requests == [] diff --git a/packages/oauth/tests/keycardai/oauth/test_exceptions.py b/packages/oauth/tests/keycardai/oauth/test_exceptions.py index 5259d0a1..6e95d2ff 100644 --- a/packages/oauth/tests/keycardai/oauth/test_exceptions.py +++ b/packages/oauth/tests/keycardai/oauth/test_exceptions.py @@ -9,6 +9,7 @@ AuthorizationDeniedError, ConfigError, DeviceAuthorizationError, + DevicePollError, NetworkError, OAuthError, OAuthHttpError, @@ -283,6 +284,30 @@ def test_grant_errors_add_only_invalid_grant(self, error_cls, code): expected = code != "invalid_grant" and code not in PERMANENT_ERROR_CODES assert error.retryable is expected + @pytest.mark.parametrize( + "cause", + [ + pytest.param( + NetworkError(cause=httpx.ConnectError("refused"), retriable=False), + id="network", + ), + pytest.param(OAuthHttpError(status_code=503), id="5xx"), + pytest.param(OAuthHttpError(status_code=429), id="429"), + pytest.param( + DeviceAuthorizationError(error="access_denied", status_code=503), + id="503-with-permanent-code", + ), + ], + ) + def test_device_poll_error(self, cause): + error = DevicePollError(15, cause) + assert error.interval == 15 + assert error.cause is cause + assert error.retryable is True + assert str(error) == ( + f"Device token polling stopped, resume with interval 15s: {cause}" + ) + # Device grant Retryability: a 429 or 5xx is retryable whatever its code, # invalid_grant included. Any other status classifies by the code. @pytest.mark.parametrize("code", PROTOCOL_ERROR_CODES)