Skip to content

API reference

Generated reference documentation for each package. The pages are rebuilt and published with this site from main.

Language Reference Generated by
TypeScript TypeScript API TypeDoc
Rust Rust API · docs.rs rustdoc
Go pkg.go.dev Go doc comments
Python below mkdocstrings
Java Java API Javadoc

Build them locally with make docs (per language: make -C <lang> docs).

Python

Grow Codes SDK for OIDC: provider-neutral access-token verification.

from grow_oidc import Verifier verifier = Verifier.from_env() # doctest: +SKIP user = verifier.verify(token) # doctest: +SKIP

PACKAGE_KEY module-attribute

PACKAGE_KEY = 'oidc'

Stack catalog key (value of GROW_SECRETS_PROVIDER / GROW_LOGGING_PROVIDER).

AsyncHttpTransport

Asynchronous transport (one per async client); options as for :class:HttpTransport.

Cancelling the calling task raises :class:CancelledError (an asyncio.CancelledError subclass) so asyncio's cancellation machinery keeps working. Every call after :meth:aclose raises :class:CancelledError ("client is closed").

aclose async

aclose() -> None

Close the connection pool and abort backoff sleeps (idempotent).

request async

request(req: Request) -> Response

Send req with retries; return the response or raise the mapped error.

AsyncOidcClient

Asynchronous OIDC client; use async with or call :meth:aclose.

Cancel a call by cancelling its task: the SDK raises :class:CancelledError, which is also an :class:asyncio.CancelledError.

aclose async

aclose() -> None

Stop watchers/renewers and close connections (idempotent).

AuthUser dataclass

The authenticated user of a verified access token.

has_role

has_role(*roles: str) -> bool

True when the user has at least one of roles (case-insensitive).

AuthenticationError

Bases: OidcError

Credentials missing or rejected (HTTP 401).

BaseConfig dataclass

Common, immutable client settings. Durations are float seconds (timedelta accepted).

Service configs subclass this (@dataclass(frozen=True, repr=False)), override url with the service default, add their own fields (Secret for credentials), extend :meth:_env_values and :meth:validate, and list vendor variables in ENV_VENDOR.

from_env classmethod

from_env(env: Mapping[str, str] | None = None, **overrides: Any) -> _C

Build from the environment, then validate.

Precedence: explicit keyword > GROW_OIDC_<NAME> > vendor variables > default. env defaults to os.environ; pass a dict in tests.

known_secrets

known_secrets() -> list[str]

Revealed values of every :class:Secret field (used to redact error text).

validate

validate() -> _C

Check the common rules; raise :class:ConfigError. Returns self.

CancelToken

Thread-safe cancellation flag passed to sync calls as cancel=.

Cancelling interrupts an in-flight request (the call returns immediately with :class:CancelledError; the abandoned HTTP exchange finishes in the background) and any retry backoff sleep.

cancel

cancel() -> None

Request cancellation (idempotent).

on_cancel

on_cancel(callback: Callable[[], None]) -> Callable[[], None]

Run callback on cancellation (now if already cancelled); returns an unregister.

wait

wait(timeout: float | None = None) -> bool

Block until cancelled or timeout; return whether the token is cancelled.

CancelledError

Bases: OidcError, CancelledError

The caller cancelled the operation (task cancel, :class:CancelToken, client close).

Also an :class:asyncio.CancelledError so asyncio keeps treating the task as cancelled.

ConfigError

Bases: OidcError

Invalid or missing configuration.

ConflictError

Bases: OidcError

Conflict or failed precondition (HTTP 409, 412, CAS mismatch).

DjangoOidcMiddleware

Django middleware: sets request.auth_user (AuthUser or None).

A request without a token passes with auth_user = None (protect views with :func:django_require_roles); an invalid token → 401, IdP unreachable → 503. Add "grow_oidc.integrations.DjangoOidcMiddleware" to MIDDLEWARE.

EnvReader

Reads GROW_<KEY_UPPER>_<NAME> and vendor variables from an injectable mapping.

Every getter returns None when no variable is set (empty strings count as unset). A present but invalid value raises :class:ConfigError that names the variable, never its value.

duration

duration(name: str, vendor_names: Iterable[str] = ()) -> builtins.float | None

Duration in seconds.

lookup

lookup(name: str, vendor_names: Iterable[str] = ()) -> tuple[str, str] | None

Return (variable_name, raw_value) for the first variable that is set.

ErrorCode

Bases: str, Enum

Canonical error codes; the value is the wire form used by the conformance suite.

ErrorInfo dataclass

Passed to Hooks.on_error; error is the (redacted) SDK error.

HealthStatus dataclass

Result of health(); status is ok/degraded/unhealthy/unreachable or a vendor word.

