From 97c319155b5a5b9149e26e24319ad6338bcc3461 Mon Sep 17 00:00:00 2001 From: Casey Marshall Date: Tue, 17 Nov 2026 17:40:31 -0600 Subject: [PATCH] fix(keycardai-oauth): the request timeout bounds the credential call too request_device_authorization, poll_device_token, and each poll of wait_for_device_token run the credential's client authentication and the request under one asyncio.wait_for, so the timeout bounds the whole round trip, as Go does with one context.WithTimeout. httpx's timeout alone applies to each phase of the request, and the credential call had no bound. Running out of time raises NetworkError, so poll until done stops with DevicePollError and a doubled interval. An exception the credential raises propagates unchanged (unit row 27). Co-Authored-By: Claude Opus 5.5 --- packages/oauth/src/keycardai/oauth/client.py | 128 +++++++++++++----- .../oauth/test_device_authorization.py | 107 ++++++++++++++- 2 files changed, 203 insertions(+), 32 deletions(-) diff --git a/packages/oauth/src/keycardai/oauth/client.py b/packages/oauth/src/keycardai/oauth/client.py index d301f50..62d9aba 100644 --- a/packages/oauth/src/keycardai/oauth/client.py +++ b/packages/oauth/src/keycardai/oauth/client.py @@ -3,7 +3,8 @@ import asyncio import threading import warnings -from dataclasses import replace +from collections.abc import Callable +from dataclasses import dataclass, replace from typing import TYPE_CHECKING, Any, overload from ._metadata_cache import MetadataCache @@ -113,6 +114,18 @@ async def client_authentication( return ClientAuthentication(form_fields={"client_id": self.client_id}) +@dataclass(frozen=True) +class _ClientAuthenticationFailure: + """An exception the credential's client authentication raised. + + The device grant helpers return it instead of raising it. Callers raise + ``error`` unchanged, outside any handler for request failures, so a + credential failure never becomes a DevicePollError. + """ + + error: Exception + + def _device_client_authenticator( credential: object | None, client_id: str | None ) -> ClientAuthenticator: @@ -1244,6 +1257,45 @@ async def _send_device_request( except ResponseBodyDecodeError as e: raise undecodable_body_error(e, operation) from e + async def _authenticate_and_send( + self, + authenticator: ClientAuthenticator, + issuer: str, + endpoint: str, + build: Callable[[ClientAuthentication], HttpRequest], + timeout: float | None, + operation: str, + ) -> "HttpResponse | _ClientAuthenticationFailure": + """Call the credential's client authentication, then send the request. + + The request timeout bounds the credential call and the request + together. Running out of time raises NetworkError. + + Returns: + The response, or a _ClientAuthenticationFailure when the + credential raised. The caller raises its ``error`` unchanged. + + Raises: + NetworkError: The request failed, or the timeout ran out. + DeviceAuthorizationError, OAuthHttpError: As for + _send_device_request. + """ + limit = timeout or self.config.timeout + + async def run() -> "HttpResponse | _ClientAuthenticationFailure": + try: + client_auth = await authenticator.client_authentication( + issuer=issuer, endpoint=endpoint + ) + except Exception as e: + return _ClientAuthenticationFailure(e) + return await self._send_device_request(build(client_auth), limit, operation) + + try: + return await asyncio.wait_for(run(), limit) + except asyncio.TimeoutError as e: + raise NetworkError(cause=e, operation=operation, retriable=False) from e + async def request_device_authorization( self, *, @@ -1275,7 +1327,9 @@ async def request_device_authorization( parameter per entry. metadata: Pre-discovered authorization server metadata. No discovery request is made. - timeout: Request timeout. Defaults to the client's timeout. + timeout: Request timeout. It bounds the credential's client + authentication and the request together. Defaults to the + client's timeout. Returns: DeviceAuthorization, with ``expires_at`` read from the client's @@ -1297,35 +1351,45 @@ async def request_device_authorization( issuer, endpoint = await self._resolve_device_endpoint( metadata, "device_authorization_endpoint" ) - client_auth = await authenticator.client_authentication( - issuer=issuer, endpoint=endpoint - ) - request = build_device_authorization_http_request( - endpoint=endpoint, - client_auth=client_auth, - scopes=scopes, - resources=resources, - ) - response = await self._send_device_request( - request, timeout, DEVICE_AUTHORIZATION_OPERATION + response = await self._authenticate_and_send( + authenticator, + issuer, + endpoint, + lambda client_auth: build_device_authorization_http_request( + endpoint=endpoint, + client_auth=client_auth, + scopes=scopes, + resources=resources, + ), + timeout, + DEVICE_AUTHORIZATION_OPERATION, ) + if isinstance(response, _ClientAuthenticationFailure): + raise response.error return parse_device_authorization_http_response( response, received_at=self.clock.now() ) async def _poll_device_token_once( self, + authenticator: ClientAuthenticator, + issuer: str, token_endpoint: str, device_code: str, - client_auth: ClientAuthentication, timeout: float | None, - ) -> TokenResponse: - request = build_device_token_http_request( - endpoint=token_endpoint, device_code=device_code, client_auth=client_auth - ) - response = await self._send_device_request( - request, timeout, DEVICE_TOKEN_OPERATION + ) -> "TokenResponse | _ClientAuthenticationFailure": + response = await self._authenticate_and_send( + authenticator, + issuer, + token_endpoint, + lambda client_auth: build_device_token_http_request( + endpoint=token_endpoint, device_code=device_code, client_auth=client_auth + ), + timeout, + DEVICE_TOKEN_OPERATION, ) + if isinstance(response, _ClientAuthenticationFailure): + return response return parse_device_token_http_response(response) async def poll_device_token( @@ -1350,7 +1414,9 @@ async def poll_device_token( credential: As for request_device_authorization. client_id: As for request_device_authorization. metadata: Pre-discovered authorization server metadata. - timeout: Request timeout. Defaults to the client's timeout. + timeout: Request timeout. It bounds the credential's client + authentication and the request together. Defaults to the + client's timeout. Returns: The token, with ``refresh_token`` and ``id_token`` as received. @@ -1373,12 +1439,12 @@ async def poll_device_token( issuer, endpoint = await self._resolve_device_endpoint( metadata, "token_endpoint" ) - client_auth = await authenticator.client_authentication( - issuer=issuer, endpoint=endpoint - ) - return await self._poll_device_token_once( - endpoint, authorization.device_code, client_auth, timeout + token = await self._poll_device_token_once( + authenticator, issuer, endpoint, authorization.device_code, timeout ) + if isinstance(token, _ClientAuthenticationFailure): + raise token.error + return token async def wait_for_device_token( self, @@ -1483,13 +1549,12 @@ def expired(description: str) -> DeviceAuthorizationError: 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 + token = await self._poll_device_token_once( + authenticator, issuer, endpoint, authorization.device_code, timeout ) + if not isinstance(token, _ClientAuthenticationFailure): + return token except NetworkError as e: raise DevicePollError(interval * 2, e) from e except (DeviceAuthorizationError, OAuthHttpError) as e: @@ -1502,6 +1567,7 @@ def expired(description: str) -> DeviceAuthorizationError: interval += SLOW_DOWN_INCREMENT continue raise + raise token.error async def impersonate( self, diff --git a/packages/oauth/tests/keycardai/oauth/test_device_authorization.py b/packages/oauth/tests/keycardai/oauth/test_device_authorization.py index 78af840..b97b161 100644 --- a/packages/oauth/tests/keycardai/oauth/test_device_authorization.py +++ b/packages/oauth/tests/keycardai/oauth/test_device_authorization.py @@ -977,6 +977,89 @@ async def test_timeout_argument_bounds_the_request(operation): assert transport.timeouts == [2.5] +class SlowCredential(FakeCredential): + """A FakeCredential that waits ``delay`` seconds, or raises ``error``.""" + + def __init__(self, delay: float = 0.0, error: BaseException | None = None): + super().__init__() + self.delay = delay + self.error = error + + async def client_authentication(self, *, issuer: str, endpoint: str) -> ClientAuthentication: + await asyncio.sleep(self.delay) + if self.error is not None: + raise self.error + return await super().client_authentication(issuer=issuer, endpoint=endpoint) + + +class SlowTransport(FakeTransport): + """A FakeTransport that records each request, then waits ``delay`` + seconds before it answers.""" + + def __init__(self, *responses, delay: float): + super().__init__(*responses) + self.delay = delay + + async def request_raw(self, req: HttpRequest, *, timeout: float | None = None) -> HttpResponse: + self.requests.append(req) + self.timeouts.append(timeout) + await asyncio.sleep(self.delay) + return self.responses.pop(0) + + +SINGLE_REQUESTS = [ + pytest.param(request_op, device_response(), id="request"), + pytest.param(poll_once_op, respond(200, TOKEN_BODY), id="poll-once"), +] + + +# The timeout is 0.2 seconds. In the "together" row each step alone takes +# less, so only a bound on both steps together ends it. +@pytest.mark.parametrize(("operation", "response"), SINGLE_REQUESTS) +@pytest.mark.parametrize( + ("credential_delay", "transport_delay", "requests_sent"), + [ + pytest.param(5.0, 0.0, 0, id="credential-hangs"), + pytest.param(0.0, 5.0, 1, id="request-hangs"), + pytest.param(0.15, 0.15, 1, id="together"), + ], +) +async def test_timeout_bounds_the_credential_and_the_request_together( + operation, response, credential_delay, transport_delay, requests_sent +): + transport = SlowTransport(response, delay=transport_delay) + + with pytest.raises(NetworkError) as exc: + await operation( + make_client(transport), credential=SlowCredential(credential_delay), timeout=0.2 + ) + + assert exc.value.operation == OPERATION_NAMES[operation] + assert isinstance(exc.value.cause, asyncio.TimeoutError) + assert len(transport.requests) == requests_sent + + +# A credential's own exception propagates unchanged, even one of the types +# the request itself raises. +@pytest.mark.parametrize(("operation", "response"), SINGLE_REQUESTS) +@pytest.mark.parametrize( + "error", + [ + pytest.param(asyncio.TimeoutError("token source timed out"), id="TimeoutError"), + pytest.param(NetworkError(OSError("token source unreachable")), id="NetworkError"), + ], +) +async def test_credential_error_propagates_unchanged(operation, response, error): + transport = FakeTransport(response) + + with pytest.raises(type(error)) as exc: + await operation(make_client(transport), credential=SlowCredential(error=error)) + + assert exc.value is error + assert exc.value.__cause__ is None + assert transport.requests == [] + + async def test_row_22_web_identity_signs_a_new_assertion_per_request(tmp_path): credential = WebIdentity( server_name="device", storage_dir=str(tmp_path), client_id="registered-client" @@ -1462,6 +1545,10 @@ async def client_authentication( NetworkError(cause=httpx.ConnectError("refused"), retriable=False), id="row-27-network-error-from-the-credential", ), + pytest.param( + asyncio.TimeoutError("token source timed out"), + id="row-27-timeout-error-from-the-credential", + ), ], ) async def test_row_27_credential_failure_returns_as_is(error): @@ -1475,6 +1562,20 @@ async def test_row_27_credential_failure_returns_as_is(error): assert len(transport.requests) == 1 +async def test_credential_that_outlasts_the_timeout_is_a_network_error(): + transport = FakeTransport() + + with pytest.raises(DevicePollError) as exc: + await wait( + make_client(transport), client_id=None, credential=SlowCredential(5.0), timeout=0.05 + ) + + assert exc.value.interval == 2 * 5 + assert type(exc.value.__cause__) is NetworkError + assert isinstance(exc.value.__cause__.cause, asyncio.TimeoutError) + assert transport.requests == [] + + @pytest.mark.parametrize( ("deadline", "expected"), [ @@ -1521,7 +1622,11 @@ async def never_respond(reader, writer): 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) + # asyncio.wait_for and httpx's read timeout both use 0.2 seconds, so + # either one ends the poll. + assert isinstance( + exc.value.__cause__.cause, (httpx.ReadTimeout, asyncio.TimeoutError) + ) class CancelAtWaitEnd(FakeClock):