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 Casdoor.

from grow_casdoor import CasdoorClient client = CasdoorClient.from_env() # doctest: +SKIP tokens = client.sign_in(username="ada@example.test", password="...") # doctest: +SKIP

PACKAGE_KEY module-attribute

PACKAGE_KEY = 'casdoor'

Stack catalog key (value of GROW_SECRETS_PROVIDER / GROW_LOGGING_PROVIDER).

ApplicationInfo dataclass

Result of :meth:CasdoorClient.ensure_application.

AsyncCasdoorClient

Asynchronous Casdoor client with the same methods as :class:CasdoorClient.

Calls run in a worker thread. Use async with or call :meth:aclose.

aclose async

aclose() -> None

Close connections (idempotent).

build_authorize_url

build_authorize_url(**kw: Any) -> str

Same as :meth:CasdoorClient.build_authorize_url (no I/O).

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.

AuthenticationError

Bases: CasdoorError

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_CASDOOR_<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: CasdoorError, 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.

CasdoorClient

Synchronous Casdoor client: user flows for BFFs and idempotent admin operations.

Every Casdoor {"status": "error"} answer (HTTP 200) and every OAuth error becomes a typed :class:~grow_casdoor.CasdoorError subclass with casdoor_reason. Thread-safe; use as a context manager or call :meth:close.

resources property

resources: ResourceRegistry

Background resources stopped by :meth:close.

assign_roles

assign_roles(user: str, roles: Sequence[str], *, organization: str | None = None, cancel: CancelToken | None = None) -> None

Add a user (org/name, name or e-mail) to roles, creating missing roles.

build_authorize_url

build_authorize_url(*, redirect_uri: str, state: str, code_challenge: str, scope: str | None = None, nonce: str | None = None, extra: dict[str, str] | None = None) -> str

Browser authorize URL on public_url (code flow, PKCE S256).

close

close() -> None

Close connections (idempotent).

ensure_application

ensure_application(**kw: Any) -> ApplicationInfo

Create or align the OAuth application; returns its client credentials.

ensure_email_provider

ensure_email_provider(smtp: SmtpSettings, *, cancel: CancelToken | None = None) -> tuple[str, bool]

Create or align an SMTP provider and list it on the configured application.

ensure_organization

ensure_organization(name: str, **kw: Any) -> tuple[str, bool]

Create the organization unless it exists; returns (name, created).

ensure_roles

ensure_roles(names: Sequence[str], *, organization: str | None = None, cancel: CancelToken | None = None) -> list[RoleInfo]

Create every missing role.

ensure_user

ensure_user(**kw: Any) -> CasdoorUser

Create or align a user (verified e-mail by default) and assign its roles.

exchange_code

exchange_code(*, code: str, code_verifier: str, redirect_uri: str, cancel: CancelToken | None = None) -> TokenSet

Exchange the authorization code from the browser redirect.

forgot_password

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

Mail a password reset code (:class:NotFoundError for unknown e-mails).

from_env classmethod

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

Build from GROW_CASDOOR_* and the platform names (GROW_AUTH_ISSUER, GROW_AUTH_CLIENT_ID/SECRET, GROW_AUTH_ORG/APP, CASDOOR_ADMIN_PASSWORD …).

health

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

GET /api/health; never raises for an unhealthy or unreachable service.

ping

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

Authenticated round trip with the admin credentials; latency in milliseconds.

refresh

refresh(refresh_token: str, *, cancel: CancelToken | None = None) -> TokenSet

New tokens from a refresh token.

reset_password

reset_password(*, email: str, code: str, new_password: str, cancel: CancelToken | None = None) -> None

Set a new password with the code from :meth:forgot_password.

send_email_verification

send_email_verification(email: str, *, purpose: str = 'auto', cancel: CancelToken | None = None) -> None

Mail a verification code (purpose: auto, signup or verify).

server_version

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

/api/get-version-info (needs the admin session).

setup_totp

setup_totp(access_token: str, *, cancel: CancelToken | None = None) -> TotpSetup

Start TOTP enrollment for the user of the access token.

sign_in

sign_in(*, username: str, password: str, totp_code: str | None = None, recovery_code: str | None = None, redirect_uri: str | None = None, cancel: CancelToken | None = None) -> TokenSet

Headless password sign-in (code flow + PKCE). Raises :class:MfaRequiredError and :class:EmailNotVerifiedError.

sign_out

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

End the Casdoor session of the token. Idempotent.

