Repository navigation
fix(keycardai-oauth): the request timeout bounds the credential call too #437
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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: | ||
|
Comment on lines
+1294
to
+1296
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. Why this was flaggedpyproject.toml sets requires-python = ">=3.10". In CPython 3.10 and 3.11, Verification: On 3.10 and 3.11, |
||
| 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, | ||
|
|
||
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) Callers whose timeout is an
httpx.Timeoutobject, not a float, now get aTypeErrorfrom every device grant call. On the base branch those calls work.limit = timeout or self.config.timeoutnow goes toasyncio.wait_for, which compares it with 0, while the base passed it only to httpx, which acceptshttpx.Timeout. Fix: reducelimitto a number beforewait_for, for example by taking the largest phase of anhttpx.Timeoutor by validating the value up front with aConfigError, 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 withtimeout: float = 30.0and does no validation. HttpxAsyncTransport passes the value straight to httpx at _transports.py:143 and :182, and httpx acceptshttpx.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) callsasyncio.wait_for(run(), limit). On 3.12+ that evaluatestimeout <= 0, and on 3.10/3.11 it adds the timeout toloop.time(). Both raiseTypeErrorbefore any credential call or request, and leaverun()un-awaited, which emits a RuntimeWarning.request_device_authorizationandpoll_device_tokenraise that bareTypeError.wait_for_device_tokenraises it too, notDevicePollError. Thefloatannotation 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.Timeoutobject, asClientConfig.timeoutor as the per-calltimeout. client.py:1294 callsawait asyncio.wait_for(run(), limit). With anhttpx.Timeout,wait_forraises TypeError. Theexcept asyncio.TimeoutErrorat 1295 does not catch that TypeError. On the base, httpx acceptshttpx.Timeout.