From 3a3ffd76c61026e2337c1bf618e3fb8a2596ade1 Mon Sep 17 00:00:00 2001 From: Kevin Wooten Date: Tue, 10 Nov 2026 14:27:30 -0800 Subject: [PATCH 1/6] Support direct HTTPX adapters without token providers --- README.md | 11 ++++ src/sunday/httpx/__init__.py | 2 + src/sunday/httpx/_transport.py | 13 ++-- src/sunday/httpx/request_adapter.py | 4 ++ src/sunday/httpx/request_security_bindings.py | 22 +++++++ tests/test_direct_security_adapter.py | 63 +++++++++++++++++++ 6 files changed, 111 insertions(+), 4 deletions(-) create mode 100644 src/sunday/httpx/request_security_bindings.py create mode 100644 tests/test_direct_security_adapter.py diff --git a/README.md b/README.md index fd91640..e3f10d6 100644 --- a/README.md +++ b/README.md @@ -420,3 +420,14 @@ it runs before the new request-adapter chain. Prefer the independent `request_ad The [adapter lifecycle audit](docs/adapter-lifecycle-audit.md) records the recurring failure patterns, native-framework boundaries, and regression coverage used for this refactor. + +### Application-owned authentication adapters + +A transport with a `request_adapter` and no `token_providers` delegates protected requests directly to the adapter. +`request_security_bindings(request)` from `sunday.httpx` exposes the generated operation's immutable audience, +scopes, and credential-placement metadata. Copies and adapter composition preserve this metadata without +adding wire headers or token receipts. Adapters run for all operations and responses; applications select the +exchanges they own and must preserve usable request/response streams. + +Standalone adapters do not enable token-recovery retries. Raise `RequestCancellationError` to stop an exchange, +or return the response for ordinary handling. The optional provider-based integration retains its recovery policy. diff --git a/src/sunday/httpx/__init__.py b/src/sunday/httpx/__init__.py index f0c0ebd..8869fa3 100644 --- a/src/sunday/httpx/__init__.py +++ b/src/sunday/httpx/__init__.py @@ -20,6 +20,7 @@ HttpxTransport, ) from .request_adapter import RequestAdapter, RequestAdapters + from .request_security_bindings import request_security_bindings from .response_adapter import ResponseAdapter, ResponseAdapters except ModuleNotFoundError as error: if error.name not in {"anyio", "httpx"}: @@ -40,4 +41,5 @@ "ResponseAdapter", "ResponseAdapters", "copy_request", + "request_security_bindings", ] diff --git a/src/sunday/httpx/_transport.py b/src/sunday/httpx/_transport.py index 2b6c2d5..8299ff9 100644 --- a/src/sunday/httpx/_transport.py +++ b/src/sunday/httpx/_transport.py @@ -40,6 +40,7 @@ from ._response_cleanup import close_response, protect_response from ._security import AuthenticationRecoveryBudget, RequestSecurity from .request_adapter import RequestAdapterLike, RequestAdapters +from .request_security_bindings import _set_request_security_bindings from .response_adapter import ResponseAdapterLike, ResponseAdapters ResponseT = TypeVar("ResponseT") @@ -120,7 +121,7 @@ def register_problem(self, type_uri: str, problem_type: type[Problem]) -> None: async def transport_request(self, spec: RequestSpec[Any]) -> httpx.Request: """Materialize an optionally authorized request, handing its lifecycle to the consumer.""" request = await self._prepare_request(spec) - if spec.security is not None: + if spec.security is not None and (self.token_providers or not self._request_adapter.adapters): await RequestSecurity(spec.security).authorize(request, self.token_providers) return await self._request_adapter.adapt(request) @@ -138,7 +139,7 @@ async def execute_request(self, spec: RequestSpec[Any]) -> httpx.Response: def _build_request(self, spec: RequestSpec[Any]) -> httpx.Request: try: - return self._build_validated_request(spec) + return _set_request_security_bindings(self._build_validated_request(spec), spec.security or ()) except (RequestEncodingError, RequestCancellationError): raise except (TypeError, ValueError) as error: @@ -329,7 +330,11 @@ async def _execute( history: list[httpx.Response] = [] while True: sent = copy_request(prepared) - authorized = await security.authorize(sent, self.token_providers) if security is not None else None + authorized = ( + await security.authorize(sent, self.token_providers) + if security is not None and (self.token_providers or not self._request_adapter.adapters) + else None + ) try: sent = await self._request_adapter.adapt(sent) except BaseException as error: @@ -350,7 +355,7 @@ async def _execute( if not recoverable: raise TokenRejectedError() response = await self._response_adapter.adapt(response, effective) - if budget.should_retry(effective, response): + if authorized is not None and budget.should_retry(effective, response): await close_response(response) continue next_request = ( diff --git a/src/sunday/httpx/request_adapter.py b/src/sunday/httpx/request_adapter.py index a6a4d9e..0e459fa 100644 --- a/src/sunday/httpx/request_adapter.py +++ b/src/sunday/httpx/request_adapter.py @@ -11,6 +11,8 @@ import anyio import httpx +from .request_security_bindings import _set_request_security_bindings, request_security_bindings + class RequestAdapter(ABC): """Adapt once before each Sunday-managed native call, or once for export. @@ -45,6 +47,8 @@ async def adapt(self, request: httpx.Request) -> httpx.Request: """Run each adapter once, preserving native task cancellation.""" for adapter in self.adapters: await anyio.lowlevel.checkpoint_if_cancelled() + bindings = request_security_bindings(request) request = await adapter.adapt(request) if isinstance(adapter, RequestAdapter) else await adapter(request) + _set_request_security_bindings(request, bindings) await anyio.lowlevel.checkpoint_if_cancelled() return request diff --git a/src/sunday/httpx/request_security_bindings.py b/src/sunday/httpx/request_security_bindings.py new file mode 100644 index 0000000..9f3df2a --- /dev/null +++ b/src/sunday/httpx/request_security_bindings.py @@ -0,0 +1,22 @@ +"""Operation metadata for HTTP adapters, independent of token acquisition and storage.""" + +from collections.abc import Sequence + +import httpx + +from ..security import SecurityBinding + +_KEY = "sunday.security_bindings" + + +def request_security_bindings(request: httpx.Request) -> tuple[SecurityBinding, ...]: + """Return the originating operation's bindings without credential receipts or token state.""" + return request.extensions.get(_KEY, ()) + + +def _set_request_security_bindings(request: httpx.Request, bindings: Sequence[SecurityBinding]) -> httpx.Request: + if bindings: + request.extensions[_KEY] = tuple(bindings) + else: + request.extensions.pop(_KEY, None) + return request diff --git a/tests/test_direct_security_adapter.py b/tests/test_direct_security_adapter.py new file mode 100644 index 0000000..a353653 --- /dev/null +++ b/tests/test_direct_security_adapter.py @@ -0,0 +1,63 @@ +import httpx +import pytest + +from sunday import RequestCancellationError, RequestSpec, SecurityBinding, SecurityTransport +from sunday.httpx import HttpxTransport, RequestAdapters, copy_request, request_security_bindings + +pytestmark = pytest.mark.anyio +BINDING = SecurityBinding( + scheme="bearerAuth", + provider="application", + flow="external", + audience="https://api.example", + transport=SecurityTransport(location="header", name="Authorization", prefix="Bearer"), +) + + +async def test_direct_adapters_receive_bindings_without_token_providers(): + calls = [] + + async def adapt(request): + assert request_security_bindings(request) == (BINDING,) + return httpx.Request(request.method, request.url, headers={"Authorization": "Bearer custom"}) + + async def copy(request): + assert request_security_bindings(request) == (BINDING,) + return copy_request(request) + + async def response_adapter(response, request): + assert request_security_bindings(request) == (BINDING,) + assert request.headers["Authorization"] == "Bearer custom" + return response + + async def send(request): + calls.append(request) + return httpx.Response(401, headers={"WWW-Authenticate": 'Bearer error="invalid_token"'}, content=b"original") + + async with httpx.AsyncClient(base_url="https://api.example", transport=httpx.MockTransport(send)) as client: + transport = HttpxTransport( + client=client, request_adapter=RequestAdapters(adapt, copy), response_adapter=response_adapter + ) + spec = RequestSpec("GET", "/value", security=(BINDING,)) + exported = await transport.transport_request(spec) + assert exported.headers["Authorization"] == "Bearer custom" + response = await transport.execute_request(spec) + assert response.status_code == 401 + assert response.content == b"original" + assert len(calls) == 1 + + +async def test_direct_adapter_cancellation_prevents_sending(): + stop = RequestCancellationError("application authorization unavailable") + + async def adapt(request): + raise stop + + async def send(request): + pytest.fail("Cancelled request was sent") + + async with httpx.AsyncClient(base_url="https://api.example", transport=httpx.MockTransport(send)) as client: + transport = HttpxTransport(client=client, request_adapter=adapt) + with pytest.raises(RequestCancellationError) as caught: + await transport.execute_request(RequestSpec("GET", "/value", security=(BINDING,))) + assert caught.value is stop From 6e33f4c5c1becb0fb2c5751c659d40eed638fa97 Mon Sep 17 00:00:00 2001 From: Kevin Wooten Date: Tue, 10 Nov 2026 14:57:14 -0800 Subject: [PATCH 2/6] Remove token coupling from HTTPX transport and SSE --- README.md | 37 ++++--- src/sunday/httpx/__init__.py | 4 + src/sunday/httpx/_diagnostics.py | 37 +++++++ src/sunday/httpx/_sse.py | 9 +- src/sunday/httpx/_transport.py | 80 +++----------- src/sunday/httpx/authentication_adapter.py | 100 ++++++++++++++++++ src/sunday/httpx/request_adapter.py | 3 + src/sunday/httpx/request_security_bindings.py | 3 +- tests/test_client_settings.py | 14 +-- tests/test_direct_security_adapter.py | 20 ++-- tests/test_httpx_adapters.py | 25 ++--- tests/test_httpx_cleanup.py | 5 +- tests/test_httpx_security.py | 72 +++++++------ 13 files changed, 252 insertions(+), 157 deletions(-) create mode 100644 src/sunday/httpx/_diagnostics.py create mode 100644 src/sunday/httpx/authentication_adapter.py diff --git a/README.md b/README.md index e3f10d6..04f8606 100644 --- a/README.md +++ b/README.md @@ -101,13 +101,13 @@ authoritative. ## Profiled credentials Generated operations carry selected `SecurityBinding` metadata in `RequestSpec.security`. Applications -pass named providers directly to `HttpxTransport(token_providers=...)`. +compose providers explicitly with `HttpxTransport(..., **authentication_adapters(providers))`. Providers and token storage stay in the application; generated code contains no credentials. ```python import httpx from sunday import TokenManager -from sunday.httpx import HttpxOAuthTokenProvider, HttpxTransport +from sunday.httpx import HttpxOAuthTokenProvider, HttpxTransport, authentication_adapters def create_transport(client: httpx.AsyncClient, client_secret: str) -> HttpxTransport: @@ -121,7 +121,7 @@ def create_transport(client: httpx.AsyncClient, client_secret: str) -> HttpxTran ) return HttpxTransport( client, - token_providers={"service-identity": TokenManager(provider)}, + **authentication_adapters({"service-identity": TokenManager(provider)}), ) ``` @@ -290,8 +290,9 @@ field configuration above. A literal string `"UNSET"` remains an ordinary string ## Application-owned token lifecycle -Transports accept named `TokenProvider` instances directly. Settings preserve supplied providers and -never add a token cache. Every managed network attempt asks its provider for current credentials. +Transports accept only request and response adapters; they have no token-provider option or authentication retry logic. +The optional `AuthenticationAdapter` bridges named providers to these contracts. Settings factories compose it explicitly +without adding a cache. External authentication frameworks can implement the adapters directly. An external framework (for example Auth0) remains responsible for storage, renewal and logout. Return only its access token and optional expiry; keep its refresh token inside that framework. @@ -303,7 +304,8 @@ settings = ClientSettings.resolve( base_url, alternatives, {"identity": ProviderCredentials(tokens)}, ) # Supply an external framework's provider directly instead to keep its lifecycle authoritative. -transport = HttpxTransport.from_settings(settings, client) +from sunday.httpx import transport_from_settings +transport = transport_from_settings(settings, client) ``` Managers retain expiry skew, coalesced renewal, refresh rotation and application-selected persistence. @@ -322,10 +324,11 @@ manager on rejection, serializing concurrent rejection handling without maintain Request export materializes an optionally authorized native request once and hands its lifecycle to the consumer. Exported requests retain no Sunday-managed recovery state. Executing an operation through -Sunday acquires once per attempt and retains the bounded safe-request recovery and SSE reconnect budget. +Sunday invokes the request adapter once per attempt. Authentication responses do not trigger an implicit retry; +an application may make another request after its credential owner handles the rejection. -Migration: replace transport `tokenManager`/`token_manager` arguments with named -`tokenProviders`/`token_providers` maps. Replace `TokenManagerFactory` hooks with explicitly constructed +Migration: replace transport `tokenManager`/`token_manager` and `tokenProviders`/`token_providers` arguments +with explicit request/response adapters. Replace `TokenManagerFactory` hooks with explicitly constructed managers supplied through provider credentials. Direct built-in OAuth providers are not implicitly cached; wrap them explicitly when Sunday should retain and refresh their tokens. For logout, stop outstanding requests and settle refresh commits before clearing the owning framework's or application's storage. @@ -360,11 +363,10 @@ transport = HttpxTransport( ) ``` -Managed attempts prepare and authorize, adapt the request, send, adapt the response, then -apply normal response handling and bounded recovery. No response capability is inferred from -a request adapter. Provider rejection feedback is independent of custom response adapters and -runs even for unsafe methods or exhausted retry budgets. Only the token actually sent is rejected. -Security receipts and retry counts are local to execution, never attached to exported requests. +Managed attempts prepare, adapt the request, send, and adapt the response before normal handling. +No response capability is inferred from a request adapter. Optional `AuthenticationAdapter` owns provider +rejection feedback; transport execution does not classify or retry token rejection. Cancellation markers +stop the exchange. Native request export detaches operation bindings and leaves execution to the consumer. Adapters surround each native HTTPX call. Borrowed-client event hooks, authentication flows, and transport-level connection recovery retain their native behavior; intermediate native @@ -423,11 +425,12 @@ patterns, native-framework boundaries, and regression coverage used for this ref ### Application-owned authentication adapters -A transport with a `request_adapter` and no `token_providers` delegates protected requests directly to the adapter. +Transports delegate requests directly to `request_adapter` and responses to `response_adapter`. `request_security_bindings(request)` from `sunday.httpx` exposes the generated operation's immutable audience, scopes, and credential-placement metadata. Copies and adapter composition preserve this metadata without adding wire headers or token receipts. Adapters run for all operations and responses; applications select the exchanges they own and must preserve usable request/response streams. -Standalone adapters do not enable token-recovery retries. Raise `RequestCancellationError` to stop an exchange, -or return the response for ordinary handling. The optional provider-based integration retains its recovery policy. +Raise `RequestCancellationError` to stop an exchange, or return the response for ordinary handling. +Transports have no token-recovery retries. `AuthenticationAdapter`, `authentication_adapters`, and +`transport_from_settings` provide optional provider composition outside transport execution. diff --git a/src/sunday/httpx/__init__.py b/src/sunday/httpx/__init__.py index 8869fa3..5d55967 100644 --- a/src/sunday/httpx/__init__.py +++ b/src/sunday/httpx/__init__.py @@ -19,6 +19,7 @@ HttpxRequestAdapterCallable, HttpxTransport, ) + from .authentication_adapter import AuthenticationAdapter, authentication_adapters, transport_from_settings from .request_adapter import RequestAdapter, RequestAdapters from .request_security_bindings import request_security_bindings from .response_adapter import ResponseAdapter, ResponseAdapters @@ -28,6 +29,7 @@ raise ImportError("sunday.httpx requires the 'httpx' extra; install 'sunday-python[httpx]'") from error __all__ = [ + "AuthenticationAdapter", "AuthorizationGrant", "HttpxEventSource", "HttpxEventSourceRequestFactory", @@ -40,6 +42,8 @@ "RequestAdapters", "ResponseAdapter", "ResponseAdapters", + "authentication_adapters", "copy_request", "request_security_bindings", + "transport_from_settings", ] diff --git a/src/sunday/httpx/_diagnostics.py b/src/sunday/httpx/_diagnostics.py new file mode 100644 index 0000000..baf2b14 --- /dev/null +++ b/src/sunday/httpx/_diagnostics.py @@ -0,0 +1,37 @@ +"""Redact operation-designated credential locations without acquiring or interpreting tokens.""" + +import httpx + +from ..request_cancellation_error import RequestCancellationError +from ._requests import copy_request +from .request_security_bindings import request_security_bindings + + +def diagnostic_request(request: httpx.Request) -> httpx.Request: + """Remove sensitive values from native response and failure diagnostics.""" + bindings = request_security_bindings(request) + if not bindings: + return request + url, headers = request.url, httpx.Headers(request.headers) + for binding in bindings: + transport = binding.transport + if transport.location == "query": + url = url.copy_set_param(transport.name, "[redacted]") + elif transport.location == "header": + headers[transport.name] = "[redacted]" + else: + headers["cookie"] = "[redacted]" + return copy_request(request, url=url, headers=headers) + + +def diagnostic_error(error: BaseException, request: httpx.Request) -> BaseException: + """Preserve cancellation while removing sensitive request data from HTTPX failures.""" + if not request_security_bindings(request) or isinstance(error, RequestCancellationError): + return error + diagnostic = diagnostic_request(request) + if isinstance(error, httpx.HTTPStatusError): + error.response.request = diagnostic + return type(error)("HTTP request failed", request=diagnostic, response=error.response) + if isinstance(error, httpx.RequestError): + return type(error)("HTTP request failed", request=diagnostic) + return error diff --git a/src/sunday/httpx/_sse.py b/src/sunday/httpx/_sse.py index 89eb03b..55f500c 100644 --- a/src/sunday/httpx/_sse.py +++ b/src/sunday/httpx/_sse.py @@ -25,11 +25,9 @@ from ..request_cancellation_error import RequestCancellationError from ..specs import RequestSpec from ..sse import EventParser, EventStreamOptions, ServerSentEvent -from ..token_provider import TokenProviderError from ._async import complete, run_io from ._reconnect import _ReconnectPolicy from ._response_cleanup import close_response, in_response_cleanup -from ._security import AuthenticationRecoveryBudget, RequestSecurity if TYPE_CHECKING: from ._transport import HttpxEventSourceRequestFactory, HttpxTransport @@ -173,7 +171,6 @@ async def events(self) -> AsyncGenerator[EventT, None]: self._close_event = anyio.Event() reconnect = _ReconnectPolicy(self._options.retry, self._options.retry_max) last_event_id: str | None = None - recovery_budget = AuthenticationRecoveryBudget() try: while not self._closed: @@ -192,8 +189,6 @@ async def events(self) -> AsyncGenerator[EventT, None]: self._disable_httpx_read_timeout(request) response = await self._transport._send_event_stream( request, - recovery_budget=recovery_budget, - security=RequestSecurity(self._spec.security) if self._spec.security is not None else None, ) self._response = response @@ -241,9 +236,7 @@ def current_timeout(state: list[float | None] = timeout_state) -> float | None: return except RequestCancellationError: raise - except (httpx.TransportError, TimeoutError, TokenProviderError) as error: - if isinstance(error, TokenProviderError) and error.reason != "temporary": - raise + except (httpx.TransportError, TimeoutError) as error: if self._closed: return if self._on_error is not None: diff --git a/src/sunday/httpx/_transport.py b/src/sunday/httpx/_transport.py index 8299ff9..ab1f3e1 100644 --- a/src/sunday/httpx/_transport.py +++ b/src/sunday/httpx/_transport.py @@ -8,12 +8,11 @@ import asyncio from collections.abc import Awaitable, Callable, Mapping, Sequence from time import monotonic -from types import MappingProxyType, TracebackType +from types import TracebackType from typing import Any, Protocol, TypeVar import httpx -from ..client_settings import ClientSettings from ..codecs import JsonCodec, MediaTypeDecoders, MediaTypeEncoders from ..errors import ( RequestEncodingError, @@ -32,15 +31,14 @@ from ..specs import RequestSpec, ResponseSpec from ..sse import EventStreamOptions, ServerSentEvent from ..streaming import StreamingBody -from ..token_provider import TokenProvider, TokenRejectedError from ..transport import BaseTransport from ..uri import URITemplate from ._async import complete, run_io +from ._diagnostics import diagnostic_error, diagnostic_request from ._requests import BodyStream, copy_request, is_credentialed, redirect_request from ._response_cleanup import close_response, protect_response -from ._security import AuthenticationRecoveryBudget, RequestSecurity from .request_adapter import RequestAdapterLike, RequestAdapters -from .request_security_bindings import _set_request_security_bindings +from .request_security_bindings import _set_request_security_bindings, request_security_bindings from .response_adapter import ResponseAdapterLike, ResponseAdapters ResponseT = TypeVar("ResponseT") @@ -81,7 +79,6 @@ def __init__( response_adapter: ResponseAdapterLike | None = None, observers: Sequence[TransportObserver] = (), sensitive_headers: Sequence[str] = (), - token_providers: Mapping[str, TokenProvider] | None = None, ) -> None: if client is not None and base_url is not None: raise TransportError("base_url cannot be provided with a borrowed HTTPX client") @@ -93,7 +90,6 @@ def __init__( self.adapters = tuple(adapters) self.observers = tuple(observers) self.sensitive_headers = tuple(sensitive_headers) - self.token_providers = MappingProxyType(dict(token_providers or {})) self._request_adapter = RequestAdapters( *((self._adapt_legacy_request,) if self.adapters else ()), *((request_adapter,) if request_adapter is not None else ()), @@ -103,17 +99,6 @@ def __init__( self._cleanup: asyncio.Task[None] | None = None self._event_sources: set[HttpxEventSource] = set() - @classmethod - def from_settings(cls, settings: ClientSettings, client: httpx.AsyncClient) -> HttpxTransport: - """Use a borrowed application client for API and isolated OAuth requests. - - The client's base URL must match the resolved endpoint. The caller owns its lifetime. - For other transport options, pass ``settings.token_providers`` to the normal constructor. - """ - if str(client.base_url).rstrip("/") != str(httpx.URL(settings.base_url)).rstrip("/"): - raise ValueError("HTTPX client base URL must match resolved settings") - return cls(client, token_providers=settings.token_providers) - def register_problem(self, type_uri: str, problem_type: type[Problem]) -> None: """Register a generated problem exception for response decoding.""" self.problem_registry.register(type_uri, problem_type) @@ -121,9 +106,7 @@ def register_problem(self, type_uri: str, problem_type: type[Problem]) -> None: async def transport_request(self, spec: RequestSpec[Any]) -> httpx.Request: """Materialize an optionally authorized request, handing its lifecycle to the consumer.""" request = await self._prepare_request(spec) - if spec.security is not None and (self.token_providers or not self._request_adapter.adapters): - await RequestSecurity(spec.security).authorize(request, self.token_providers) - return await self._request_adapter.adapt(request) + return _set_request_security_bindings(await self._request_adapter.adapt(request), ()) async def _prepare_request(self, spec: RequestSpec[Any]) -> httpx.Request: """Build without adapting; execution and export each own their adaptation step.""" @@ -134,8 +117,7 @@ async def _prepare_request(self, spec: RequestSpec[Any]) -> httpx.Request: async def execute_request(self, spec: RequestSpec[Any]) -> httpx.Response: """Execute with invocation-local security receipts and no request-attached state.""" request = await self._prepare_request(spec) - security = RequestSecurity(spec.security) if spec.security is not None else None - return await self._execute(request, stream=False, security=security) + return await self._execute(request, stream=False) def _build_request(self, spec: RequestSpec[Any]) -> httpx.Request: try: @@ -306,13 +288,8 @@ async def _send(self, request: httpx.Request, *, stream: bool = False) -> httpx. async def _send_event_stream( self, request: httpx.Request, - *, - recovery_budget: AuthenticationRecoveryBudget, - security: RequestSecurity | None = None, ) -> httpx.Response: - return await self._execute( - request, stream=True, follow_redirects=True, recovery_budget=recovery_budget, security=security - ) + return await self._execute(request, stream=True, follow_redirects=True) async def _execute( self, @@ -320,47 +297,26 @@ async def _execute( *, stream: bool, follow_redirects: bool | None = None, - recovery_budget: AuthenticationRecoveryBudget | None = None, - security: RequestSecurity | None = None, ) -> httpx.Response: - budget = recovery_budget or AuthenticationRecoveryBudget() follow = self.client.follow_redirects if follow_redirects is None else follow_redirects prepared = request redirects = 0 history: list[httpx.Response] = [] while True: sent = copy_request(prepared) - authorized = ( - await security.authorize(sent, self.token_providers) - if security is not None and (self.token_providers or not self._request_adapter.adapters) - else None - ) try: sent = await self._request_adapter.adapt(sent) except BaseException as error: - if authorized is not None: - diagnostic_error = authorized.diagnostic_error(error, sent) - if diagnostic_error is not error: - raise diagnostic_error from None - raise - response = await self._send_httpx(sent, security=authorized) + raise diagnostic_error(error, sent) from None + response = await self._send_httpx(sent) effective = sent try: response.history = [*history, *response.history] effective = copy_request(response.request) - if authorized is not None: - recoverable = True - for lease in authorized.rejected_leases(effective, response): - recoverable = await lease.invalidate() and recoverable - if not recoverable: - raise TokenRejectedError() response = await self._response_adapter.adapt(response, effective) - if authorized is not None and budget.should_retry(effective, response): - await close_response(response) - continue next_request = ( redirect_request(prepared, effective, response) - if follow and not (authorized is not None and authorized.bindings) + if follow and not request_security_bindings(effective) else None ) if next_request is not None: @@ -374,30 +330,23 @@ async def _execute( history = [*response.history, response] prepared = next_request continue - if authorized is not None and authorized.bindings: - response.request = authorized.diagnostic_request(effective) + response.request = diagnostic_request(effective) if not stream: await run_io(response.aread) await close_response(response) return response except BaseException as error: await close_response(response, error) - if authorized is not None: - diagnostic_error = authorized.diagnostic_error(error, effective) - if diagnostic_error is not error: - raise diagnostic_error from None - raise + raise diagnostic_error(error, effective) from None async def _send_httpx( self, request: httpx.Request, - *, - security: RequestSecurity | None = None, ) -> httpx.Response: if self._closed: raise TransportError("HttpxTransport is closed") started = monotonic() - diagnostic = security.diagnostic_request(request) if security is not None and security.bindings else request + diagnostic = diagnostic_request(request) self._observe( TransportEvent( TransportEventKind.REQUEST, @@ -407,7 +356,7 @@ async def _send_httpx( ) ) try: - if (security is not None and security.bindings) or is_credentialed(request): + if request_security_bindings(request) or is_credentialed(request): response = await run_io( lambda: self.client.send(request, stream=True, follow_redirects=False, auth=None), discard=close_response, @@ -418,8 +367,7 @@ async def _send_httpx( discard=close_response, ) except BaseException as error: - if security is not None: - error = security.diagnostic_error(error, request) + error = diagnostic_error(error, request) try: self._observe( TransportEvent( diff --git a/src/sunday/httpx/authentication_adapter.py b/src/sunday/httpx/authentication_adapter.py new file mode 100644 index 0000000..87d3354 --- /dev/null +++ b/src/sunday/httpx/authentication_adapter.py @@ -0,0 +1,100 @@ +"""Explicit provider integration outside HTTP transport execution.""" + +from collections.abc import Mapping +from typing import TYPE_CHECKING, TypedDict, cast, overload + +from ..client_settings import ClientSettings + +if TYPE_CHECKING: + from ._transport import HttpxTransport + +import httpx + +from ..request_cancellation_error import RequestCancellationError +from ..token_provider import TokenProvider, TokenProviderError, TokenRejectedError +from ._security import RequestSecurity +from .request_adapter import RequestAdapterLike, RequestAdapters +from .request_security_bindings import request_security_bindings +from .response_adapter import ResponseAdapterLike, ResponseAdapters + + +class AuthenticationAdapter: + """Callable request/response adapter, without transport retries. + + Install the same instance in both slots. Compose using RequestAdapters and + ResponseAdapters, whose independent chain types avoid ambiguous inheritance. + """ + + def __init__(self, providers: Mapping[str, TokenProvider]) -> None: + self._providers = dict(providers) + self._receipt = f"sunday.authentication.{id(self)}" + + @overload + async def __call__(self, value: httpx.Request) -> httpx.Request: ... + + @overload + async def __call__(self, value: httpx.Response, request: httpx.Request) -> httpx.Response: ... + + async def __call__( + self, value: httpx.Request | httpx.Response, request: httpx.Request | None = None + ) -> httpx.Request | httpx.Response: + """Return a usable message; terminal provider failure cancels the exchange.""" + if request is not None: + assert isinstance(value, httpx.Response) + security = ( + cast(RequestSecurity | None, request.extensions.get(self._receipt)) + if request_security_bindings(request) + else None + ) + if security is not None: + recoverable = True + try: + for lease in security.rejected_leases(request, value): + recoverable = await lease.invalidate() and recoverable + except TokenProviderError as error: + if error.reason != "temporary": + raise RequestCancellationError(str(error)) from error + raise httpx.TransportError("Credentials temporarily unavailable", request=request) from error + if not recoverable: + raise TokenRejectedError() + return value + assert isinstance(value, httpx.Request) + bindings = request_security_bindings(value) + if not bindings: + return value + try: + value.extensions[self._receipt] = await RequestSecurity(bindings).authorize(value, self._providers) + except TokenProviderError as error: + if error.reason != "temporary": + raise RequestCancellationError(str(error)) from error + raise httpx.TransportError("Credentials temporarily unavailable", request=value) from error + return value + + +class AuthenticationAdapters(TypedDict): + """Explicit request/response slots accepted by HttpxTransport.""" + + request_adapter: RequestAdapterLike + response_adapter: ResponseAdapterLike + + +def authentication_adapters( + providers: Mapping[str, TokenProvider], + request_adapter: RequestAdapterLike | None = None, + response_adapter: ResponseAdapterLike | None = None, +) -> AuthenticationAdapters: + """Compose provider integration explicitly before optional application adapters.""" + authentication = AuthenticationAdapter(providers) + return { + "request_adapter": RequestAdapters(authentication, *((request_adapter,) if request_adapter else ())), + "response_adapter": ResponseAdapters(authentication, *((response_adapter,) if response_adapter else ())), + } + + +def transport_from_settings(settings: ClientSettings, client: httpx.AsyncClient) -> "HttpxTransport": + """Compose provider adapters from client settings using a caller-owned HTTPX client.""" + from ._transport import HttpxTransport + + if str(client.base_url).rstrip("/") != str(httpx.URL(settings.base_url)).rstrip("/"): + raise ValueError("HTTPX client base URL must match resolved settings") + return HttpxTransport(client, **authentication_adapters(settings.token_providers)) diff --git a/src/sunday/httpx/request_adapter.py b/src/sunday/httpx/request_adapter.py index 0e459fa..5e08545 100644 --- a/src/sunday/httpx/request_adapter.py +++ b/src/sunday/httpx/request_adapter.py @@ -47,8 +47,11 @@ async def adapt(self, request: httpx.Request) -> httpx.Request: """Run each adapter once, preserving native task cancellation.""" for adapter in self.adapters: await anyio.lowlevel.checkpoint_if_cancelled() + metadata = {key: value for key, value in request.extensions.items() if key.startswith("sunday.")} bindings = request_security_bindings(request) request = await adapter.adapt(request) if isinstance(adapter, RequestAdapter) else await adapter(request) + for key, value in metadata.items(): + request.extensions.setdefault(key, value) _set_request_security_bindings(request, bindings) await anyio.lowlevel.checkpoint_if_cancelled() return request diff --git a/src/sunday/httpx/request_security_bindings.py b/src/sunday/httpx/request_security_bindings.py index 9f3df2a..99a6bb4 100644 --- a/src/sunday/httpx/request_security_bindings.py +++ b/src/sunday/httpx/request_security_bindings.py @@ -1,6 +1,7 @@ """Operation metadata for HTTP adapters, independent of token acquisition and storage.""" from collections.abc import Sequence +from typing import cast import httpx @@ -11,7 +12,7 @@ def request_security_bindings(request: httpx.Request) -> tuple[SecurityBinding, ...]: """Return the originating operation's bindings without credential receipts or token state.""" - return request.extensions.get(_KEY, ()) + return cast(tuple[SecurityBinding, ...], request.extensions.get(_KEY, ())) def _set_request_security_bindings(request: httpx.Request, bindings: Sequence[SecurityBinding]) -> httpx.Request: diff --git a/tests/test_client_settings.py b/tests/test_client_settings.py index d17ee21..f2c2bc4 100644 --- a/tests/test_client_settings.py +++ b/tests/test_client_settings.py @@ -22,7 +22,7 @@ TokenSet, provider_credentials, ) -from sunday.httpx import AuthorizationGrant, HttpxTransport +from sunday.httpx import AuthorizationGrant, transport_from_settings BINDING = SecurityBinding( scheme="identity", @@ -41,10 +41,10 @@ def test_static_settings_and_httpx_adapter() -> None: async def check() -> None: async with httpx.AsyncClient(base_url=settings.base_url) as client: - transport = HttpxTransport.from_settings(settings, client) + transport = transport_from_settings(settings, client) assert transport.client is client - assert transport.token_providers - lease = await provider_credentials(transport.token_providers[BINDING.provider], BINDING) + assert settings.token_providers + lease = await provider_credentials(settings.token_providers[BINDING.provider], BINDING) assert lease.tokens.access_token == "private-token" asyncio.run(check()) @@ -68,7 +68,7 @@ def test_settings_snapshot_and_adapter_endpoint_validation() -> None: async def check() -> None: async with httpx.AsyncClient(base_url="https://other.example") as client: with pytest.raises(ValueError, match="base URL"): - HttpxTransport.from_settings(settings, client) + transport_from_settings(settings, client) asyncio.run(check()) @@ -199,9 +199,9 @@ def test_httpx_adapter_normalizes_both_endpoint_urls() -> None: async def check() -> None: async with httpx.AsyncClient(base_url=settings.base_url) as client: - assert HttpxTransport.from_settings(settings, client).client is client + assert transport_from_settings(settings, client).client is client async with httpx.AsyncClient(base_url="https://api.example/different") as client: with pytest.raises(ValueError): - HttpxTransport.from_settings(settings, client) + transport_from_settings(settings, client) asyncio.run(check()) diff --git a/tests/test_direct_security_adapter.py b/tests/test_direct_security_adapter.py index a353653..b57b001 100644 --- a/tests/test_direct_security_adapter.py +++ b/tests/test_direct_security_adapter.py @@ -1,3 +1,5 @@ +from typing import Any + import httpx import pytest @@ -14,23 +16,23 @@ ) -async def test_direct_adapters_receive_bindings_without_token_providers(): +async def test_direct_adapters_receive_bindings_without_token_providers() -> None: calls = [] - async def adapt(request): + async def adapt(request: httpx.Request) -> httpx.Request: assert request_security_bindings(request) == (BINDING,) return httpx.Request(request.method, request.url, headers={"Authorization": "Bearer custom"}) - async def copy(request): + async def copy(request: httpx.Request) -> httpx.Request: assert request_security_bindings(request) == (BINDING,) return copy_request(request) - async def response_adapter(response, request): + async def response_adapter(response: httpx.Response, request: httpx.Request) -> httpx.Response: assert request_security_bindings(request) == (BINDING,) assert request.headers["Authorization"] == "Bearer custom" return response - async def send(request): + async def send(request: httpx.Request) -> httpx.Response: calls.append(request) return httpx.Response(401, headers={"WWW-Authenticate": 'Bearer error="invalid_token"'}, content=b"original") @@ -38,7 +40,7 @@ async def send(request): transport = HttpxTransport( client=client, request_adapter=RequestAdapters(adapt, copy), response_adapter=response_adapter ) - spec = RequestSpec("GET", "/value", security=(BINDING,)) + spec: RequestSpec[Any] = RequestSpec("GET", "/value", security=(BINDING,)) exported = await transport.transport_request(spec) assert exported.headers["Authorization"] == "Bearer custom" response = await transport.execute_request(spec) @@ -47,13 +49,13 @@ async def send(request): assert len(calls) == 1 -async def test_direct_adapter_cancellation_prevents_sending(): +async def test_direct_adapter_cancellation_prevents_sending() -> None: stop = RequestCancellationError("application authorization unavailable") - async def adapt(request): + async def adapt(request: httpx.Request) -> httpx.Request: raise stop - async def send(request): + async def send(request: httpx.Request) -> httpx.Response: pytest.fail("Cancelled request was sent") async with httpx.AsyncClient(base_url="https://api.example", transport=httpx.MockTransport(send)) as client: diff --git a/tests/test_httpx_adapters.py b/tests/test_httpx_adapters.py index ae2a82d..dac54b0 100644 --- a/tests/test_httpx_adapters.py +++ b/tests/test_httpx_adapters.py @@ -41,9 +41,9 @@ RequestAdapters, ResponseAdapter, ResponseAdapters, + authentication_adapters, copy_request, ) -from sunday.httpx._security import AuthenticationRecoveryBudget, RequestSecurity pytestmark = pytest.mark.anyio @@ -86,8 +86,6 @@ async def perform(transport: HttpxTransport, streaming: bool, spec: RequestSpec[ request = await transport._prepare_request(spec) response = await transport._send_event_stream( request, - recovery_budget=AuthenticationRecoveryBudget(), - security=RequestSecurity(spec.security) if spec.security is not None else None, ) try: await response.aread() @@ -344,9 +342,9 @@ async def reject(self, request: TokenRequest, rejected_token: str) -> bool: @pytest.mark.parametrize("streaming", [False, True]) -@pytest.mark.parametrize("method,expected", [("POST", 1), ("GET", 2)]) +@pytest.mark.parametrize("method,expected", [("POST", 1), ("GET", 1)]) @pytest.mark.parametrize("rewrite", [False, True]) -async def test_feedback_is_independent_of_retry_budget_and_matches_wire_token( +async def test_feedback_does_not_retry_and_matches_wire_token( streaming: bool, method: str, expected: int, @@ -370,7 +368,7 @@ async def hook(request: httpx.Request) -> None: lambda _: httpx.Response(401, headers={"WWW-Authenticate": "Bearer error=invalid_token"}) ), ) as client: - transport = HttpxTransport(client, token_providers={"identity": provider}, response_adapter=observe) + transport = HttpxTransport(client, **authentication_adapters({"identity": provider}, None, observe)) response = await perform(transport, streaming, RequestSpec(method, "/value", security=(BINDING,))) assert response.status_code == 401 assert provider.acquisitions == expected @@ -444,7 +442,9 @@ def content() -> bytes: ), ) as client: transport = HttpxTransport( - client, token_providers={"identity": StoppingProvider()}, observers=(FailingObserver(),) + client, + observers=(FailingObserver(),), + **authentication_adapters({"identity": StoppingProvider()}, None, None), ) spec = RequestSpec( "POST", "/value", security=(BINDING,), body=StreamingBody(content) if stage == "upload" else None @@ -865,9 +865,7 @@ async def adapt(response: httpx.Response, request: httpx.Request) -> httpx.Respo return response async with httpx.AsyncClient(base_url="https://api.example", transport=httpx.MockTransport(handle)) as client: - transport = HttpxTransport( - client, request_adapter=adapt_request, response_adapter=adapt, token_providers={"identity": provider} - ) + transport = HttpxTransport(client, **authentication_adapters({"identity": provider}, adapt_request, adapt)) with pytest.raises(httpx.ReadError) as failure: await perform(transport, streaming, RequestSpec("GET", "/value", security=bindings if managed else None)) error = failure.value @@ -918,10 +916,7 @@ def handle(request: httpx.Request) -> httpx.Response: base_url="https://api.example", transport=httpx.MockTransport(handle), event_hooks={"response": [hook]} ) as client: transport = HttpxTransport( - client, - request_adapter=adapt_request, - response_adapter=adapt_response, - token_providers={"identity": Provider()}, + client, **authentication_adapters({"identity": Provider()}, adapt_request, adapt_response) ) with pytest.raises(asyncio.CancelledError) as failure: await perform(transport, streaming, RequestSpec("GET", "/value", security=(BINDING,))) @@ -988,7 +983,7 @@ def handle(request: httpx.Request) -> httpx.Response: base_url="https://api.example", transport=httpx.MockTransport(handle), event_hooks={"response": [hook]} ) as client: transport = HttpxTransport( - client, response_adapter=adapt, token_providers={"identity": Provider()}, observers=(Observer(),) + client, observers=(Observer(),), **authentication_adapters({"identity": Provider()}, None, adapt) ) with pytest.raises(httpx.HTTPStatusError) as failure: await perform(transport, streaming, RequestSpec("GET", "/value", security=bindings if managed else None)) diff --git a/tests/test_httpx_cleanup.py b/tests/test_httpx_cleanup.py index 5d63edd..41ff730 100644 --- a/tests/test_httpx_cleanup.py +++ b/tests/test_httpx_cleanup.py @@ -29,7 +29,6 @@ TokenRequest, ) from sunday.httpx import HttpxOAuthTokenProvider, HttpxTransport, copy_request -from sunday.httpx._security import AuthenticationRecoveryBudget pytestmark = pytest.mark.anyio @@ -107,9 +106,7 @@ async def server() -> AsyncIterator[Server]: async def execute(transport: HttpxTransport, streaming: bool, spec: RequestSpec[Any]) -> httpx.Response: if not streaming: return await transport.execute_request(spec) - response = await transport._send_event_stream( - await transport._prepare_request(spec), recovery_budget=AuthenticationRecoveryBudget() - ) + response = await transport._send_event_stream(await transport._prepare_request(spec)) try: await response.aread() return response diff --git a/tests/test_httpx_security.py b/tests/test_httpx_security.py index 725d30a..2eda018 100644 --- a/tests/test_httpx_security.py +++ b/tests/test_httpx_security.py @@ -2,7 +2,6 @@ # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. - from collections.abc import AsyncIterator from dataclasses import replace from typing import Any @@ -13,6 +12,7 @@ from sunday import ( Operation, OperationSpec, + RequestCancellationError, RequestSpec, ResponseSpec, SecurityBinding, @@ -26,7 +26,7 @@ TransportEvent, UnexpectedResponse, ) -from sunday.httpx import HttpxTransport +from sunday.httpx import HttpxTransport, authentication_adapters BINDING = SecurityBinding( scheme="token", @@ -71,7 +71,7 @@ async def send(transport: HttpxTransport, spec: RequestSpec[Any]) -> httpx.Respo @pytest.mark.anyio -async def test_complete_credentials_and_one_safe_recovery() -> None: +async def test_complete_credentials_and_explicit_subsequent_renewal() -> None: provider = Provider() authorization: list[str] = [] @@ -82,7 +82,9 @@ def handle(request: httpx.Request) -> httpx.Response: return httpx.Response(204) async with httpx.AsyncClient(base_url="https://api.example", transport=httpx.MockTransport(handle)) as client: - transport = HttpxTransport(client, token_providers={"identity": TokenManager(provider)}) + transport = HttpxTransport(client, **authentication_adapters({"identity": TokenManager(provider)}, None, None)) + response = await send(transport, RequestSpec("GET", "/value", security=(BINDING,))) + assert response.status_code == 401 response = await send(transport, RequestSpec("GET", "/value", security=(BINDING,))) assert response.status_code == 204 assert response.request.headers["authorization"] == "[redacted]" @@ -101,8 +103,8 @@ def handle(request: httpx.Request) -> httpx.Response: ("GET", 401, 'Bearer error="INVALID_TOKEN"', 1), ("GET", 401, 'Basic realm="x", error="invalid_token"', 1), ("GET", 401, 'Bearer error="insufficient_scope"', 1), - ("GET", 401, 'Bearer realm="x,y", error="invalid_token"', 2), - ("GET", 401, 'Basic realm="x", Bearer error="invalid_token"', 2), + ("GET", 401, 'Bearer realm="x,y", error="invalid_token"', 1), + ("GET", 401, 'Basic realm="x", Bearer error="invalid_token"', 1), ("GET", 401, 'Bearer realm="unterminated, error=invalid_token', 1), ], ) @@ -119,7 +121,7 @@ def handle(request: httpx.Request) -> httpx.Response: return httpx.Response(status, headers={"WWW-Authenticate": challenge}) async with httpx.AsyncClient(base_url="https://api.example", transport=httpx.MockTransport(handle)) as client: - transport = HttpxTransport(client, token_providers={"identity": TokenManager(provider)}) + transport = HttpxTransport(client, **authentication_adapters({"identity": TokenManager(provider)}, None, None)) operation: Operation[None, httpx.Request, httpx.Response] = Operation( transport, OperationSpec(RequestSpec(method, "/value", security=(BINDING,)), (ResponseSpec(204),)), @@ -140,7 +142,7 @@ def handle(request: httpx.Request) -> httpx.Response: manager = TokenManager({"identity": provider}) async with httpx.AsyncClient(base_url="https://api.example", transport=httpx.MockTransport(handle)) as client: - transport = HttpxTransport(client, token_providers={"identity": manager}) + transport = HttpxTransport(client, **authentication_adapters({"identity": manager}, None, None)) request = await transport.transport_request(RequestSpec("GET", "/value", security=(BINDING,))) await transport.transport_response(request) await manager.invalidate(await manager.credentials(BINDING)) @@ -183,7 +185,9 @@ def handle(request: httpx.Request) -> httpx.Response: return httpx.Response(204) async with httpx.AsyncClient(base_url="https://api.example", transport=httpx.MockTransport(handle)) as client: - transport = HttpxTransport(client, token_providers={"identity": TokenManager(provider)}, observers=(observer,)) + transport = HttpxTransport( + client, observers=(observer,), **authentication_adapters({"identity": TokenManager(provider)}, None, None) + ) response = await send( transport, RequestSpec( @@ -208,11 +212,13 @@ def handle(_request: httpx.Request) -> httpx.Response: return httpx.Response(204) async with httpx.AsyncClient(base_url="https://api.example", transport=httpx.MockTransport(handle)) as client: - missing = HttpxTransport(client) - with pytest.raises(TokenProviderError): + missing = HttpxTransport(client, **authentication_adapters({})) + with pytest.raises(RequestCancellationError): await send(missing, RequestSpec("GET", "/value", security=(BINDING,))) - transport = HttpxTransport(client, token_providers={"identity": TokenManager(Provider())}) - with pytest.raises(TokenProviderError): + transport = HttpxTransport( + client, **authentication_adapters({"identity": TokenManager(Provider())}, None, None) + ) + with pytest.raises(RequestCancellationError): await send( transport, RequestSpec( @@ -222,7 +228,7 @@ def handle(_request: httpx.Request) -> httpx.Response: headers=(("Authorization", "existing"),), ), ) - with pytest.raises(TokenProviderError): + with pytest.raises(RequestCancellationError): await send(transport, RequestSpec("GET", "/value", security=(BINDING, BINDING))) assert sends == 0 @@ -237,7 +243,7 @@ def handle(request: httpx.Request) -> httpx.Response: async with httpx.AsyncClient(base_url="https://api.example", transport=httpx.MockTransport(handle)) as client: transport = HttpxTransport( - client, token_providers={"identity": TokenManager(Provider())}, observers=(observer,) + client, observers=(observer,), **authentication_adapters({"identity": TokenManager(Provider())}, None, None) ) with pytest.raises(httpx.ConnectError) as error: await send(transport, RequestSpec("GET", "/value", security=(binding,))) @@ -263,14 +269,16 @@ def handle(request: httpx.Request) -> httpx.Response: follow_redirects=True, auth=("unrelated", "credentials"), ) as client: - transport = HttpxTransport(client, token_providers={"identity": TokenManager(Provider())}) + transport = HttpxTransport( + client, **authentication_adapters({"identity": TokenManager(Provider())}, None, None) + ) response = await send(transport, RequestSpec("GET", "/value", security=(binding,))) assert response.status_code == 302 assert sends == ["https://api.example/value"] @pytest.mark.anyio -async def test_event_reconnects_share_one_authentication_recovery() -> None: +async def test_event_rejection_has_no_hidden_authentication_retry() -> None: from sunday import EventStreamOptions provider = Provider() @@ -283,7 +291,7 @@ def handle(request: httpx.Request) -> httpx.Response: return httpx.Response(401, headers={"WWW-Authenticate": "Bearer error=invalid_token"}) async with httpx.AsyncClient(base_url="https://api.example", transport=httpx.MockTransport(handle)) as client: - transport = HttpxTransport(client, token_providers={"identity": TokenManager(provider)}) + transport = HttpxTransport(client, **authentication_adapters({"identity": TokenManager(provider)}, None, None)) stream = transport.event_stream( RequestSpec("GET", "/events", security=(BINDING,)), lambda event: event.data, @@ -294,9 +302,9 @@ def handle(request: httpx.Request) -> httpx.Response: async for value in stream: values.append(value) await stream.aclose() - assert values == ["first"] - assert authorization == ["Bearer access-1", "Bearer renewed-1", "Bearer renewed-1"] - assert provider.refreshes == ["refresh-first"] + assert values == [] + assert authorization == ["Bearer access-1"] + assert provider.refreshes == [] @pytest.mark.anyio @@ -317,7 +325,7 @@ async def acquire(self, request: TokenRequest) -> TokenSet: lambda _: httpx.Response(200, headers={"Content-Type": "text/event-stream"}, content="data: recovered\n\n") ), ) as client: - transport = HttpxTransport(client, token_providers={"identity": TokenManager(provider)}) + transport = HttpxTransport(client, **authentication_adapters({"identity": TokenManager(provider)}, None, None)) stream = transport.event_stream( RequestSpec("GET", "/events", security=(BINDING,)), lambda event: event.data, @@ -345,11 +353,13 @@ def handle(request: httpx.Request) -> httpx.Response: transport=httpx.MockTransport(handle), headers={"Authorization": "Bearer ambient"}, ) as client: - transport = HttpxTransport(client, token_providers={"identity": TokenManager(Provider())}) + transport = HttpxTransport( + client, **authentication_adapters({"identity": TokenManager(Provider())}, None, None) + ) await send(transport, RequestSpec("GET", "/managed", security=(binding,))) await send(transport, RequestSpec("GET", "/unmanaged")) assert client.headers["authorization"] == "Bearer ambient" - with pytest.raises(TokenProviderError): + with pytest.raises(RequestCancellationError): await send( transport, RequestSpec("GET", "/managed", security=(binding,), headers=(("Authorization", "Bearer explicit"),)), @@ -373,7 +383,7 @@ def configure(self, binding: SecurityBinding) -> TokenConfiguration: async with httpx.AsyncClient( base_url="https://api.example", transport=httpx.MockTransport(lambda _: httpx.Response(204)) ) as client: - transport = HttpxTransport(client, token_providers={"identity": TokenManager(provider)}) + transport = HttpxTransport(client, **authentication_adapters({"identity": TokenManager(provider)}, None, None)) native = await transport.transport_request(RequestSpec("GET", "/value", security=(BINDING,))) assert provider.configurations == provider.acquisitions == 1 await transport.transport_response(native) @@ -412,7 +422,7 @@ def handle(request: httpx.Request) -> httpx.Response: return httpx.Response(204) async with httpx.AsyncClient(base_url="https://api.example", transport=httpx.MockTransport(handle)) as client: - transport = HttpxTransport(client, token_providers={"identity": provider}) + transport = HttpxTransport(client, **authentication_adapters({"identity": provider}, None, None)) operation: Operation[None, httpx.Request, httpx.Response] = Operation( transport, OperationSpec(RequestSpec("GET", "/value", security=(BINDING,)), (ResponseSpec(204),)) ) @@ -420,12 +430,14 @@ def handle(request: httpx.Request) -> httpx.Response: provider.token = "replacement" await operation.transport_response() provider.token = "rejected" + with pytest.raises(UnexpectedResponse): + await operation.execute() await operation.execute() assert provider.acquisitions == 4 assert provider.rejections == 1 assert seen == ["Bearer first", "Bearer replacement", "Bearer rejected", "Bearer renewed"] provider.token = None - with pytest.raises(TokenProviderError): + with pytest.raises(RequestCancellationError): await operation.execute() assert len(seen) == 4 @@ -440,7 +452,7 @@ def handle(request: httpx.Request) -> httpx.Response: return httpx.Response(401, headers={"WWW-Authenticate": "Bearer error=invalid_token"}) async with httpx.AsyncClient(base_url="https://api.example", transport=httpx.MockTransport(handle)) as client: - transport = HttpxTransport(client, token_providers={"identity": provider}) + transport = HttpxTransport(client, **authentication_adapters({"identity": provider}, None, None)) with pytest.raises(TokenRejectedError): await transport.execute_request(RequestSpec("GET", "/value", security=(BINDING,))) assert len(seen) == provider.acquisitions == 1 @@ -462,8 +474,8 @@ async def __aiter__(self) -> AsyncIterator[bytes]: async with httpx.AsyncClient( base_url="https://api.example", transport=httpx.MockTransport(lambda _: response) ) as client: - transport = HttpxTransport(client, token_providers={"identity": FailingProvider()}) - with pytest.raises(TokenProviderError) as failure: + transport = HttpxTransport(client, **authentication_adapters({"identity": FailingProvider()}, None, None)) + with pytest.raises(RequestCancellationError) as failure: await transport.execute_request(RequestSpec("GET", "/value", security=(BINDING,))) assert "private-provider-detail" not in str(failure.value) assert response.is_closed From c22b558f00d0b4482840c805509e64b5b2d8dd48 Mon Sep 17 00:00:00 2001 From: Kevin Wooten Date: Tue, 10 Nov 2026 16:27:59 -0800 Subject: [PATCH 3/6] Make authentication stop policy explicit through adapters --- README.md | 20 ++++++- src/sunday/httpx/__init__.py | 2 + src/sunday/httpx/_security.py | 29 ---------- src/sunday/httpx/_transport.py | 16 ++++-- .../httpx/bearer_token_rejection_adapter.py | 24 ++++++++ tests/test_httpx_adapters.py | 56 +++++++++++++++++++ 6 files changed, 111 insertions(+), 36 deletions(-) create mode 100644 src/sunday/httpx/bearer_token_rejection_adapter.py diff --git a/README.md b/README.md index 04f8606..51267d8 100644 --- a/README.md +++ b/README.md @@ -290,12 +290,26 @@ field configuration above. A literal string `"UNSET"` remains an ordinary string ## Application-owned token lifecycle -Transports accept only request and response adapters; they have no token-provider option or authentication retry logic. -The optional `AuthenticationAdapter` bridges named providers to these contracts. Settings factories compose it explicitly -without adding a cache. External authentication frameworks can implement the adapters directly. +Transport constructors perform no authentication or authorization by default. They accept request and response +adapters, with no token-provider option or authentication retry loop. External authentication frameworks can +implement these adapters directly, without using Sunday's token or security classes. + +The optional `AuthenticationAdapter` acquires credentials for declared bindings, reports missing providers, +and sends matching rejection feedback to the credential owner. Install it explicitly in each desired slot; +installing a request adapter alone does not install response behavior. It adds no cache. + +`BearerTokenRejectionAdapter` is a separate, opt-in response policy. It throws the cancellation marker when +an initiating request sent a bearer credential and its response is 401 with an explicit Bearer `invalid_token` +challenge. It leaves all other responses and all bodies untouched. Compose it after `AuthenticationAdapter` +when provider feedback should run before cancellation. It has no counter, renewal, or replay behavior. +The removed `AuthenticationRecoveryBudget` has no implicit replacement: applications choose their own +recovery policy, and a cancellation-marked error always stops the exchange, retries, and SSE reconnections. An external framework (for example Auth0) remains responsible for storage, renewal and logout. Return only its access token and optional expiry; keep its refresh token inside that framework. +The provider-settings convenience `transport_from_settings(...)` explicitly installs provider adapters. +Use the ordinary transport constructor with your own adapters when you want to own the exchange entirely. + For Sunday's caching and refresh lifecycle, explicitly supply a `TokenManager` as the provider: ```python diff --git a/src/sunday/httpx/__init__.py b/src/sunday/httpx/__init__.py index 5d55967..b19bb2d 100644 --- a/src/sunday/httpx/__init__.py +++ b/src/sunday/httpx/__init__.py @@ -20,6 +20,7 @@ HttpxTransport, ) from .authentication_adapter import AuthenticationAdapter, authentication_adapters, transport_from_settings + from .bearer_token_rejection_adapter import BearerTokenRejectionAdapter from .request_adapter import RequestAdapter, RequestAdapters from .request_security_bindings import request_security_bindings from .response_adapter import ResponseAdapter, ResponseAdapters @@ -31,6 +32,7 @@ __all__ = [ "AuthenticationAdapter", "AuthorizationGrant", + "BearerTokenRejectionAdapter", "HttpxEventSource", "HttpxEventSourceRequestFactory", "HttpxEventStream", diff --git a/src/sunday/httpx/_security.py b/src/sunday/httpx/_security.py index d3ae18a..2b33f0e 100644 --- a/src/sunday/httpx/_security.py +++ b/src/sunday/httpx/_security.py @@ -151,35 +151,6 @@ def _invalid_bearer_challenge(header: str) -> bool: return False -class AuthenticationRecoveryBudget: - """One authentication recovery across an invocation, including event reconnects.""" - - def __init__(self) -> None: - self._used = False - - def should_retry(self, request: httpx.Request, response: httpx.Response) -> bool: - """Allow one bodyless safe-method retry after explicit token rejection.""" - if ( - request.method not in {"GET", "HEAD", "OPTIONS"} - or response.status_code != 401 - or _bearer_token(request) is None - or not _invalid_bearer_challenge(response.headers.get("www-authenticate", "")) - ): - return False - try: - if request.content: - return False - except httpx.RequestNotRead: - return False - return self.consume() - - def consume(self) -> bool: - if self._used: - return False - self._used = True - return True - - def _bearer_token(request: httpx.Request) -> str | None: parts = request.headers.get("authorization", "").split() return parts[1] if len(parts) == 2 and parts[0].lower() == "bearer" else None diff --git a/src/sunday/httpx/_transport.py b/src/sunday/httpx/_transport.py index ab1f3e1..45e5233 100644 --- a/src/sunday/httpx/_transport.py +++ b/src/sunday/httpx/_transport.py @@ -307,7 +307,10 @@ async def _execute( try: sent = await self._request_adapter.adapt(sent) except BaseException as error: - raise diagnostic_error(error, sent) from None + diagnostic = diagnostic_error(error, sent) + if diagnostic is error: + raise + raise diagnostic from None response = await self._send_httpx(sent) effective = sent try: @@ -337,7 +340,10 @@ async def _execute( return response except BaseException as error: await close_response(response, error) - raise diagnostic_error(error, effective) from None + diagnostic = diagnostic_error(error, effective) + if diagnostic is error: + raise + raise diagnostic from None async def _send_httpx( self, @@ -366,8 +372,8 @@ async def _send_httpx( lambda: self.client.send(request, stream=True, follow_redirects=False), discard=close_response, ) - except BaseException as error: - error = diagnostic_error(error, request) + except BaseException as original: + error = diagnostic_error(original, request) try: self._observe( TransportEvent( @@ -381,6 +387,8 @@ async def _send_httpx( ) except BaseException: error.add_note("Reporting the HTTP request failure also failed") + if error is original: + raise raise error from None protect_response(response) try: diff --git a/src/sunday/httpx/bearer_token_rejection_adapter.py b/src/sunday/httpx/bearer_token_rejection_adapter.py new file mode 100644 index 0000000..563dfca --- /dev/null +++ b/src/sunday/httpx/bearer_token_rejection_adapter.py @@ -0,0 +1,24 @@ +"""Optional terminal policy for explicit bearer rejection, independent of credential ownership.""" + +import httpx + +from ..request_cancellation_error import RequestCancellationError +from ._security import _bearer_token, _invalid_bearer_challenge +from .response_adapter import ResponseAdapter + + +class BearerTokenRejectionAdapter(ResponseAdapter): + """Stop a rejected bearer exchange without refreshing, replaying, or reading response data. + + Compose after provider rejection feedback when both adapters are installed. + """ + + async def adapt(self, response: httpx.Response, request: httpx.Request) -> httpx.Response: + """Return unrelated responses unchanged; cancellation leaves renewal to the credential owner.""" + if ( + response.status_code == 401 + and _bearer_token(request) is not None + and _invalid_bearer_challenge(response.headers.get("www-authenticate", "")) + ): + raise RequestCancellationError("Access token rejected") + return response diff --git a/tests/test_httpx_adapters.py b/tests/test_httpx_adapters.py index dac54b0..b2e9ee1 100644 --- a/tests/test_httpx_adapters.py +++ b/tests/test_httpx_adapters.py @@ -1019,3 +1019,59 @@ def handle(request: httpx.Request) -> httpx.Response: if stop: assert error.request is sent[0] assert error.response.request is sent[0] + + +@pytest.mark.parametrize("stage", ["request", "send", "response"]) +@pytest.mark.parametrize("cancel", [False, True]) +async def test_unchanged_failures_preserve_their_explicit_cause(stage, cancel): + cause = ValueError("application cause") + failure = RequestCancellationError("stopped") if cancel else RuntimeError("failed") + + async def request_adapter(request): + if stage == "request": + raise failure from cause + return request + + async def respond(request): + if stage == "send": + raise failure from cause + return httpx.Response(200) + + async def response_adapter(response, request): + raise failure from cause + + async with ( + httpx.AsyncClient(base_url="https://example.test", transport=httpx.MockTransport(respond)) as client, + HttpxTransport(client, request_adapter=request_adapter, response_adapter=response_adapter) as transport, + ): + with pytest.raises(type(failure)) as caught: + await transport.execute_request(RequestSpec("GET", "/value")) + assert caught.value is failure + assert caught.value.__cause__ is cause + + +@pytest.mark.parametrize("method", ["GET", "POST"]) +@pytest.mark.parametrize("status", [200, 401, 403]) +@pytest.mark.parametrize( + "challenge", ["Bearer error=invalid_token", "Basic error=invalid_token", "Bearer error=insufficient_scope"] +) +async def test_explicit_bearer_rejection_policy_preserves_bodies(method, status, challenge): + from sunday.httpx import BearerTokenRejectionAdapter + + request = httpx.Request( + method, "https://example.test", headers={"Authorization": "Bearer fixture"}, content=b"request" + ) + body = Body() + response = httpx.Response(status, headers={"WWW-Authenticate": challenge}, stream=body) + adapter = BearerTokenRejectionAdapter() + if status == 401 and challenge == "Bearer error=invalid_token": + for _ in range(2): + with pytest.raises(RequestCancellationError): + await adapter.adapt(response, request) + else: + assert await adapter.adapt(response, request) is response + del request.headers["Authorization"] + assert await adapter.adapt(response, request) is response + assert request.content == b"request" + assert body.reads == 0 + await response.aclose() From 4a8e9032b96a33d2e4f4bc880e786c7ae6b21e7d Mon Sep 17 00:00:00 2001 From: Kevin Wooten Date: Tue, 10 Nov 2026 16:33:18 -0800 Subject: [PATCH 4/6] Type regression tests under full CI checks --- tests/test_httpx_adapters.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/test_httpx_adapters.py b/tests/test_httpx_adapters.py index b2e9ee1..1d8d010 100644 --- a/tests/test_httpx_adapters.py +++ b/tests/test_httpx_adapters.py @@ -1023,21 +1023,21 @@ def handle(request: httpx.Request) -> httpx.Response: @pytest.mark.parametrize("stage", ["request", "send", "response"]) @pytest.mark.parametrize("cancel", [False, True]) -async def test_unchanged_failures_preserve_their_explicit_cause(stage, cancel): +async def test_unchanged_failures_preserve_their_explicit_cause(stage: str, cancel: bool) -> None: cause = ValueError("application cause") failure = RequestCancellationError("stopped") if cancel else RuntimeError("failed") - async def request_adapter(request): + async def request_adapter(request: httpx.Request) -> httpx.Request: if stage == "request": raise failure from cause return request - async def respond(request): + async def respond(request: httpx.Request) -> httpx.Response: if stage == "send": raise failure from cause return httpx.Response(200) - async def response_adapter(response, request): + async def response_adapter(response: httpx.Response, request: httpx.Request) -> httpx.Response: raise failure from cause async with ( @@ -1055,7 +1055,7 @@ async def response_adapter(response, request): @pytest.mark.parametrize( "challenge", ["Bearer error=invalid_token", "Basic error=invalid_token", "Bearer error=insufficient_scope"] ) -async def test_explicit_bearer_rejection_policy_preserves_bodies(method, status, challenge): +async def test_explicit_bearer_rejection_policy_preserves_bodies(method: str, status: int, challenge: str) -> None: from sunday.httpx import BearerTokenRejectionAdapter request = httpx.Request( From a776db144a4f9581b9ea39e4d757c1b28c8ff5b0 Mon Sep 17 00:00:00 2001 From: Kevin Wooten Date: Wed, 11 Nov 2026 06:56:38 -0800 Subject: [PATCH 5/6] Compose standard authentication explicitly for generated clients --- README.md | 43 ++++++- src/sunday/httpx/__init__.py | 2 + src/sunday/httpx/authentication_adapter.py | 7 +- .../httpx/standard_authentication_adapter.py | 43 +++++++ tests/test_standard_authentication.py | 106 ++++++++++++++++++ 5 files changed, 198 insertions(+), 3 deletions(-) create mode 100644 src/sunday/httpx/standard_authentication_adapter.py create mode 100644 tests/test_standard_authentication.py diff --git a/README.md b/README.md index 51267d8..1f90f4f 100644 --- a/README.md +++ b/README.md @@ -288,6 +288,47 @@ is a typed, copyable, picklable singleton; it is omitted from JSON Schema and se field configuration above. A literal string `"UNSET"` remains an ordinary string value. Keep the `default_factory` and `exclude_if` configuration when defining patch models manually. +## Explicit standard authentication + +Choose standard authentication once in the transport factory supplied to generated clients. +`StandardAuthenticationAdapter` composes credential attachment, missing-provider checks, rejection +feedback, and terminal bearer-rejection cancellation. It delegates to the existing adapters, including +their body ownership rules, and ignores public/detached operation responses. Feedback runs before +cancellation. There is no hidden replay; a later explicit request can obtain renewed credentials. + +The standard settings helper selects this policy on both sides. Lower-level `AuthenticationAdapter` +remains available when an application wants feedback without the standard stop policy. Ordinary +transport constructors perform no authentication and do not install this composition. + +```python +from sunday.httpx import HttpxTransport, transport_from_settings + +# Keep the HTTPX client open for the lifetime of the generated clients. +async with httpx.AsyncClient(base_url=base_url) as client: + def standard_factory(settings): + return transport_from_settings(settings, client) + + # Pass standard_factory to the generated configuration-based factory, + # or construct a generated service with this caller-owned transport: + custom_transport = HttpxTransport( + client, request_adapter=auth0_link, response_adapter=auth0_link, + ) +``` + +Caching is a separate explicit choice: construct `TokenManager` around a Sunday OAuth provider and +supply that manager through provider credentials to the generated factory. This retains expiry renewal, +refresh rotation, and application-selected storage. A provider returned by an OAuth credential factory +can likewise be an explicitly constructed manager. Supplied external providers are used unchanged; +standard composition never wraps them, creates a second cache, closes them, or clears their storage. +Keep managers at application/session scope, share them across clients using the same credential lifecycle, +and settle outstanding requests before closing managers or clearing credentials. + +Static bearer, basic, and API-key credentials use their declared placement without an OAuth cache. +Only an explicit Bearer `invalid_token` challenge for a sent bearer credential invokes the bearer stop +policy; 403s and unrelated challenges retain ordinary response handling. Authentication selection and +credential validation in generated settings remain active for the standard path. The direct-transport +path lets a custom adapter own those choices using operation metadata. + ## Application-owned token lifecycle Transport constructors perform no authentication or authorization by default. They accept request and response @@ -307,7 +348,7 @@ recovery policy, and a cancellation-marked error always stops the exchange, retr An external framework (for example Auth0) remains responsible for storage, renewal and logout. Return only its access token and optional expiry; keep its refresh token inside that framework. -The provider-settings convenience `transport_from_settings(...)` explicitly installs provider adapters. +The provider-settings convenience `transport_from_settings(...)` explicitly installs the standard authentication composition. Use the ordinary transport constructor with your own adapters when you want to own the exchange entirely. For Sunday's caching and refresh lifecycle, explicitly supply a `TokenManager` as the provider: diff --git a/src/sunday/httpx/__init__.py b/src/sunday/httpx/__init__.py index b19bb2d..bac0ab5 100644 --- a/src/sunday/httpx/__init__.py +++ b/src/sunday/httpx/__init__.py @@ -24,6 +24,7 @@ from .request_adapter import RequestAdapter, RequestAdapters from .request_security_bindings import request_security_bindings from .response_adapter import ResponseAdapter, ResponseAdapters + from .standard_authentication_adapter import StandardAuthenticationAdapter except ModuleNotFoundError as error: if error.name not in {"anyio", "httpx"}: raise @@ -44,6 +45,7 @@ "RequestAdapters", "ResponseAdapter", "ResponseAdapters", + "StandardAuthenticationAdapter", "authentication_adapters", "copy_request", "request_security_bindings", diff --git a/src/sunday/httpx/authentication_adapter.py b/src/sunday/httpx/authentication_adapter.py index 87d3354..4e6e418 100644 --- a/src/sunday/httpx/authentication_adapter.py +++ b/src/sunday/httpx/authentication_adapter.py @@ -92,9 +92,12 @@ def authentication_adapters( def transport_from_settings(settings: ClientSettings, client: httpx.AsyncClient) -> "HttpxTransport": - """Compose provider adapters from client settings using a caller-owned HTTPX client.""" + """Select standard attachment, rejection feedback, and cancellation using caller-owned providers/client.""" from ._transport import HttpxTransport if str(client.base_url).rstrip("/") != str(httpx.URL(settings.base_url)).rstrip("/"): raise ValueError("HTTPX client base URL must match resolved settings") - return HttpxTransport(client, **authentication_adapters(settings.token_providers)) + from .standard_authentication_adapter import StandardAuthenticationAdapter + + authentication = StandardAuthenticationAdapter(settings.token_providers) + return HttpxTransport(client, request_adapter=authentication, response_adapter=authentication) diff --git a/src/sunday/httpx/standard_authentication_adapter.py b/src/sunday/httpx/standard_authentication_adapter.py new file mode 100644 index 0000000..3ad87a5 --- /dev/null +++ b/src/sunday/httpx/standard_authentication_adapter.py @@ -0,0 +1,43 @@ +"""Explicit standard authentication policy, composed outside transport execution.""" + +from collections.abc import Mapping +from typing import overload + +import httpx + +from ..token_provider import TokenProvider +from .authentication_adapter import AuthenticationAdapter +from .bearer_token_rejection_adapter import BearerTokenRejectionAdapter +from .request_security_bindings import request_security_bindings +from .response_adapter import ResponseAdapters + + +class StandardAuthenticationAdapter: + """Attach credentials, report rejection, and cancel rejected bearer exchanges without replay. + + Supplied providers retain lifecycle ownership. Supply TokenManager explicitly for caching and refresh. + Install the same instance in both request and response slots. + """ + + def __init__(self, providers: Mapping[str, TokenProvider]) -> None: + """Compose policy without acquiring, wrapping, or taking ownership of providers.""" + self._authentication = AuthenticationAdapter(providers) + self._responses = ResponseAdapters(self._authentication, BearerTokenRejectionAdapter()) + + @overload + async def __call__(self, value: httpx.Request) -> httpx.Request: ... + + @overload + async def __call__(self, value: httpx.Response, request: httpx.Request) -> httpx.Response: ... + + async def __call__( + self, value: httpx.Request | httpx.Response, request: httpx.Request | None = None + ) -> httpx.Request | httpx.Response: + """Leave unrelated responses and all bodies untouched; feedback precedes cancellation.""" + if request is None: + assert isinstance(value, httpx.Request) + return await self._authentication(value) + assert isinstance(value, httpx.Response) + if not request_security_bindings(request): + return value + return await self._responses.adapt(value, request) diff --git a/tests/test_standard_authentication.py b/tests/test_standard_authentication.py new file mode 100644 index 0000000..2a9129a --- /dev/null +++ b/tests/test_standard_authentication.py @@ -0,0 +1,106 @@ +"""Standard settings composition and custom adapters share generated operation contracts.""" + +import httpx +import pytest + +from sunday import ( + ClientSettings, + ProviderCredentials, + RequestCancellationError, + RequestSpec, + SecurityBinding, + SecurityTransport, + TokenConfiguration, + TokenManager, + TokenRequest, + TokenSet, +) +from sunday.httpx import HttpxTransport, StandardAuthenticationAdapter, transport_from_settings + +pytestmark = pytest.mark.anyio +BINDING = SecurityBinding( + scheme="identity", + provider="identity", + flow="clientCredentials", + transport=SecurityTransport(location="header", name="Authorization", prefix="Bearer"), +) +SPEC: RequestSpec[None] = RequestSpec("GET", "/value", security=(BINDING,)) + + +async def test_generated_settings_standard_expiry_and_rejection() -> None: + now = 1000.0 + acquired = refreshed = sent = 0 + rejecting = False + + class Provider: + identity = "fixture" + + def configure(self, binding: SecurityBinding) -> TokenConfiguration: + return TokenConfiguration("client") + + async def acquire(self, request: TokenRequest) -> TokenSet: + nonlocal acquired + acquired += 1 + return TokenSet("initial", expires_at=now + 100, refresh_token="r1") + + async def refresh(self, request: TokenRequest, refresh_token: str) -> TokenSet: + nonlocal refreshed + refreshed += 1 + return TokenSet(f"renewed-{refreshed}", expires_at=now + 100, refresh_token="r2") + + def respond(request: httpx.Request) -> httpx.Response: + nonlocal sent + sent += 1 + assert request.headers["Authorization"].startswith("Bearer ") + return httpx.Response(401 if rejecting else 204, headers={"WWW-Authenticate": "Bearer error=invalid_token"}) + + manager = TokenManager(Provider(), now=lambda: now, expiry_skew=0) + settings = ClientSettings.resolve( + "https://example.test", {"read": [[BINDING]]}, {"identity": ProviderCredentials(manager)} + ) + assert settings.token_providers["identity"] is manager + async with ( + httpx.AsyncClient(base_url=settings.base_url, transport=httpx.MockTransport(respond)) as client, + transport_from_settings(settings, client) as transport, + ): + assert acquired == 0 + await transport.execute_request(SPEC) + await transport.execute_request(SPEC) + now += 101 + await transport.execute_request(SPEC) + assert (acquired, refreshed) == (1, 1) + rejecting = True + with pytest.raises(RequestCancellationError): + await transport.execute_request(SPEC) + assert sent == 4 + rejecting = False + await transport.execute_request(SPEC) + assert refreshed == 2 + + +async def test_same_generated_operation_custom_plain_and_explicit_missing_policy() -> None: + sent: list[str] = [] + calls = 0 + + def respond(request: httpx.Request) -> httpx.Response: + sent.append(request.headers.get("Authorization", "")) + return httpx.Response(204) + + async def custom(request: httpx.Request) -> httpx.Request: + nonlocal calls + calls += 1 + request.headers["Authorization"] = "Custom credential" + return request + + async with httpx.AsyncClient(base_url="https://example.test", transport=httpx.MockTransport(respond)) as client: + async with HttpxTransport(client, request_adapter=custom) as direct: + await direct.execute_request(SPEC) + async with HttpxTransport(client) as plain: + await plain.execute_request(SPEC) + authentication = StandardAuthenticationAdapter({}) + async with HttpxTransport(client, request_adapter=authentication, response_adapter=authentication) as missing: + with pytest.raises(RequestCancellationError): + await missing.execute_request(SPEC) + await missing.execute_request(RequestSpec("GET", "/value")) + assert calls == 1 + assert sent == ["Custom credential", "", ""] From f02275f38d047ace4eb913cbbccbdbf76ab70df5 Mon Sep 17 00:00:00 2001 From: Kevin Wooten Date: Wed, 11 Nov 2026 07:30:56 -0800 Subject: [PATCH 6/6] Preserve explicit rejection policy and private adapter state --- src/sunday/httpx/_diagnostics.py | 5 +- src/sunday/httpx/_request_context.py | 18 ++++ src/sunday/httpx/_sse.py | 3 + src/sunday/httpx/_transport.py | 3 +- src/sunday/httpx/authentication_adapter.py | 7 +- .../httpx/standard_authentication_adapter.py | 10 +- tests/test_httpx_security.py | 96 +++++++++++++++++++ tests/test_standard_authentication.py | 46 +++++++++ 8 files changed, 180 insertions(+), 8 deletions(-) create mode 100644 src/sunday/httpx/_request_context.py diff --git a/src/sunday/httpx/_diagnostics.py b/src/sunday/httpx/_diagnostics.py index baf2b14..09af55f 100644 --- a/src/sunday/httpx/_diagnostics.py +++ b/src/sunday/httpx/_diagnostics.py @@ -3,6 +3,7 @@ import httpx from ..request_cancellation_error import RequestCancellationError +from ._request_context import clear_request_context from ._requests import copy_request from .request_security_bindings import request_security_bindings @@ -10,8 +11,6 @@ def diagnostic_request(request: httpx.Request) -> httpx.Request: """Remove sensitive values from native response and failure diagnostics.""" bindings = request_security_bindings(request) - if not bindings: - return request url, headers = request.url, httpx.Headers(request.headers) for binding in bindings: transport = binding.transport @@ -21,7 +20,7 @@ def diagnostic_request(request: httpx.Request) -> httpx.Request: headers[transport.name] = "[redacted]" else: headers["cookie"] = "[redacted]" - return copy_request(request, url=url, headers=headers) + return clear_request_context(copy_request(request, url=url, headers=headers)) def diagnostic_error(error: BaseException, request: httpx.Request) -> BaseException: diff --git a/src/sunday/httpx/_request_context.py b/src/sunday/httpx/_request_context.py new file mode 100644 index 0000000..3737c1f --- /dev/null +++ b/src/sunday/httpx/_request_context.py @@ -0,0 +1,18 @@ +"""Private adapter state retained only during a managed exchange.""" + +from typing import cast + +import httpx + +_KEY = "sunday.request_context" + + +def request_context(request: httpx.Request) -> dict[object, object]: + """Share adapter receipts through native request copies within an exchange.""" + return cast(dict[object, object], request.extensions.setdefault(_KEY, {})) + + +def clear_request_context(request: httpx.Request) -> httpx.Request: + """Detach private adapter state without altering native extensions or shared copies.""" + request.extensions.pop(_KEY, None) + return request diff --git a/src/sunday/httpx/_sse.py b/src/sunday/httpx/_sse.py index 55f500c..4be1cf8 100644 --- a/src/sunday/httpx/_sse.py +++ b/src/sunday/httpx/_sse.py @@ -28,6 +28,7 @@ from ._async import complete, run_io from ._reconnect import _ReconnectPolicy from ._response_cleanup import close_response, in_response_cleanup +from .request_security_bindings import _set_request_security_bindings if TYPE_CHECKING: from ._transport import HttpxEventSourceRequestFactory, HttpxTransport @@ -186,6 +187,8 @@ async def events(self) -> AsyncGenerator[EventT, None]: else: request_value = self._request_factory(tuple(headers)) request = await request_value if inspect.isawaitable(request_value) else request_value + if self._spec.security is not None: + _set_request_security_bindings(request, self._spec.security) self._disable_httpx_read_timeout(request) response = await self._transport._send_event_stream( request, diff --git a/src/sunday/httpx/_transport.py b/src/sunday/httpx/_transport.py index 45e5233..5f2818b 100644 --- a/src/sunday/httpx/_transport.py +++ b/src/sunday/httpx/_transport.py @@ -35,6 +35,7 @@ from ..uri import URITemplate from ._async import complete, run_io from ._diagnostics import diagnostic_error, diagnostic_request +from ._request_context import clear_request_context from ._requests import BodyStream, copy_request, is_credentialed, redirect_request from ._response_cleanup import close_response, protect_response from .request_adapter import RequestAdapterLike, RequestAdapters @@ -106,7 +107,7 @@ def register_problem(self, type_uri: str, problem_type: type[Problem]) -> None: async def transport_request(self, spec: RequestSpec[Any]) -> httpx.Request: """Materialize an optionally authorized request, handing its lifecycle to the consumer.""" request = await self._prepare_request(spec) - return _set_request_security_bindings(await self._request_adapter.adapt(request), ()) + return clear_request_context(_set_request_security_bindings(await self._request_adapter.adapt(request), ())) async def _prepare_request(self, spec: RequestSpec[Any]) -> httpx.Request: """Build without adapting; execution and export each own their adaptation step.""" diff --git a/src/sunday/httpx/authentication_adapter.py b/src/sunday/httpx/authentication_adapter.py index 4e6e418..c41d85e 100644 --- a/src/sunday/httpx/authentication_adapter.py +++ b/src/sunday/httpx/authentication_adapter.py @@ -12,6 +12,7 @@ from ..request_cancellation_error import RequestCancellationError from ..token_provider import TokenProvider, TokenProviderError, TokenRejectedError +from ._request_context import request_context from ._security import RequestSecurity from .request_adapter import RequestAdapterLike, RequestAdapters from .request_security_bindings import request_security_bindings @@ -27,7 +28,7 @@ class AuthenticationAdapter: def __init__(self, providers: Mapping[str, TokenProvider]) -> None: self._providers = dict(providers) - self._receipt = f"sunday.authentication.{id(self)}" + self._receipt = object() @overload async def __call__(self, value: httpx.Request) -> httpx.Request: ... @@ -42,7 +43,7 @@ async def __call__( if request is not None: assert isinstance(value, httpx.Response) security = ( - cast(RequestSecurity | None, request.extensions.get(self._receipt)) + cast(RequestSecurity | None, request_context(request).get(self._receipt)) if request_security_bindings(request) else None ) @@ -63,7 +64,7 @@ async def __call__( if not bindings: return value try: - value.extensions[self._receipt] = await RequestSecurity(bindings).authorize(value, self._providers) + request_context(value)[self._receipt] = await RequestSecurity(bindings).authorize(value, self._providers) except TokenProviderError as error: if error.reason != "temporary": raise RequestCancellationError(str(error)) from error diff --git a/src/sunday/httpx/standard_authentication_adapter.py b/src/sunday/httpx/standard_authentication_adapter.py index 3ad87a5..fab38bd 100644 --- a/src/sunday/httpx/standard_authentication_adapter.py +++ b/src/sunday/httpx/standard_authentication_adapter.py @@ -5,6 +5,7 @@ import httpx +from ..request_cancellation_error import RequestCancellationError from ..token_provider import TokenProvider from .authentication_adapter import AuthenticationAdapter from .bearer_token_rejection_adapter import BearerTokenRejectionAdapter @@ -40,4 +41,11 @@ async def __call__( assert isinstance(value, httpx.Response) if not request_security_bindings(request): return value - return await self._responses.adapt(value, request) + try: + return await self._responses.adapt(value, request) + except RequestCancellationError: + raise + except Exception: + # Feedback failure must not bypass the explicitly selected stop policy. + await BearerTokenRejectionAdapter().adapt(value, request) + raise diff --git a/tests/test_httpx_security.py b/tests/test_httpx_security.py index 2eda018..8f9697f 100644 --- a/tests/test_httpx_security.py +++ b/tests/test_httpx_security.py @@ -479,3 +479,99 @@ async def __aiter__(self) -> AsyncIterator[bytes]: await transport.execute_request(RequestSpec("GET", "/value", security=(BINDING,))) assert "private-provider-detail" not in str(failure.value) assert response.is_closed + + +@pytest.mark.anyio +@pytest.mark.parametrize("outcome", ["response", "request_error", "status_error"]) +async def test_private_receipts_do_not_escape_export_or_diagnostics(outcome: str) -> None: + manager = TokenManager(Provider()) + spec: RequestSpec[None] = RequestSpec("GET", "/value", security=(BINDING,)) + sent: list[httpx.Request] = [] + + def handle(request: httpx.Request) -> httpx.Response: + sent.append(request) + assert "sunday.request_context" in request.extensions + if outcome == "request_error": + raise httpx.ConnectError("offline", request=request) + if outcome == "status_error": + response = httpx.Response(500, request=request) + raise httpx.HTTPStatusError("failed", request=request, response=response) + return httpx.Response(204) + + async with httpx.AsyncClient(base_url="https://api.example", transport=httpx.MockTransport(handle)) as client: + transport = HttpxTransport(client, **authentication_adapters({"identity": manager})) + exported = await transport.transport_request(spec) + assert set(exported.extensions) == {"timeout"} + assert exported.headers["authorization"] == "Bearer access-1" + if outcome == "response": + diagnostic = (await transport.execute_request(spec)).request + else: + with pytest.raises(httpx.HTTPError) as caught: + await transport.execute_request(spec) + diagnostic = caught.value.request + assert diagnostic.headers["authorization"] == "[redacted]" + assert set(diagnostic.extensions) == {"timeout", "sunday.security_bindings"} + assert "sunday.request_context" in sent[0].extensions + + +@pytest.mark.anyio +@pytest.mark.parametrize("kind", ["stream", "source"]) +@pytest.mark.parametrize("configured", [False, True]) +@pytest.mark.parametrize("factory_bindings", [False, True]) +async def test_factory_event_requests_receive_operation_bindings( + kind: str, configured: bool, factory_bindings: bool +) -> None: + import asyncio + + import anyio + + from sunday import EventSourceState, EventStreamOptions + from sunday.httpx import ( + HttpxEventSource, + HttpxEventStream, + StandardAuthenticationAdapter, + request_security_bindings, + ) + from sunday.httpx.request_security_bindings import _set_request_security_bindings + + provider = Provider() + sent: list[httpx.Request] = [] + spec: RequestSpec[None] = RequestSpec("GET", "/value", security=None if factory_bindings else (BINDING,)) + + def handle(request: httpx.Request) -> httpx.Response: + sent.append(request) + assert request_security_bindings(request) == (BINDING,) + assert request.headers["authorization"] == "Bearer access-1" + return httpx.Response(204) + + async with httpx.AsyncClient(base_url="https://api.example", transport=httpx.MockTransport(handle)) as client: + adapter = StandardAuthenticationAdapter({"identity": provider} if configured else {}) + transport = HttpxTransport(client, request_adapter=adapter, response_adapter=adapter) + + async def factory(headers: tuple[tuple[str, str], ...]) -> httpx.Request: + request = client.build_request("GET", "/value", headers=headers) + return _set_request_security_bindings(request, (BINDING,)) if factory_bindings else request + + with anyio.fail_after(2): + if kind == "stream": + stream: HttpxEventStream[None] = HttpxEventStream( + transport, spec, lambda _: None, request_factory=factory, options=EventStreamOptions(retry=0) + ) + if configured: + assert [event async for event in stream] == [] + else: + with pytest.raises(RequestCancellationError): + _ = [event async for event in stream] + else: + errors: list[BaseException | None] = [] + source = HttpxEventSource(transport, factory, spec=spec, options=EventStreamOptions(retry=0)) + source.on_error = errors.append + source.connect() + while source.ready_state is not EventSourceState.CLOSED: + await asyncio.sleep(0) + source.close() + await source._wait_closed() + assert len(errors) == (0 if configured else 1) + if errors: + assert isinstance(errors[0], RequestCancellationError) + assert len(sent) == (1 if configured else 0) diff --git a/tests/test_standard_authentication.py b/tests/test_standard_authentication.py index 2a9129a..1a41bd2 100644 --- a/tests/test_standard_authentication.py +++ b/tests/test_standard_authentication.py @@ -1,10 +1,12 @@ """Standard settings composition and custom adapters share generated operation contracts.""" +import anyio import httpx import pytest from sunday import ( ClientSettings, + EventStreamOptions, ProviderCredentials, RequestCancellationError, RequestSpec, @@ -12,6 +14,7 @@ SecurityTransport, TokenConfiguration, TokenManager, + TokenProviderError, TokenRequest, TokenSet, ) @@ -104,3 +107,46 @@ async def custom(request: httpx.Request) -> httpx.Request: await missing.execute_request(RequestSpec("GET", "/value")) assert calls == 1 assert sent == ["Custom credential", "", ""] + + +@pytest.mark.parametrize("cancel", [False, True]) +async def test_feedback_failure_still_stops_event_stream(cancel: bool) -> None: + failure = RequestCancellationError("provider stop") if cancel else TokenProviderError("temporary") + rejections = sent = 0 + fail_acquisition = False + + class Provider: + identity = "feedback" + + def configure(self, binding: SecurityBinding) -> TokenConfiguration: + return TokenConfiguration("client") + + async def acquire(self, request: TokenRequest) -> TokenSet: + if fail_acquisition: + raise TokenProviderError("temporary") + return TokenSet("access") + + async def reject(self, request: TokenRequest, rejected_token: str) -> bool: + nonlocal rejections + rejections += 1 + raise failure + + def respond(request: httpx.Request) -> httpx.Response: + nonlocal sent + sent += 1 + return httpx.Response(401, headers={"WWW-Authenticate": "Bearer error=invalid_token"}) + + authentication = StandardAuthenticationAdapter({"identity": Provider()}) + async with httpx.AsyncClient(base_url="https://example.test", transport=httpx.MockTransport(respond)) as client: + transport = HttpxTransport(client, request_adapter=authentication, response_adapter=authentication) + with anyio.fail_after(2), pytest.raises(RequestCancellationError) as caught: + async for _ in transport.event_stream(SPEC, lambda event: event, options=EventStreamOptions(retry=0)): + pytest.fail("Rejected stream must not emit") + if cancel: + assert caught.value is failure + assert sent == rejections == 1 + fail_acquisition = True + with pytest.raises(httpx.TransportError) as temporary: + await transport.execute_request(SPEC) + assert not isinstance(temporary.value, RequestCancellationError) + assert sent == 1