Auth
Composable authentication for applications, HTTP clients and token keepers.
Settings supply values; this package never reads Doppler, environment files or
application configuration repositories. There is one operation-report type: AuthResult.
Install
common-auth: contracts/configs, credential resolution, memory custody, static verification, TOTP and provider-session coordination.common-auth[http]:common-httprequest authentication, OAuth grants/login and remote keeper reads.common-auth[crypto]: asymmetric signatures and AES-GCM protection.common-auth[postgres]: encrypted PostgreSQL custody and credential sources.common-auth[all]: all of these.
The HTTP integration requires common-http>=0.2,<0.3 and its prepared-request
auth-flow contract (HttpAuth.flow(request, *, prepare)). Importing an HTTP-backed
surface without the extra raises an error naming common-auth[http].
Simple HTTP authentication
from common_auth import Authenticatorfrom common_http import HttpClient
# api_key comes from your existing settings object.auth = Authenticator.api_key( api_key, name="X-API-Key", allowed_origins=("https://api.example.com",))async with HttpClient(auth=auth) as http: result = await http.get("https://api.example.com/items")Authenticator.basic(username, password, allowed_origins=...) and
Authenticator.bearer(token_or_source, allowed_origins=...) use the same
construction path. Origins are explicit to prevent credential forwarding to an
unrelated destination. Redirects remain HTTP’s responsibility. HMAC and signed
JWT variants take a provider-specific profile that receives the prepared
request and Signer; payload bytes and current managed cookies are available
before signing. Profiles supply the provider’s canonicalization, not another
HTTP transport.
Bearer challenge replay defaults to zero. Opt in with max_challenge_replays=1
only when the consumer permits it. A recognized invalid_token challenge asks
the source for a replacement once; unchanged credentials are not replayed.
Keeper acquisition and client reads
from common_auth import ( ConnectionRef, Grant, GrantConfig, GrantRef, ManagedTokenConfig, ManagedTokens, Store, StoredTokens,)
ref = GrantRef( connection=ConnectionRef(namespace="production", name="broker-account"), grant_id="primary",)grant_config = GrantConfig.model_validate( { "grant_type": "client_credentials", "issuer": "https://identity.example.com", "token_url": "https://identity.example.com/token", "client": { "method": "client_secret_basic", "client_id": client_id, "credential": { "credential": { "kind": "client_secret", "client_id": client_id, "client_secret": client_secret, } }, }, })policy = ManagedTokenConfig(grant=ref)async with Store.memory() as store, Grant(grant_config) as grant: keeper = ManagedTokens(policy, store=store, grant=grant) access = (await keeper.get()).unwrap() reader = StoredTokens(policy, store=store) auth = Authenticator.bearer(reader, allowed_origins=("https://api.example.com",))Use refresh_token grant configuration for refresh-token keepers. A grant
exchange returns (AccessToken, RefreshToken | None) inside AuthResult; omission
means no replacement refresh token. A replacement’s expiry comes from the response
member refresh_lifetime_field names, refresh_token_expires_in by default; set it
for an issuer that spells it its own way (Intuit: x_refresh_token_expires_in).
The keeper retains the existing refresh credential before saving the complete
TokenSet. Authorization-code acquisition is an explicit login operation, not
something a read-only client can trigger.
StoredTokens has no acquisition or publication methods.
get(audience=..., scopes=..., proof_key=...) verifies requested bindings. Unknown
expiry is rejected unless policy explicitly bounds age using an original known
issuance/acquisition time. A cache never resets that time. cache_ttl_sec=0
(the default) reads authoritative state; a positive TTL deliberately permits
bounded stale observations between processes.
The keeper coordinates by the full namespace/connection/grant key. A durable
pending marker is committed before an issuer exchange. Another owner waits
for the active guard and rereads the committed result. A crash, cancellation or
uncertain exchange leaves an unknown result, preventing unsafe refresh/code replay.
Replayable client-credentials acquisition can recover on a later lookup; callers
already waiting on the failed acquisition share its unknown outcome.
For rotating credentials, after explicit provider/operator recovery, keeper.publish(snapshot, expected_revision=observed_revision) conditionally restores usable custody.
No background scheduler or second retry framework is created. HTTP owns execution;
code/refresh exchanges and private-key JWT client authentication force one attempt
even when general HTTP retries are enabled. A later client-credentials acquisition
creates a fresh assertion instead of replaying a consumed JWT identifier.
PostgreSQL and credential references
from common_auth import AesGcmProtector, Store, StoredCredentials
# settings.token_dsn and settings.auth_encryption_key are injected by the app.# The AES key is decoded key bytes (16, 24 or 32 bytes), not an arbitrary password.async with Store.postgres( connection={"dsn": settings.token_dsn}, schema_name="common_auth", protector=AesGcmProtector(settings.auth_encryption_key),) as store: await store.initialize() # explicit installation step; reads never create tables credentials = StoredCredentials(store)Native PostgreSQL DSNs and the existing postgresql+psycopg:// settings form are
accepted. An injected async pool stays caller-owned. Store connections are bound
to their opening event loop. Create separate collaborators for gateway keeper/API
loops or give both one owner; do not share one async client across threads.
PostgreSQL stores encrypted secret payloads in its own auth_records_v1 table, using
context-bound AES-GCM by default when that protector is supplied. Pass another
Protector for an existing application encryption system. Keys still arrive
through current settings. This does not rewrite the legacy vendor-keyed token
table; existing records require explicit migration to named GrantRef lineages.
StoredCredentials.get(CredentialRef(...)) implements the source port consumed by
CredentialResolver. put(ref, credential, expected_revision=..., expires_at=...)
uses the same encrypted custody and revision checks. A named version is immutable;
version=None is a separate explicit current record. Publishing a named version
does not silently change the current record. Conditional delete(ref, expected_revision=...)
revokes either record while retaining its revision tombstone. Direct supplied credentials require
no store. Reference sources are injected and borrowed.
Remote market-gateway consumers
from common_auth import KeeperTokenDecoder, RemoteTokenConfig, RemoteTokens, TokenBindingfrom common_http import Endpoint
source = RemoteTokens( RemoteTokenConfig(grant=ref, endpoint=Endpoint(name="token", url=keeper_url)), decoder=KeeperTokenDecoder( vendor="schwab", scheme="oauth2_refresh", kind="access", binding=TokenBinding(issuer=issuer, client_id=client_id), ),)async with source: auth = Authenticator.bearer(source, allowed_origins=(resource_origin,))The adapter consumes the existing gateway’s vendor/scheme/kind/value/expires_at
shape and checks its configured identity. For IB’s keeper-issued session token,
use vendor="ib", scheme="jwt_assertion", kind="session". Keeper kind names
the stored product; token_type="Bearer" separately controls HTTP authentication
and is the default for both. IB’s initial client-credentials token and the final
brokerage session token are distinct products; its provider workflow owns that
second exchange. Supply a decoder for a different keeper
protocol. A remote source only reads access credentials; it cannot mint at the
issuer. Inject a separately authenticated HttpClient for the keeper if required.
A borrowed client remains open when the source closes.
Login, sessions and incoming application authentication
OAuthLogin(config, grant=code_grant, store=store) exposes
begin(authorization_ref, caller=trusted_caller) and
complete(callback_url, caller=trusted_caller). Begin succeeds with a protected
redirect URL (begin(...).unwrap()); the authorization stays pending until
completion, which binds caller, target, state, expiry, issuer
when supplied and PKCE. Browser navigation is an application/common-browser step.
Completion consumes state before exchange; replicas cannot submit the code twice.
Registered callback query bytes are preserved. Configuration rejects fields
owned by OAuth completion, such as state, code and error, before login begins.
Completed protected issuance can be recovered by the same caller until login
expiry, then assembled/published explicitly by the keeper. No OIDC identity-token
verification is implied.
A provider that adds its own parameters to the callback, such as Intuit’s realmId
(the company the person connected), declares them in provider_fields.
login.provider_values(callback_url) reads them after the same address, issuer and
duplicate checks, consuming nothing; a declared field the callback lacks is a
rejection. Undeclared parameters stay ignored.
Totp(seed).generate().unwrap() returns a protected code from supplied settings; agenerate()
resolves referenced seeds. Signer(credential, algorithm).sign(bytes) and
.jwt(claims) share key validation and optional asymmetric implementations.
JWT HMAC keys must meet the selected digest size; RSA JWT keys require at least
2048 bits. Generic request HMAC signing retains its provider-specific key policy.
Session(SessionConfig(...), provider=...) coordinates injected async
start/check/stop hooks returning AuthResult[SessionState]. It bounds waits,
serializes operations and retains original health-observation times. Schwab UI
steps and IB brokerage workflows stay in provider code; no browser install is
needed for other auth users.
StaticVerifier(config, source=...).verify(presented) uses constant-time comparison
and returns AuthResult[PrincipalRef]. FastAPI or another application extracts the
presented header and maps rejected/dependency-failed results into its own response
policy. This package does not silently change gateway access controls.
Results, lifecycle and verification
Use .ok, .status, .reason, .reference and .revision for normal handling.
.unwrap() explicitly accesses the operation product or raises the retained
failure. Routine repr excludes values, HTTP evidence and original exceptions;
explicit payload access is not a logging/export interface. HTTP evidence remains
the original HttpResult, without copied retry counters.
Constructors do not connect. Use async context managers for stores, HTTP grants
and remote sources. Injected collaborators are borrowed. Utilities that own no
resources do not invent a close operation. Cancellation propagates; it never
claims an issuer-side operation was rolled back.
Store shutdown stops admitting work before cleanup. Cleanup completes before
caller cancellation propagates; failed teardown stays closed to operations and
can be retried with aclose().
Tests are organized in classes around contracts, configuration and connected
runtime behavior. test_auth_system.py proves keeper/store/client composition;
test_stores_runtime.py includes disposable real PostgreSQL checks. Nothing in
the suite requires user credentials or connects to a user’s database.
Protocol references: OAuth 2.0 and TOTP reference vectors.
The usage notebook contains the executable supplied-key and keeper-to-consumer examples. Edge cases and protocol verification live in the class-based test suite.