Skip to content
Open
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
128 changes: 97 additions & 31 deletions packages/oauth/src/keycardai/oauth/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Comment on lines +1283 to +1295

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) Callers whose timeout is an httpx.Timeout object, not a float, now get a TypeError from every device grant call. On the base branch those calls work. limit = timeout or self.config.timeout now goes to asyncio.wait_for, which compares it with 0, while the base passed it only to httpx, which accepts httpx.Timeout. Fix: reduce limit to a number before wait_for, for example by taking the largest phase of an httpx.Timeout or by validating the value up front with a ConfigError, so the httpx transport still gets the original value.

Why this was flagged

I could not list who sets the timeout. ClientConfig (types/models.py:491) is a plain dataclass with timeout: float = 30.0 and does no validation. HttpxAsyncTransport passes the value straight to httpx at _transports.py:143 and :182, and httpx accepts httpx.Timeout(10, connect=2). So a config that sets one works for every other AsyncClient operation (for example client.py:863 and :1089). After this change, _authenticate_and_send (client.py:1283-1295) calls asyncio.wait_for(run(), limit). On 3.12+ that evaluates timeout <= 0, and on 3.10/3.11 it adds the timeout to loop.time(). Both raise TypeError before any credential call or request, and leave run() un-awaited, which emits a RuntimeWarning. request_device_authorization and poll_device_token raise that bare TypeError. wait_for_device_token raises it too, not DevicePollError. The float annotation does not prevent this, because nothing checks it at runtime.

Verification: Trigger: a caller passes a value the public API does not declare, an httpx.Timeout object, as ClientConfig.timeout or as the per-call timeout. client.py:1294 calls await asyncio.wait_for(run(), limit). With an httpx.Timeout, wait_for raises TypeError. The except asyncio.TimeoutError at 1295 does not catch that TypeError. On the base, httpx accepts httpx.Timeout.

except asyncio.TimeoutError as e:
Comment on lines +1294 to +1296

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 On Python 3.10 and 3.11, a cancellation that lands just as a device request finishes is silently lost. The polling loop then keeps calling the credential and sending polls. asyncio.wait_for on those versions returns the inner result when the inner task is already done at cancel time, which swallows the CancelledError. Fix: bound the call so outer cancellation always propagates, for example with asyncio.timeout on 3.11+ and a cancel-aware fallback on 3.10. This covers request_device_authorization, poll_device_token and each wait_for_device_token poll.

Why this was flagged

pyproject.toml sets requires-python = ">=3.10". In CPython 3.10 and 3.11, asyncio.wait_for catches CancelledError and, when fut.done(), does return fut.result() without re-raising. That code was rewritten only in 3.12. _authenticate_and_send (client.py:1294-1296) now wraps every device request in asyncio.wait_for. Suppose a caller cancels wait_for_device_token, for example through asyncio.timeout or a TaskGroup, in the same loop iteration the poll response completes with authorization_pending. The cancellation is consumed, the loop takes the continue path, and it sleeps, calls the credential and polls again. The docstring at client.py:1467-1469 promises it will not do that. The caller's deadline is missed until the device code expires or the user approves. On the base branch the credential and _send_device_request were awaited directly, so the CancelledError always reached the caller. The await asyncio.sleep(0) guard at client.py:1548 does not help, because the cancellation was already swallowed.

Verification: On 3.10 and 3.11, wait_for runs fut as a separate task. Its except CancelledError: if fut.done(): return fut.result() path returns the result without re-raising, which drops the cancellation (bpo-42130 / gh-86296). The diff adds return await asyncio.wait_for(run(), limit) at client.py:1295. This is a regression. The base had no wait_for anywhere in packages/oauth/src.

raise NetworkError(cause=e, operation=operation, retriable=False) from e

async def request_device_authorization(
self,
*,
Expand Down Expand Up @@ -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
Expand All @@ -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(
Expand All @@ -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.
Expand All @@ -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,
Expand Down Expand Up @@ -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:
Expand All @@ -1502,6 +1567,7 @@ def expired(description: str) -> DeviceAuthorizationError:
interval += SLOW_DOWN_INCREMENT
continue
raise
raise token.error

async def impersonate(
self,
Expand Down
107 changes: 106 additions & 1 deletion packages/oauth/tests/keycardai/oauth/test_device_authorization.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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):
Expand All @@ -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"),
[
Expand Down Expand Up @@ -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):
Expand Down
Loading