Hooks dataclass

Optional callbacks invoked on every attempt. Exceptions raised by hooks are ignored.

HttpTransport

Synchronous transport (one per client).

Service options (all optional):

  • request_id_headers: vendor request id headers, checked before :data:REQUEST_ID_HEADERS.
  • retry_after_headers: headers read (in order) for the delay a 429/503 response asks for; default ("retry-after",), e.g. ("retry-after", "x-ratelimit-reset"). See :func:retry_after_from_headers.
  • error_mapper: mapper(error, response) returns a service-specific error for an HTTP error response (or None to keep the default). The mapped error is what Hooks.on_error, the retry planner (retry_after) and the caller see; whether a status is retried stays the SPEC rule. Exceptions raised by the mapper are logged and ignored.

Every call after :meth:close raises :class:CancelledError ("client is closed").

close

close() -> None

Close the connection pool and abort backoff sleeps (idempotent).

request

request(req: Request, *, cancel: CancelToken | None = None) -> Response

Send req with retries; return the response or raise the mapped error.

LoggerLike

Bases: Protocol

Structured logger interface accepted in configuration (SPEC Logger).

NotFoundError

Bases: OidcError

Missing record (HTTP 404).

OidcClient

Synchronous OIDC client. Thread-safe; use as a context manager or call :meth:close.

Every I/O method accepts cancel= (a :class:CancelToken) to abort from another thread.

resources property

resources: ResourceRegistry

Background resources (watchers, renewers) stopped by :meth:close.

close

close() -> None

Stop watchers/renewers and close connections (idempotent).

from_env classmethod

from_env(env: Mapping[str, str] | None = None, **overrides: Any) -> OidcClient

Build a client from the GROW_<KEY>_* and vendor environment variables.

health

health(*, cancel: CancelToken | None = None) -> HealthStatus

Unauthenticated health check; never raises for an unhealthy/unreachable service.

ping

ping(*, cancel: CancelToken | None = None) -> float

Authenticated round trip (userinfo with the configured token); latency in ms.

:class:AuthenticationError for a rejected token, :class:UnsupportedError when the provider has no userinfo endpoint.

request

request(req: Request, *, cancel: CancelToken | None = None) -> Response

Send a raw request through the client's transport (retries, hooks, redaction).

server_version

server_version(*, cancel: CancelToken | None = None) -> str

Always :class:UnsupportedError (CancelledError once closed).

OidcConfig dataclass

Bases: BaseConfig

Immutable settings for :class:~grow_oidc.OidcClient.

Common fields (url, timeouts, retry, tls, proxy, headers, user_agent_suffix, hooks, logger) come from :class:BaseConfig. Durations are float seconds; datetime.timedelta is accepted. token accepts a str and is stored as a :class:Secret; repr() never shows it.

Environment (from_env), prefix GROW_OIDC_: URL, TOKEN, CONNECT_TIMEOUT, REQUEST_TIMEOUT, TOTAL_TIMEOUT, MAX_RETRIES, CA_CERT, CLIENT_CERT, CLIENT_KEY, INSECURE_SKIP_VERIFY, PROXY.

validate

validate() -> _C

Common checks plus service rules; raises :class:ConfigError.

OidcMiddleware

Pure ASGI middleware (Starlette, FastAPI, any ASGI app).

Verifies the bearer token of every HTTP request and stores the user in scope["user"] and scope["state"]["user"] (request.user / request.state.user in Starlette). public_paths (exact paths or prefixes ending in *) and optional=True let requests without a token through. Missing/invalid token → 401, IdP unreachable → 503.

PermissionDeniedError

Bases: OidcError

Authenticated but not allowed (HTTP 403).

RateLimitError

Bases: OidcError

Too many requests (HTTP 429); retry_after holds the requested delay when known.

Request dataclass

One logical API call (possibly several attempts).

path is joined to the base URL ({name} style values must already be encoded; use :func:urllib.parse.quote); an absolute http:///https:// URL is used as is (for pagination links the service returns; the default headers, config.headers included, are sent there too, so only pass URLs of the same service). json is encoded when not None; content sends raw bytes. idempotent overrides the method rule; an idempotency_key sends the Idempotency-Key header and marks the request idempotent. raise_for_status=False returns error responses instead of raising (retries still apply). Statuses in allow_status are expected answers (a 404 that carries data, a health endpoint's 503): the response is returned at once, like a success, without retries or on_error.

RequestInfo dataclass

Passed to Hooks.on_request; url and headers are redacted.

ResourceRegistry

Holds :class:Stoppable objects (or plain closers such as handle.shutdown); :meth:stop_all stops each once, ignoring errors.

