Skip to content

Authentication, transports and lifecycle

Authentication belongs to its implementation

HttpClient(auth=...) accepts the exported structural HttpAuth interface. The authenticator owns credentials, signing rules, expiry, refresh coordination, token storage and its handshake step budget. HTTP sends messages, supplies response evidence and releases exchange resources. No PostgreSQL, TOTP or browser dependencies are imported by this integration.

Use the shared authenticator for a supplied token or token source:

from common_auth import Authenticator
from common_http import HttpClient
auth = Authenticator.bearer("example-token", allowed_origins=("https://provider.example",))
http = HttpClient.create(base_url="https://provider.example/", auth=auth)

common-auth[http] supplies API-key, Basic, Bearer and signing schemes through this interface. Stored, managed and remote token sources compose with the same Bearer helper. A custom authenticator can implement HttpAuth for another handshake without introducing a different HTTP client.

Credentials stay out of evidence and logs

Retained evidence records the application message, not the signed one. HttpResult.response.request, every history head and the head yielded by stream() hold the request as the caller built it for that hop: no fields the authenticator added and no jar cookies. The authenticator itself still receives the exact signed exchange it produced, so challenge handling keeps working.

HTTPX logs each request URL at INFO. While an HttpxTransport is open it filters the httpx logger so credential query values print as <redacted>: common provider names (apikey, api_token, access_token, token, key, signature, …) and every query name an authenticator adds. Other parameters keep their exact spelling, so logs stay useful for debugging.

Multi-step flows and signing

The flow yields a Request and receives its response through asend. Ending the flow accepts that response. Yielding another request authorizes another exchange. There is no hardcoded single-401 retry or implicit refresh in HTTP.

requires_body(head) selects responses that must be buffered before the flow continues. Those arrive as HttpResponse with retained bytes, or empty-response semantics when no bytes exist. Buffering obeys max_response_bytes, including when the caller uses streaming. A fresh flow is created per attempt and followed original-origin redirect; concurrent flows need independent handshake state.

Before authentication, transport.prepare freezes the canonical target, headers and encoded body bytes, including multipart boundaries. Auth yields final binary bodies and canonical URLs. This lets body signatures cover bytes actually sent. Authentication follow-ups stay on the original origin. The adapter owns its step limit and shared refresh synchronization; buffered operations also have their configured per-attempt timeout. Refresh/token calls should use a separate unauthenticated client to avoid recursion and pool contention.

The flow receives a synchronous prepare(request) callback. Call it before signing each follow-up, then apply authentication fields and yield the signed request. Preparation refreshes inherited jar cookies, including challenge updates/deletions and path changes, before freezing the wire bytes. Explicit caller Cookie fields retain precedence; authentication-specific Cookie fields are applied after preparation with the other credentials. HTTP does not alter session cookies after signing. Existing adapters must accept the prepare keyword and use it when constructing follow-ups.

On repeated preparation, matching inherited cookie name/value pairs remain jar-managed. Added names and changed values remain authenticator-owned. An identical reassignment cannot distinguish ownership and stays jar-managed.

Per-exchange admission

async def admit(request: Request) -> None:
await limiter.acquire(account="provider-account", cost=1)
http = HttpClient.create(base_url="https://provider.example/", admit=admit)

limiter is supplied by the application’s shared common-rates integration. The hook runs before every physical exchange, including retries, redirects and auth follow-ups. A hook may wait or reject by raising. It does not imply a built-in distributed backend. Separate token-refresh clients need their own admission.

Cookie persistence defaults on. Domain, path, secure and expiry rules control attachment; an explicit Cookie field takes precedence. Set persist_cookies=False to disable the client’s jar. The jar is in memory and cleared when the client closes.

Redirects default off. With follow_redirects=True, max_redirects bounds the chain. POST 301/302 and non-HEAD 303 become GET without a body. 307/308 preserve method/body. Cross-origin redirects forward only Accept, Accept-Language and User-Agent from carried headers, rebuild destination cookies, and disable the original authenticator. Automatic HTTPS downgrade and cross-origin body replay are rejected. Use an explicit new request when a provider requires such a step and the consumer has decided which credentials/body may be sent.

Stream response bytes

import asyncio
from common_http import HttpClient
async with HttpClient.create(base_url="https://provider.example/") as http:
request = http.build_request("/download")
async with asyncio.timeout(120):
async with http.stream(request) as (head, chunks):
if not head.is_success:
raise RuntimeError(f"Download failed: HTTP {head.status}")
async for chunk in chunks:
await sink.write(chunk)

The sink is application-owned. Chunks are HTTP content-decoded bytes. Exiting the context early or cancellation closes the response. Streaming does not create a buffered HttpResult, run automatic retries or apply runner batch/pacing settings. Phase timeouts and per-exchange admission still apply. The client does not enforce the buffered response cap on an ordinary stream; the sink controls total size.

Owned and borrowed resources

The default HTTPX transport is owned by HttpClient and closed with it. Injected transports and authenticators are borrowed. Each client/transport belongs to one asyncio loop and closed instances cannot reopen. Close rejects active logical operations, including retry waits and batches; finish or cancel and await those operations before closing.

import httpx
from common_http import HttpClient, HttpxTransport
async with httpx.AsyncClient() as engine:
transport = HttpxTransport(engine=engine)
try:
async with HttpClient(transport=transport) as http:
result = await http.get("https://provider.example/health")
finally:
await transport.aclose()

Configure pool/TLS/proxy/protocol settings on a borrowed transport/engine itself. Explicit creation overrides are rejected when borrowing. HTTPX engine default headers, query, cookies and auth are not merged into prepared messages. A borrowed engine may still store received cookies in its own jar. Custom native transports must avoid hidden retries if the caller expects one execution owner.

BaseTransport defines lifecycle and one managed exchange. Implement its native open/close/exchange/capability seams for another engine; override prepare when it serializes structured bodies. It never invokes execution runners or batching. See the transport reference.