sign_up

sign_up(*, email: str, password: str, username: str | None = None, display_name: str | None = None, email_code: str | None = None, cancel: CancelToken | None = None) -> SignUpResult

Register a user (/api/signup); email_code when the application requires it.

verify_email

verify_email(*, email: str, code: str, cancel: CancelToken | None = None) -> None

Check the code and mark the user's e-mail verified.

verify_totp

verify_totp(*, access_token: str, secret: str, code: str, recovery_code: str, cancel: CancelToken | None = None) -> None

Verify the first TOTP code, then enable TOTP.

CasdoorConfig dataclass

Bases: BaseConfig

Immutable settings for :class:~grow_casdoor.CasdoorClient.

Environment (from_env): GROW_CASDOOR_<NAME> first, then the platform names.

======================== =========================================================== Field Variables (in order) ======================== =========================================================== url URL, GROW_AUTH_ISSUER, GROW_AUTH_PUBLIC_URL, CASDOOR_URL public_url PUBLIC_URL, GROW_AUTH_PUBLIC_URL (default url) client_id CLIENT_ID, GROW_AUTH_CLIENT_ID client_secret CLIENT_SECRET, GROW_AUTH_CLIENT_SECRET organization ORG, GROW_AUTH_ORG application APP, GROW_AUTH_APP redirect_uri REDIRECT_URL, GROW_AUTH_REDIRECT_URL scope SCOPE (default openid profile email) admin_username ADMIN_USERNAME, CASDOOR_ADMIN_USERNAME (default admin) admin_password ADMIN_PASSWORD, CASDOOR_ADMIN_PASSWORD admin_organization ADMIN_ORG (default built-in) admin_application ADMIN_APP (default app-built-in) require_verified_email REQUIRE_VERIFIED_EMAIL (default True) ======================== ===========================================================

browser_url property

browser_url: str

Browser-facing URL (public_url, always set after construction).

validate

validate() -> _C

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

CasdoorReason

Machine-readable reasons attached to normalized Casdoor errors (err.casdoor_reason).

CasdoorUser dataclass

A Casdoor user (subset).

ConfigError

Bases: CasdoorError

Invalid or missing configuration.

ConflictError

Bases: CasdoorError

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

EmailNotVerifiedError

Bases: PermissionDeniedError

The user signed in but the e-mail address is not verified yet.

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).

MfaRequiredError

Bases: AuthenticationError

Sign-in needs a second factor: retry with totp_code or recovery_code.

NotFoundError

Bases: CasdoorError

Missing record (HTTP 404).

PermissionDeniedError

Bases: CasdoorError

Authenticated but not allowed (HTTP 403).

Pkce dataclass

A PKCE pair (RFC 7636, S256).

RateLimitError

Bases: CasdoorError

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).

RoleInfo dataclass

Result entry of :meth:CasdoorClient.ensure_roles.

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.

SignUpResult dataclass

Result of :meth:CasdoorClient.sign_up.

SmtpSettings dataclass

SMTP settings for :meth:CasdoorClient.ensure_email_provider.

TimeoutError

Bases: CasdoorError

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.

TokenSet dataclass

OAuth tokens returned by sign-in, refresh and code exchange.

from_response classmethod

from_response(body: dict[str, Any], now: datetime | None = None) -> TokenSet

Build from a token endpoint body.

TotpSetup dataclass

Result of :meth:CasdoorClient.setup_totp (show the secret once, never log it).

UnavailableError

Bases: CasdoorError

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

UnsupportedError

Bases: CasdoorError

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

ValidationError

Bases: CasdoorError

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

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.

casdoor_reason

casdoor_reason(err: BaseException) -> str | None

The casdoor_reason of a normalized error, else None.

create_pkce

create_pkce() -> Pkce

A new PKCE verifier (64 characters) and its S256 challenge.

error_for_code

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

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.

get_logger

get_logger() -> logging.Logger

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

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.

pkce_challenge

pkce_challenge(code_verifier: str) -> str

S256 challenge of a verifier: base64url(sha256(verifier)).

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.

random_state

random_state(nbytes: int = 24) -> str

Random URL-safe value for state or nonce.

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.

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.

to_seconds

to_seconds(value: float | timedelta) -> float

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

totp_code

totp_code(secret: str, at: float | None = None) -> str

Current TOTP code (RFC 6238, SHA-1, 6 digits, 30 s) for tests and e2e helpers.

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.