A client owns one registry and calls :meth:stop_all from close(). After that, :meth:ensure_open and :meth:register with operation= raise :class:CancelledError ("<operation>: client is closed", SPEC 2.4): client-bound entry points that do no request of their own, such as init_tracing or remote_sampler, use them to fail with CANCELLED on a closed client.

ensure_open

ensure_open(operation: str) -> None

Raise :class:CancelledError ("<operation>: client is closed") once closed.

register

register(item: Stoppable | Callable[[], object], *, operation: str | None = None) -> None

Track item; when the registry is already closed the item is stopped now.

With operation a closed registry also raises :class:CancelledError after stopping item, so a resource created while close() runs is never handed to the caller.

Response dataclass

A completed HTTP response (body fully read).

json

json() -> Any

Decode the body as JSON; :class:ValidationError when it is not valid JSON.

ResponseInfo dataclass

Passed to Hooks.on_response; headers are the redacted response headers (rate limit headers and the like stay readable).

RetryPolicy dataclass

Retry settings. Durations are seconds (datetime.timedelta is accepted).

Backoff for retry n (0-based) is full jitter: random(0, min(max_backoff, initial_backoff * multiplier ** n)).

random returns a float in [0, 1); inject it in tests for deterministic sleeps.

max_attempts property

max_attempts: int

Total attempts including the first one.

backoff

backoff(retry: int) -> float

Full-jitter sleep in seconds before retry retry (0-based).

backoff_cap

backoff_cap(retry: int) -> float

Upper bound of the jittered sleep before retry retry (0-based).

Secret

Wraps a credential so it never shows up in str/repr/logs.

s = Secret("hunter2") str(s), s.reveal() ('[REDACTED]', 'hunter2')

reveal

reveal() -> str

Return the wrapped value.

TimeoutError

Bases: OidcError

A connect, request or total deadline was exceeded (also HTTP 408, 504).

TlsConfig dataclass

TLS settings. insecure_skip_verify is for tests only and logs a warning once.

UnavailableError

Bases: OidcError

Network error or server unavailable (HTTP 500, 502, 503).

UnsupportedError

Bases: OidcError

The service or deployment does not offer this capability (HTTP 501, missing API).

ValidationError

Bases: OidcError

Bad input (HTTP 400, 413, 422, other 4xx, client-side validation).

Verifier

Verifies OIDC access tokens (JWT) against the issuer's JWKS. Thread-safe.

Raises :class:AuthenticationError for every invalid token (the message names the failed check, never the token), :class:UnavailableError when discovery or the JWKS cannot be fetched and :class:ConfigError for invalid options. verify is synchronous; averify is the async variant with the same behaviour.

averify async

averify(token: str) -> AuthUser

async variant of :meth:verify.

clear_cache

clear_cache() -> None

Drops the cached JWKS so the next verification refetches it.

from_env classmethod

from_env(env: Mapping[str, str] | None = None, **overrides: Any) -> Verifier

Builds a verifier from GROW_AUTH_* variables; keyword overrides win.

GROW_AUTH_ISSUER (required), GROW_AUTH_AUDIENCE (default GROW_AUTH_CLIENT_ID), GROW_AUTH_JWKS_URL, GROW_AUTH_ROLES_CLAIM (default roles) and GROW_AUTH_CLOCK_SKEW (duration, default 60s).

verify

verify(token: str) -> AuthUser

Verifies a raw JWT access token and returns its user.

verify_request

verify_request(request: Any) -> AuthUser

Verifies the bearer token of a request (AuthenticationError when missing).

apoll_until async

apoll_until(fn: Callable[[], Awaitable[T | None]], *, timeout_s: float = 30.0, interval_s: float = 1.0, predicate: Callable[[T], bool] | None = None, operation: str = 'poll', clock: Callable[[], float] = time.monotonic) -> T

Async :func:poll_until; fn is an async callable.

bearer_token

bearer_token(source: Any) -> str | None

Bearer token of an Authorization header, or None.

source is a header value string, a headers mapping (case-insensitive lookup), or an object with .headers (Starlette/FastAPI/Django/httpx requests).

claim_at

claim_at(claims: Mapping[str, Any], path: str) -> Any

Value at a claim name (roles) or dotted path (realm_access.roles), else None.

An exact top-level match wins, so claim names containing dots keep working.

default_verifier

default_verifier() -> Verifier

The process-wide verifier (Verifier.from_env() on first use).

django_require_roles

django_require_roles(*roles: str) -> Callable[[Callable[..., Any]], Callable[..., Any]]

Django view decorator: 401 without request.auth_user, 403 unless one of roles.

error_for_code

error_for_code(code: ErrorCode | str) -> type[OidcError]

Return the error class for a code (ErrorCode member or wire value).

