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
¶
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").
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.
AuthUser
dataclass
¶
The authenticated user of a verified access token.
has_role ¶
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.
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.
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.
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 (orNoneto keep the default). The mapped error is whatHooks.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").
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
¶
Background resources (watchers, renewers) stopped by :meth:close.
from_env
classmethod
¶
Build a client from the GROW_<KEY>_* and vendor environment variables.
health ¶
Unauthenticated health check; never raises for an unhealthy/unreachable service.
ping ¶
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 ¶
Send a raw request through the client's transport (retries, hooks, redaction).
server_version ¶
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.
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 ¶
Raise :class:CancelledError ("<operation>: client is closed") once closed.
register ¶
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).
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.
Secret ¶
Wraps a credential so it never shows up in str/repr/logs.
s = Secret("hunter2") str(s), s.reveal() ('[REDACTED]', 'hunter2')
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.
from_env
classmethod
¶
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_request ¶
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 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 ¶
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 ¶
The process-wide verifier (Verifier.from_env() on first use).
django_require_roles ¶
Django view decorator: 401 without request.auth_user, 403 unless one of roles.
error_for_code ¶
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 ¶
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 ¶
The package logger (LOGGER_NAME), silent by default (NullHandler).
has_any_role ¶
True when user_roles has at least one of required (case-insensitive).
An empty required means any authenticated user.
parse_bool ¶
Parse true/false/1/0/yes/no/on/off (case-insensitive); raise :class:ValueError.
parse_duration ¶
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 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 ¶
Recursively redact values whose key looks sensitive in nested mappings and lists.
redact_headers ¶
Copy of headers with sensitive values replaced by [REDACTED].
redact_text ¶
Replace every known secret value (length >= 4) in text with [REDACTED].
redact_url ¶
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 ¶
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 ¶
Replaces the process-wide verifier (None = rebuild from the environment).
to_seconds ¶
Normalise a duration given as float seconds or :class:datetime.timedelta.
truncate ¶
Truncate text to limit characters (adds an ellipsis when cut).
user_agent ¶
grow-codes-<key>/<version> (python) plus <suffix> when given.