error_from_status

error_from_status(status: int, operation: str, *, content: bytes = b'', headers: Headers | None = None, known_secrets: list[str] | None = None, retry_after: float | None = None, request_id_headers: Sequence[str] = ()) -> ServiceError

Map an HTTP error status to the SPEC 2.1 error with a redacted, truncated message.

request_id_headers are checked before the default :data:REQUEST_ID_HEADERS.

extract_roles

extract_roles(claims: Mapping[str, Any], roles_claim: str = 'roles') -> list[str]

Role names of the claim at roles_claim.

A string is split on commas and whitespace; a list yields each string, or each object's name (Casdoor), code, role or value; anything else yields []. Duplicates are removed, order is kept.

get_logger

get_logger() -> logging.Logger

The package logger (LOGGER_NAME), silent by default (NullHandler).

has_any_role

has_any_role(user_roles: Iterable[str], required: Iterable[str]) -> bool

True when user_roles has at least one of required (case-insensitive).

An empty required means any authenticated user.

new_idempotency_key

new_idempotency_key() -> str

A random key for the Idempotency-Key header.

parse_bool

parse_bool(text: str) -> bool

Parse true/false/1/0/yes/no/on/off (case-insensitive); raise :class:ValueError.

parse_duration

parse_duration(text: str) -> float

Parse a duration into seconds.

Accepts integer milliseconds ("1500" → 1.5) or Go-style units ("500ms", "10s", "2m", "1h", "1m30s"). Raises :class:ValueError for anything else.

parse_retry_after

parse_retry_after(value: str | None, *, now: Callable[[], float] = time.time) -> float | None

Parse Retry-After as delta seconds or an HTTP-date; return seconds (>= 0) or None.

poll_until

poll_until(fn: Callable[[], T | None], *, timeout_s: float = 30.0, interval_s: float = 1.0, predicate: Callable[[T], bool] | None = None, operation: str = 'poll', sleep: Callable[[float], None] = time.sleep, clock: Callable[[], float] = time.monotonic) -> T

Call fn every interval_s until it returns a ready value; return that value.

A value is ready when it is not None and predicate(value) is true (without a predicate: not an empty container). Retryable SDK errors raised by fn are remembered and polling continues; other errors propagate. Raises :class:TimeoutError after timeout_s.

redact_fields

redact_fields(value: Any, extra_keys: Iterable[str] = ()) -> Any

Recursively redact values whose key looks sensitive in nested mappings and lists.

redact_headers

redact_headers(headers: Mapping[str, str] | Iterable[tuple[str, str]]) -> dict[str, str]

Copy of headers with sensitive values replaced by [REDACTED].

redact_text

redact_text(text: str, known_secrets: Iterable[str | Secret | None] = ()) -> str

Replace every known secret value (length >= 4) in text with [REDACTED].

redact_url

redact_url(url: str) -> str

Redact user info and every query value (all values, not only sensitive ones).

Query names are kept so the URL stays useful in logs.

relative_endpoint

relative_endpoint(base: str, endpoint: str) -> str

Path of endpoint relative to the provider URL base.

The part after base when the endpoint starts with it (keeps realm prefixes out), else the endpoint's own path and query.

require_user

require_user(roles: Iterable[str] | None = None, *, verifier: Verifier | None = None, optional: bool = False) -> Callable[..., Awaitable[AuthUser | None]]

FastAPI dependency returning the :class:AuthUser of the request's bearer token.

Depends(require_user()) → 401 without/with an invalid token, 503 when the IdP is unreachable; require_user(roles=["admin"]) → 403 unless the user has one of the roles; optional=True returns None when there is no token. verifier defaults to :func:default_verifier.

retry_after_from_headers

retry_after_from_headers(headers: Headers | Mapping[str, str], names: Sequence[str] = RETRY_AFTER_HEADERS, *, now: Callable[[], float] = time.time) -> float | None

Server requested delay in seconds from the first of names that parses.

Retry-After is delta seconds or an HTTP-date. Other headers (X-RateLimit-Reset, RateLimit-Reset …) may be delta seconds or a Unix timestamp in seconds or milliseconds; timestamps are turned into the remaining delay.

set_default_verifier

set_default_verifier(verifier: Verifier | None) -> None

Replaces the process-wide verifier (None = rebuild from the environment).

to_seconds

to_seconds(value: float | timedelta) -> float

Normalise a duration given as float seconds or :class:datetime.timedelta.

truncate

truncate(text: str, limit: int = 300) -> str

Truncate text to limit characters (adds an ellipsis when cut).

user_agent

user_agent(suffix: str | None = None) -> str

grow-codes-<key>/<version> (python) plus <suffix> when given.