Skip to content

Authentication

auth

Authentication: who is calling, and whether they may.

from oxbrook import App, Depends, Request, Router
from oxbrook.auth import APIKey, JWT, Principal, optional, principal

tokens = JWT(key=SECRET, algorithms=["HS256"], audience="notes")
keys = APIKey(header="x-api-key", verify=lookup_key)

app = App(auth=tokens | keys)                          # every route, by default

@app.get("/health", auth=None)                         # public, on purpose
async def health(_: Request): ...

@app.post("/notes", auth=tokens.requires("notes:write"))
async def create(_: Request, note: NoteIn, who: Principal = Depends(principal)): ...

Three ideas. A scheme finds a credential in a request and checks it. A principal is who it found. A requirement is what a route demands of that principal. auth= on an app, a router, a route or a WebSocket declares all three at once, and the nearest declaration wins.

The rules the framework enforces. Schemes are tried in the order written, and the first one that finds a credential of its kind decides: a credential that is present and wrong answers 401 and never falls through to the next scheme or to anonymous access. Missing or wrong credentials are 401, with a WWW-Authenticate challenge for each scheme that has one; a principal that fails a requirement is 403. Authentication runs before the request body is read and before any router middleware or handler, so a refused caller never makes the server take in what they sent.

A scheme is any object with async authenticate(request) returning a Principal, returning None when the request carries no credential of its kind, and raising Unauthenticated when it carries one that is wrong. Subclass Scheme to get | and .requires(...) as well.

Principal dataclass

Principal(
    subject: str,
    scheme: str = "",
    scopes: frozenset[str] = frozenset(),
    roles: frozenset[str] = frozenset(),
    claims: Mapping[str, Any] = dict(),
    user: Any = None,
)

Who a scheme found: the same shape whatever the credential was.

subject identifies the caller — a user id, a key id, a client id — and is a string, so str(user.id) rather than the id itself. scheme is the name of the scheme that found it, filled in by the framework when left empty. scopes are what the credential grants the client, and roles what the caller is, as an identity provider assigns them; requires(...) checks both. claims is anything else the credential carried, and user whatever a verify function looked up, if anything.

Scopes and roles are kept apart because providers issue them separately, and a role that shares a name with a scope must not grant it.

subject instance-attribute

subject: str

scheme class-attribute instance-attribute

scheme: str = ''

scopes class-attribute instance-attribute

scopes: frozenset[str] = frozenset()

roles class-attribute instance-attribute

roles: frozenset[str] = frozenset()

claims class-attribute instance-attribute

claims: Mapping[str, Any] = field(default_factory=dict)

user class-attribute instance-attribute

user: Any = None

Scheme

Bases: _Combinable

A way of finding and checking a credential.

Subclass it and write authenticate:

class Signature(Scheme):
    name = "signature"

    async def authenticate(self, request):
        signature = request.header("x-signature")
        if signature is None:
            return None                       # not mine: try the next scheme
        if not valid(signature, await request.read()):
            raise Unauthenticated("bad signature")   # mine, and wrong
        return Principal(subject="webhook")

challenge gives the WWW-Authenticate header sent with a refusal, and openapi the entry in the OpenAPI document's securitySchemes; both are optional.

name instance-attribute

name: str

authenticate async

authenticate(request: Any) -> Principal | None
Source code in python/oxbrook/auth.py
async def authenticate(self, request: Any) -> Principal | None:
    raise NotImplementedError

challenge

challenge(error: HTTPError | None) -> str | None

The WWW-Authenticate value for a refusal, or None for none.

error is the Unauthenticated this scheme raised, the Forbidden its principal earned, or None when no credential of its kind was sent.

Source code in python/oxbrook/auth.py
def challenge(self, error: HTTPError | None) -> str | None:
    """The `WWW-Authenticate` value for a refusal, or None for none.

    `error` is the `Unauthenticated` this scheme raised, the `Forbidden`
    its principal earned, or None when no credential of its kind was sent.
    """
    return None

openapi

openapi() -> dict[str, Any] | None

This scheme's OpenAPI securitySchemes entry, or None.

Source code in python/oxbrook/auth.py
def openapi(self) -> dict[str, Any] | None:
    """This scheme's OpenAPI `securitySchemes` entry, or None."""
    return None

APIKey

APIKey(
    *,
    header: str | None = None,
    cookie: str | None = None,
    verify: Callable[[str], Any],
    name: str = "api_key",
)

Bases: Scheme

A key in a header or a cookie, looked up by its hash.

async def lookup_key(digest):        # -> Principal, or None if unknown
    row = await db.fetchrow("select * from api_keys where digest = $1", digest)
    return None if row is None else Principal(
        subject=row["id"], scopes=row["scopes"]
    )

keys = APIKey(header="x-api-key", verify=lookup_key)

verify receives the key's SHA-256 digest, never the key, so what is stored is the digest: a leaked table is not a list of working keys, and a lookup by digest cannot be timed to recover a key byte by byte. Store APIKey.digest(key) when issuing one; APIKey.generate() makes a key long enough that an unsalted hash is the right tool.

Not the query string, which ends up in logs.

Source code in python/oxbrook/auth.py
def __init__(
    self,
    *,
    header: str | None = None,
    cookie: str | None = None,
    verify: Callable[[str], Any],
    name: str = "api_key",
) -> None:
    if (header is None) == (cookie is None):
        raise TypeError("APIKey needs exactly one of header= or cookie=")
    self.header = header.lower() if header is not None else None
    self.cookie = cookie
    self.verify = _verifier(verify, "APIKey")
    self.name = name

header instance-attribute

header = header.lower() if header is not None else None

cookie instance-attribute

cookie = cookie

verify instance-attribute

verify = _verifier(verify, 'APIKey')

name instance-attribute

name = name

digest staticmethod

digest(key: str) -> str

What to store for key, and what verify is given to look up.

Source code in python/oxbrook/auth.py
@staticmethod
def digest(key: str) -> str:
    """What to store for `key`, and what `verify` is given to look up."""
    return hashlib.sha256(key.encode()).hexdigest()

generate staticmethod

generate(prefix: str = '') -> str

A new random key: 256 bits, URL-safe, after prefix.

Source code in python/oxbrook/auth.py
@staticmethod
def generate(prefix: str = "") -> str:
    """A new random key: 256 bits, URL-safe, after `prefix`."""
    return prefix + secrets.token_urlsafe(32)

authenticate async

authenticate(request: Any) -> Principal | None
Source code in python/oxbrook/auth.py
async def authenticate(self, request: Any) -> Principal | None:
    if self.header is not None:
        raw = request.header(self.header)
    else:
        raw = request.cookies.get(self.cookie)
    if raw is None:
        return None
    raw = raw.strip()
    if not raw:
        raise Unauthenticated("API key invalid")
    found = await _call(self.verify, self.digest(raw))
    if found is None:
        logger.info("api key refused: unknown", extra={"scheme": self.name})
        raise Unauthenticated("API key invalid")
    return _found(found, self)

openapi

openapi() -> dict[str, Any]
Source code in python/oxbrook/auth.py
def openapi(self) -> dict[str, Any]:
    if self.header is not None:
        return {"type": "apiKey", "in": "header", "name": self.header}
    return {"type": "apiKey", "in": "cookie", "name": self.cookie}

Bearer

Bearer(
    verify: Callable[[str], Any] | None = None,
    *,
    realm: str | None = None,
    name: str = "bearer",
    bearer_format: str | None = None,
)

Bases: Scheme

A token in Authorization: Bearer <token>, checked by verify.

async def check_token(token):          # -> Principal, or None if invalid
    record = await tokens.lookup(token)
    return None if record is None else Principal(subject=record.user_id)

bearer = Bearer(verify=check_token)

For tokens this app can check itself, JWT does the verifying. verify is for everything else: a provider SDK, an opaque token looked up in a database or introspected at the issuer.

Refusals carry an RFC 6750 challenge: invalid_token for a token that did not verify, insufficient_scope with the scopes needed for a 403.

Source code in python/oxbrook/auth.py
def __init__(
    self,
    verify: Callable[[str], Any] | None = None,
    *,
    realm: str | None = None,
    name: str = "bearer",
    bearer_format: str | None = None,
) -> None:
    if verify is None and type(self) is Bearer:
        raise TypeError("Bearer needs verify=, a function from token to Principal or None")
    self.verify = verify
    self.realm = realm
    self.name = name
    self.bearer_format = bearer_format

verify instance-attribute

verify = verify

realm instance-attribute

realm = realm

name instance-attribute

name = name

bearer_format instance-attribute

bearer_format = bearer_format

authenticate async

authenticate(request: Any) -> Principal | None
Source code in python/oxbrook/auth.py
async def authenticate(self, request: Any) -> Principal | None:
    token = _authorization(request, "bearer")
    if token is None:
        return None
    if not token:
        raise Unauthenticated("token invalid")
    return await self.check(token)

check async

check(token: str) -> Principal
Source code in python/oxbrook/auth.py
async def check(self, token: str) -> Principal:
    found = await _call(self.verify, token)
    if found is None:
        logger.info("bearer token refused by verify", extra={"scheme": self.name})
        raise Unauthenticated("token invalid")
    return _found(found, self)

challenge

challenge(error: HTTPError | None) -> str
Source code in python/oxbrook/auth.py
def challenge(self, error: HTTPError | None) -> str:
    params = []
    if self.realm is not None:
        params.append(f"realm={_quoted(self.realm)}")
    if isinstance(error, Forbidden):
        params.append('error="insufficient_scope"')
        if error.scopes:
            params.append(f"scope={_quoted(' '.join(error.scopes))}")
    elif error is not None:
        params.append('error="invalid_token"')
        if error.detail:
            params.append(f"error_description={_quoted(error.detail)}")
    return "Bearer" + (" " + ", ".join(params) if params else "")

openapi

openapi() -> dict[str, Any]
Source code in python/oxbrook/auth.py
def openapi(self) -> dict[str, Any]:
    entry = {"type": "http", "scheme": "bearer"}
    if self.bearer_format:
        entry["bearerFormat"] = self.bearer_format
    return entry

JWT

JWT(
    key: Any,
    *,
    algorithms: Iterable[str],
    audience: str | Iterable[str] | None,
    issuer: str | None = None,
    leeway: float = 60,
    scopes_claim: str | tuple[str, ...] = "scope",
    roles_claim: str | tuple[str, ...] | None = None,
    subject_claim: str = "sub",
    claims: Mapping[str, Any] | None = None,
    cache_size: int = _CACHE_SIZE,
    realm: str | None = None,
    name: str = "jwt",
)

Bases: _Signed

A JSON Web Token this app can verify itself.

tokens = JWT(key=os.environ["JWT_SECRET"], algorithms=["HS256"], audience="notes")
tokens = JWT(key=public_key_pem, algorithms=["RS256"], audience="notes",
             issuer="https://login.example.com/")

Checked every time: the signature, exp with leeway seconds of clock skew, nbf, aud against audience, and iss against issuer when one is given. The principal's subject is the sub claim and its scopes the scope claim, a space-separated string or a list; scopes_claim names a different claim, such as "scp" or "permissions", and roles_claim one to read roles from. Either may be a tuple naming a nested claim: roles_claim=("realm_access", "roles"). claims= names claims that must have a given value, or one of a list: claims={"token_use": "access"}.

algorithms is required, and cannot mix families: an HMAC secret with HS*, or a public key with the asymmetric ones. Accepting both is how a public key ends up used as an HMAC secret to forge a token, and none is never accepted. An HMAC secret must be at least as long as the hash.

audience=None accepts a token for any audience, and has to be written out: a token issued for another service is otherwise accepted by this one.

A token that verified is remembered until it expires, up to cache_size of them, so a caller's next request skips the signature check; 0 turns that off.

Needs PyJWT: pip install 'oxbrook[auth]'.

Source code in python/oxbrook/auth.py
def __init__(
    self,
    key: Any,
    *,
    algorithms: Iterable[str],
    audience: str | Iterable[str] | None,
    issuer: str | None = None,
    leeway: float = 60,
    scopes_claim: str | tuple[str, ...] = "scope",
    roles_claim: str | tuple[str, ...] | None = None,
    subject_claim: str = "sub",
    claims: Mapping[str, Any] | None = None,
    cache_size: int = _CACHE_SIZE,
    realm: str | None = None,
    name: str = "jwt",
) -> None:
    jwt = _pyjwt("JWT")
    super().__init__(realm=realm, name=name, bearer_format="JWT")
    self._jwt = jwt
    if isinstance(algorithms, str):
        raise TypeError("algorithms is a list: algorithms=['HS256']")
    algorithms = list(algorithms)
    if not algorithms:
        raise ValueError("JWT needs at least one algorithm")
    if any(a.lower() == "none" for a in algorithms):
        raise ValueError("the 'none' algorithm means an unsigned token, and is never accepted")
    unknown = [a for a in algorithms if a not in _HMAC and a not in _ASYMMETRIC]
    if unknown:
        raise ValueError(f"unknown JWT algorithm(s) {unknown}")
    hmac_algorithms = [a for a in algorithms if a in _HMAC]
    if hmac_algorithms and len(hmac_algorithms) != len(algorithms):
        raise ValueError(
            "algorithms cannot mix HMAC (HS*) with public-key algorithms: a public "
            "key accepted as an HMAC secret lets anyone who has it forge a token"
        )
    if hmac_algorithms:
        if not isinstance(key, (str, bytes)):
            raise TypeError("an HS* algorithm needs the shared secret, as str or bytes")
        secret = key.encode() if isinstance(key, str) else key
        if secret.lstrip().startswith(b"-----BEGIN"):
            raise ValueError(
                "that key is a PEM key, not a shared secret; use an RS*, PS*, ES* "
                "or EdDSA algorithm with it"
            )
        needed = max(_HMAC[a] for a in hmac_algorithms)
        if len(secret) < needed:
            raise ValueError(
                f"an HMAC secret for {'/'.join(hmac_algorithms)} must be at least "
                f"{needed} bytes; this one is {len(secret)}. "
                f"secrets.token_urlsafe({needed}) makes one"
            )
    self.key = key
    self._key = key if hmac_algorithms else self._prepared(jwt, key, algorithms)
    self.algorithms = algorithms
    self._configure(
        audience=audience, issuer=issuer, leeway=leeway, scopes_claim=scopes_claim,
        roles_claim=roles_claim, subject_claim=subject_claim, claims=claims,
        cache_size=cache_size,
    )

key instance-attribute

key = key

algorithms instance-attribute

algorithms = algorithms

OIDC

OIDC(
    issuer: str,
    *,
    audience: str | Iterable[str] | None,
    algorithms: Iterable[str] | None = None,
    scopes_claim: str | tuple[str, ...] = "scope",
    roles_claim: str | tuple[str, ...] | None = None,
    subject_claim: str = "sub",
    claims: Mapping[str, Any] | None = None,
    leeway: float = 60,
    discovery_url: str | None = None,
    keys_max_age: float = 300,
    allow_http: bool = False,
    timeout: float = 10,
    cache_size: int = _CACHE_SIZE,
    realm: str | None = None,
    name: str = "oidc",
)

Bases: _Signed

Tokens from an OpenID Connect provider, checked against its published keys.

users = OIDC("https://login.example.com/realms/acme", audience="notes-api")
users = OIDC.auth0("acme.eu.auth0.com", audience="https://notes.example.com")

The provider's discovery document, /.well-known/openid-configuration under the issuer, says where its signing keys are. They are fetched on the first token, once for the whole process however many worker loops ask, and again every keys_max_age seconds so that a key the provider withdraws stops being accepted. A token signed with a key id not yet seen fetches them again at once — how a provider's key rotation arrives — but at most once a minute, so tokens with made-up key ids cannot turn into a stream of requests to the provider. Call await scheme.load() from a lifespan to fetch them at startup instead, and fail there if the provider is unreachable.

Only public-key algorithms are accepted, those the provider advertises, and each only with a key of its own type: never none, never HMAC, so a provider's public key cannot be used as a shared secret to forge a token. algorithms= narrows the list further. Every token is checked for its signature, iss, aud, exp and nbf, with leeway seconds of clock skew; claims are read as in JWT, including roles_claim and claims=.

When the provider cannot be reached before any keys were fetched, the answer is 503 rather than 401: the token may well be good, and a 401 tells a client to throw it away.

The issuer must be HTTPS, since keys fetched over plain HTTP can be replaced in transit; http://localhost is allowed for development, and allow_http=True for a provider on a private network.

The class methods set up known providers: keycloak, auth0, entra, okta, cognito, google and firebase. Each takes the same keyword arguments as OIDC itself, to override what it sets.

Source code in python/oxbrook/auth.py
def __init__(
    self,
    issuer: str,
    *,
    audience: str | Iterable[str] | None,
    algorithms: Iterable[str] | None = None,
    scopes_claim: str | tuple[str, ...] = "scope",
    roles_claim: str | tuple[str, ...] | None = None,
    subject_claim: str = "sub",
    claims: Mapping[str, Any] | None = None,
    leeway: float = 60,
    discovery_url: str | None = None,
    keys_max_age: float = 300,
    allow_http: bool = False,
    timeout: float = 10,
    cache_size: int = _CACHE_SIZE,
    realm: str | None = None,
    name: str = "oidc",
) -> None:
    jwt = _pyjwt("OIDC")
    from . import _jwks

    super().__init__(realm=realm, name=name, bearer_format="JWT")
    self._jwt = jwt
    if not isinstance(issuer, str) or not issuer:
        raise TypeError("OIDC needs the provider's issuer URL")
    _jwks.check_url(issuer, allow_http, "issuer")
    if discovery_url is None:
        discovery_url = issuer.rstrip("/") + "/.well-known/openid-configuration"
    _jwks.check_url(discovery_url, allow_http, "discovery_url")
    if algorithms is not None:
        if isinstance(algorithms, str):
            raise TypeError("algorithms is a list: algorithms=['RS256']")
        algorithms = frozenset(algorithms)
        refused = [a for a in algorithms if a not in _ASYMMETRIC]
        if refused or not algorithms:
            raise ValueError(
                f"OIDC accepts only public-key algorithms ({', '.join(sorted(_ASYMMETRIC))}); "
                f"a provider's tokens are never HMAC or unsigned. Refused: {refused}"
            )
    if keys_max_age <= 0:
        raise ValueError("keys_max_age is seconds, more than 0")
    self.discovery_url = discovery_url
    self._configure(
        audience=audience, issuer=issuer, leeway=leeway, scopes_claim=scopes_claim,
        roles_claim=roles_claim, subject_claim=subject_claim, claims=claims,
        cache_size=cache_size,
    )
    self.keys = _jwks.KeySet(
        discovery_url,
        issuer,
        algorithms=algorithms,
        allow_http=allow_http,
        timeout=timeout,
        max_age=keys_max_age,
        changed=self._verified.clear,
    )

discovery_url instance-attribute

discovery_url = discovery_url

keys instance-attribute

keys = _jwks.KeySet(
    discovery_url,
    issuer,
    algorithms=algorithms,
    allow_http=allow_http,
    timeout=timeout,
    max_age=keys_max_age,
    changed=self._verified.clear,
)

load async

load() -> None

Fetch the discovery document and keys now, raising if that fails.

Source code in python/oxbrook/auth.py
async def load(self) -> None:
    """Fetch the discovery document and keys now, raising if that fails."""
    from . import _jwks

    try:
        await self.keys.load()
    except _jwks.Unavailable as exc:
        raise RuntimeError(f"{self.name}: {exc}") from None

openapi

openapi() -> dict[str, Any]
Source code in python/oxbrook/auth.py
def openapi(self) -> dict[str, Any]:
    return {"type": "openIdConnect", "openIdConnectUrl": self.discovery_url}

keycloak classmethod

keycloak(
    url: str, realm: str, *, audience: Any, **options: Any
) -> OIDC

Keycloak: OIDC.keycloak("https://sso.example.com", "acme", audience="notes-api").

Scopes from scope, roles from the realm roles in realm_access. For a client's own roles, roles_claim=("resource_access", client, "roles"). Keycloak puts a client in aud only through an audience mapper, which the API's clients need.

Source code in python/oxbrook/auth.py
@classmethod
def keycloak(cls, url: str, realm: str, *, audience: Any, **options: Any) -> "OIDC":
    """Keycloak: `OIDC.keycloak("https://sso.example.com", "acme", audience="notes-api")`.

    Scopes from `scope`, roles from the realm roles in `realm_access`. For
    a client's own roles, `roles_claim=("resource_access", client, "roles")`.
    Keycloak puts a client in `aud` only through an audience mapper, which
    the API's clients need.
    """
    issuer = f"{_bare(url, 'url', scheme=True)}/realms/{_segment(realm, 'realm')}"
    defaults = {"audience": audience, "roles_claim": ("realm_access", "roles")}
    return cls._preset(issuer, defaults, options)

auth0 classmethod

auth0(
    domain: str, *, audience: Any, **options: Any
) -> OIDC

Auth0: OIDC.auth0("acme.eu.auth0.com", audience="https://notes.example.com").

audience is the API's identifier. Scopes from scope; with RBAC's "Add Permissions in the Access Token", scopes_claim="permissions".

Source code in python/oxbrook/auth.py
@classmethod
def auth0(cls, domain: str, *, audience: Any, **options: Any) -> "OIDC":
    """Auth0: `OIDC.auth0("acme.eu.auth0.com", audience="https://notes.example.com")`.

    `audience` is the API's identifier. Scopes from `scope`; with RBAC's
    "Add Permissions in the Access Token", `scopes_claim="permissions"`.
    """
    issuer = f"https://{_bare(domain, 'domain')}/"
    return cls._preset(issuer, {"audience": audience}, options)

entra classmethod

entra(
    tenant_id: str,
    *,
    audience: Any,
    version: int = 2,
    **options: Any,
) -> OIDC

Microsoft Entra ID: OIDC.entra(tenant_id, audience=api_client_id).

tenant_id is the directory's GUID; common and organizations name no single issuer and are refused. Scopes from scp, app roles from roles. An API's access tokens are version 1 unless its manifest sets requestedAccessTokenVersion to 2, and the two have different issuers: pass version=1 for those.

Source code in python/oxbrook/auth.py
@classmethod
def entra(
    cls, tenant_id: str, *, audience: Any, version: int = 2, **options: Any
) -> "OIDC":
    """Microsoft Entra ID: `OIDC.entra(tenant_id, audience=api_client_id)`.

    `tenant_id` is the directory's GUID; `common` and `organizations`
    name no single issuer and are refused. Scopes from `scp`, app roles
    from `roles`. An API's access tokens are version 1 unless its manifest
    sets `requestedAccessTokenVersion` to 2, and the two have different
    issuers: pass `version=1` for those.
    """
    tenant = _segment(tenant_id, "tenant_id")
    if tenant.lower() in {"common", "organizations", "consumers"}:
        raise ValueError(
            f"{tenant!r} is not one tenant, so it names no issuer to check; pass the "
            f"tenant id"
        )
    defaults: dict[str, Any] = {
        "audience": audience, "scopes_claim": "scp", "roles_claim": "roles",
    }
    if version == 2:
        issuer = f"https://login.microsoftonline.com/{tenant}/v2.0"
    elif version == 1:
        issuer = f"https://sts.windows.net/{tenant}/"
        defaults["discovery_url"] = (
            f"https://login.microsoftonline.com/{tenant}/.well-known/openid-configuration"
        )
    else:
        raise ValueError("Entra access tokens are version 1 or 2")
    return cls._preset(issuer, defaults, options)

okta classmethod

okta(
    domain: str,
    *,
    audience: Any,
    server: str = "default",
    **options: Any,
) -> OIDC

Okta: OIDC.okta("acme.okta.com", audience="api://default").

A custom authorization server, default unless server names another; the org server's access tokens are for Okta alone to verify. Scopes from scp.

Source code in python/oxbrook/auth.py
@classmethod
def okta(
    cls, domain: str, *, audience: Any, server: str = "default", **options: Any
) -> "OIDC":
    """Okta: `OIDC.okta("acme.okta.com", audience="api://default")`.

    A custom authorization server, `default` unless `server` names
    another; the org server's access tokens are for Okta alone to verify.
    Scopes from `scp`.
    """
    issuer = f"https://{_bare(domain, 'domain')}/oauth2/{_segment(server, 'server')}"
    return cls._preset(issuer, {"audience": audience, "scopes_claim": "scp"}, options)

cognito classmethod

cognito(
    region: str,
    user_pool_id: str,
    *,
    client_id: str | Iterable[str],
    **options: Any,
) -> OIDC

Amazon Cognito: OIDC.cognito("eu-west-1", "eu-west-1_AbC123", client_id="...").

Cognito access tokens carry no aud: the app client is in client_id, which is checked instead, along with token_use being access so an ID token is not accepted in its place. Scopes from scope, groups as roles from cognito:groups.

Source code in python/oxbrook/auth.py
@classmethod
def cognito(
    cls, region: str, user_pool_id: str, *, client_id: str | Iterable[str], **options: Any
) -> "OIDC":
    """Amazon Cognito: `OIDC.cognito("eu-west-1", "eu-west-1_AbC123", client_id="...")`.

    Cognito access tokens carry no `aud`: the app client is in
    `client_id`, which is checked instead, along with `token_use` being
    `access` so an ID token is not accepted in its place. Scopes from
    `scope`, groups as roles from `cognito:groups`.
    """
    issuer = (
        f"https://cognito-idp.{_segment(region, 'region')}.amazonaws.com/"
        f"{_segment(user_pool_id, 'user_pool_id')}"
    )
    clients = [client_id] if isinstance(client_id, str) else list(client_id)
    defaults = {
        "audience": None,
        "claims": {"token_use": "access", "client_id": clients},
        "roles_claim": "cognito:groups",
    }
    return cls._preset(issuer, defaults, options)

google classmethod

google(
    client_id: str | Iterable[str], **options: Any
) -> OIDC

Google ID tokens, from Sign in with Google: OIDC.google(client_id).

Identity only: Google's tokens carry no scopes for an API. aud is the app's OAuth client id, and iss either of the two forms Google uses.

Source code in python/oxbrook/auth.py
@classmethod
def google(cls, client_id: str | Iterable[str], **options: Any) -> "OIDC":
    """Google ID tokens, from Sign in with Google: `OIDC.google(client_id)`.

    Identity only: Google's tokens carry no scopes for an API. `aud` is
    the app's OAuth client id, and `iss` either of the two forms Google
    uses.
    """
    scheme = cls._preset("https://accounts.google.com", {"audience": client_id}, options)
    scheme._issuers = ["https://accounts.google.com", "accounts.google.com"]
    return scheme

firebase classmethod

firebase(project_id: str, **options: Any) -> OIDC

Firebase Authentication ID tokens: OIDC.firebase("acme-app").

aud is the project id. Custom claims set through the Admin SDK are top-level claims, so roles_claim="roles" reads a roles list.

Source code in python/oxbrook/auth.py
@classmethod
def firebase(cls, project_id: str, **options: Any) -> "OIDC":
    """Firebase Authentication ID tokens: `OIDC.firebase("acme-app")`.

    `aud` is the project id. Custom claims set through the Admin SDK are
    top-level claims, so `roles_claim="roles"` reads a `roles` list.
    """
    project = _segment(project_id, "project_id")
    return cls._preset(
        f"https://securetoken.google.com/{project}", {"audience": project}, options
    )

Basic

Basic(
    verify: Callable[[str, str], Any],
    *,
    realm: str = "api",
    name: str = "basic",
    allow_http: bool = False,
)

Bases: Scheme

A username and password in Authorization: Basic ....

async def check_password(username, password):   # -> Principal, or None
    user = await users.find(username)
    if user is None or not hasher.verify(user.password_hash, password):
        return None
    return Principal(subject=str(user.id), user=user)

staff = Basic(verify=check_password)

Refused over plain HTTP, since the password crosses the network readable. HTTPS, a proxy that sets X-Forwarded-Proto: https, and loopback are all accepted; allow_http=True accepts anything.

Compare the password against a slow hash — argon2, bcrypt, scrypt — in verify: a password is not a random key, and a fast hash of one is cracked offline.

Source code in python/oxbrook/auth.py
def __init__(
    self,
    verify: Callable[[str, str], Any],
    *,
    realm: str = "api",
    name: str = "basic",
    allow_http: bool = False,
) -> None:
    self.verify = _verifier(verify, "Basic")
    self.realm = realm
    self.name = name
    self.allow_http = allow_http

verify instance-attribute

verify = _verifier(verify, 'Basic')

realm instance-attribute

realm = realm

name instance-attribute

name = name

allow_http instance-attribute

allow_http = allow_http

authenticate async

authenticate(request: Any) -> Principal | None
Source code in python/oxbrook/auth.py
async def authenticate(self, request: Any) -> Principal | None:
    encoded = _authorization(request, "basic")
    if encoded is None:
        return None
    try:
        username, colon, password = (
            base64.b64decode(encoded, validate=True).decode("utf-8").partition(":")
        )
    except (binascii.Error, UnicodeDecodeError):
        raise Unauthenticated("credentials malformed") from None
    if not colon:
        raise Unauthenticated("credentials malformed")
    if not self.allow_http and not _secure(request):
        logger.warning(
            "basic credentials refused over plain http; serve https, or pass "
            "Basic(allow_http=True)", extra={"scheme": self.name},
        )
        raise Unauthenticated("Basic credentials are refused over plain HTTP")
    found = await _call(self.verify, username, password)
    if found is None:
        logger.info("basic credentials refused by verify", extra={"scheme": self.name})
        raise Unauthenticated("credentials invalid")
    return _found(found, self)

challenge

challenge(error: HTTPError | None) -> str
Source code in python/oxbrook/auth.py
def challenge(self, error: HTTPError | None) -> str:
    return f'Basic realm={_quoted(self.realm)}, charset="UTF-8"'

openapi

openapi() -> dict[str, Any]
Source code in python/oxbrook/auth.py
def openapi(self) -> dict[str, Any]:
    return {"type": "http", "scheme": "basic"}

SessionAuth

SessionAuth(
    sessions: Any,
    *,
    key: str = "user_id",
    load: Callable[[Any], Any] | None = None,
    name: str = "session",
    csrf: bool = True,
    trusted_origins: Iterable[str] | None = None,
)

Bases: Scheme

The user a signed session cookie says is logged in.

sessions = Sessions(secret=SECRET)

@app.post("/login", auth=None)
async def login(_: Request, form: Login = Form(), session=Depends(sessions.load)):
    user = await check(form)
    session["user_id"] = user.id

web = SessionAuth(sessions, key="user_id", load=load_user)

load turns the stored value into the user, and may return a Principal to set scopes. With no load, the value itself is the subject.

A session cookie that does not verify, has expired, or names a user load cannot find counts as no session rather than a wrong credential. A browser sends the cookie on its own, and the person using it cannot remove a stale one; refusing it outright would lock them out of pages that accept anonymous visitors, until the cookie expired.

Cross-site requests are refused. A browser sends the session cookie with a request another site's page makes, so a request that changes state — anything but GET, HEAD and OPTIONS — must show it came from this site:

  1. Sec-Fetch-Site: same-origin or none, which browsers set themselves;
  2. otherwise an Origin naming this server, or one of trusted_origins;
  3. with neither header, an X-CSRF-Token header equal to the session's token, from csrf_token(session).

Anything else is 403. trusted_origins defaults to the app's CORS origins: a page allowed to call the API with credentials is trusted to. csrf=False turns the check off, for an app that does its own.

Source code in python/oxbrook/auth.py
def __init__(
    self,
    sessions: Any,
    *,
    key: str = "user_id",
    load: Callable[[Any], Any] | None = None,
    name: str = "session",
    csrf: bool = True,
    trusted_origins: Iterable[str] | None = None,
) -> None:
    if not callable(getattr(sessions, "decode", None)):
        raise TypeError("SessionAuth needs the app's Sessions(...)")
    if load is not None and not callable(load):
        raise TypeError(f"load= needs a function, got {type(load).__name__}")
    if trusted_origins is not None:
        from ._cors import check_origin

        if isinstance(trusted_origins, str):
            raise TypeError("trusted_origins is a list of origins, not one string")
        trusted_origins = frozenset(
            check_origin(o).lower() for o in trusted_origins if o != "*"
        )
    self.sessions = sessions
    self.key = key
    self.load = load
    self.name = name
    self.csrf = csrf
    self.trusted_origins = trusted_origins

sessions instance-attribute

sessions = sessions

key instance-attribute

key = key

load instance-attribute

load = load

name instance-attribute

name = name

csrf instance-attribute

csrf = csrf

trusted_origins instance-attribute

trusted_origins = trusted_origins

csrf_token staticmethod

csrf_token(session: Any) -> str

The session's CSRF token, made on first use.

For a request that carries neither Sec-Fetch-Site nor Origin — an old browser, mostly — to send as X-CSRF-Token. Render it into the page, or return it from an endpoint the page's script reads.

Source code in python/oxbrook/auth.py
@staticmethod
def csrf_token(session: Any) -> str:
    """The session's CSRF token, made on first use.

    For a request that carries neither `Sec-Fetch-Site` nor `Origin` —
    an old browser, mostly — to send as `X-CSRF-Token`. Render it into the
    page, or return it from an endpoint the page's script reads.
    """
    token = session.get(CSRF_KEY)
    if not isinstance(token, str) or not token:
        token = secrets.token_urlsafe(32)
        session[CSRF_KEY] = token
    return token

authenticate async

authenticate(request: Any) -> Principal | None
Source code in python/oxbrook/auth.py
async def authenticate(self, request: Any) -> Principal | None:
    raw = request.cookies.get(self.sessions.cookie)
    if not raw:
        return None
    data = self.sessions.decode(raw)
    value = data.get(self.key)
    if value is None:
        return None
    if self.csrf:
        # Before `load`: a forged request should not cost a lookup.
        reason = self._forged(request, data)
        if reason is not None:
            logger.warning("session request refused: %s", reason,
                           extra={"scheme": self.name, "path": request.path})
            raise Forbidden("cross-site request refused")
    if self.load is None:
        return Principal(subject=str(value), scheme=self.name)
    user = await _call(self.load, value)
    if user is None:
        return None
    if isinstance(user, Principal):
        return user
    return Principal(subject=str(value), scheme=self.name, user=user)

openapi

openapi() -> dict[str, Any]
Source code in python/oxbrook/auth.py
def openapi(self) -> dict[str, Any]:
    return {"type": "apiKey", "in": "cookie", "name": self.sessions.cookie}

Tickets

Tickets(
    *,
    ttl: float = 30,
    param: str = "ticket",
    name: str = "ticket",
    limit: int = 100000,
)

Bases: Scheme

Short-lived tickets for opening a WebSocket from a browser.

tickets = Tickets()

@app.post("/ws-ticket", auth=users)
async def ws_ticket(_: Request, who: Principal = Depends(principal)):
    return {"ticket": tickets.issue(who)}

@app.websocket("/feed", auth=tickets)
async def feed(_: Request, ws, who: Principal = Depends(principal)): ...

A browser cannot set Authorization on a WebSocket, and a token in the URL ends up in proxy logs and history. A ticket goes in the URL instead — new WebSocket("wss://.../feed?ticket=...") — and is safe there because it is good for one connection, within ttl seconds (30 by default), and for nothing else. The socket's principal is the one it was issued for.

Only a WebSocket upgrade reads one: on any other request a ticket in the query string is ignored, and no other scheme reads the query string.

Tickets are kept in the process that issued them. Behind a load balancer with several processes, the socket must reach the process the ticket came from.

Source code in python/oxbrook/auth.py
def __init__(
    self, *, ttl: float = 30, param: str = "ticket", name: str = "ticket",
    limit: int = 100_000,
) -> None:
    if ttl <= 0:
        raise ValueError("ttl is seconds, more than 0")
    self.ttl = ttl
    self.param = param
    self.name = name
    self.limit = limit
    self._waiting: dict[str, tuple[float, Principal]] = {}

ttl instance-attribute

ttl = ttl

param instance-attribute

param = param

name instance-attribute

name = name

limit instance-attribute

limit = limit

issue

issue(who: Principal) -> str

A new ticket for who, good for one socket within ttl seconds.

Source code in python/oxbrook/auth.py
def issue(self, who: Principal) -> str:
    """A new ticket for `who`, good for one socket within `ttl` seconds."""
    if not isinstance(who, Principal):
        raise TypeError("issue() takes the Principal the socket should have")
    now = time.monotonic()
    waiting = self._waiting
    if len(waiting) >= self.limit:
        try:
            for key in [k for k, (until, _) in list(waiting.items()) if until < now]:
                waiting.pop(key, None)
            # Still full of live ones: the oldest go first. A ticket is
            # meant to be used within a second or two of being issued.
            for key in list(itertools.islice(waiting, max(1, len(waiting) - self.limit + 1))):
                waiting.pop(key, None)
        except RuntimeError:
            pass  # another loop changed it mid-pass; the next issue trims
    ticket = secrets.token_urlsafe(32)
    waiting[ticket] = (now + self.ttl, who)
    return ticket

authenticate async

authenticate(request: Any) -> Principal | None
Source code in python/oxbrook/auth.py
async def authenticate(self, request: Any) -> Principal | None:
    if (request.header("upgrade") or "").strip().lower() != "websocket":
        return None
    query = request.query
    if not query:
        return None
    from urllib.parse import parse_qsl

    offered = [v for k, v in parse_qsl(query, keep_blank_values=True) if k == self.param]
    if not offered:
        return None
    # Popped, whatever happens next: single use means a second attempt
    # with the same ticket fails even if the first was refused later.
    entry = self._waiting.pop(offered[0], None) if len(offered) == 1 else None
    if entry is None or entry[0] < time.monotonic():
        logger.info("websocket ticket refused", extra={"scheme": self.name})
        raise Unauthenticated("ticket invalid")
    return entry[1]

OAuthLogin

OAuthLogin(
    issuer: str,
    *,
    client_id: str,
    client_secret: str | None,
    sessions: Any,
    scopes: Iterable[str] = ("openid", "email", "profile"),
    on_login: Callable[[Any, Login], Any] | None = None,
    key: str = "user_id",
    redirect_uri: str | None = None,
    after_login: str = "/",
    after_logout: str = "/",
    params: Mapping[str, str] | None = None,
    trusted_origins: Iterable[str] | None = None,
    discovery_url: str | None = None,
    allow_http: bool = False,
    timeout: float = 10,
    name: str = "oidc",
)

Logging people in through an identity provider.

sessions = Sessions(secret=os.environ["SECRET_KEY"])
google = OAuthLogin.google(
    client_id=os.environ["GOOGLE_CLIENT_ID"],
    client_secret=os.environ["GOOGLE_CLIENT_SECRET"],
    sessions=sessions,
    on_login=find_or_create_user,
)
app.include(google.routes(prefix="/auth"))  # /auth/login, /auth/callback, /auth/logout
web = SessionAuth(sessions, key="user_id", load=load_user)

A link to /auth/login?next=/notes sends the person to the provider; the provider sends them back to /auth/callback, which finishes the login and redirects to /notes. next is followed only when it is a path on this site. POST /auth/logout empties the session.

on_login(request, login) is where the app decides who that is: it receives a Login, and returns the value to keep in the session under key — usually the app's own user id, after finding or creating the user. Returning None refuses the login with 403. It may be async, and receives the request so it can reach a pool from request.state. With no on_login the value kept is "<name>:<subject>", such as "google:1161...".

What the flow checks. state must match a login this browser started, within ten minutes, and is good once. PKCE (S256) binds the code to that login too, so a code intercepted on its way back is useless elsewhere. For OpenID Connect providers the ID token is checked like any OIDC token — signature, issuer, audience (the client id), expiry — and its nonce must be this login's. An iss parameter on the callback must name the provider, which stops a callback from one provider being passed to another's endpoint. The session is emptied before the new value goes in, so nothing written into it before the login survives it.

The redirect URI must be registered with the provider exactly. It is worked out from the request unless redirect_uri= gives it; give it behind a proxy that changes the host or the scheme.

The session cookie must be SameSite=Lax or None: the callback arrives as a navigation from the provider's site, which a Strict cookie is not sent with.

OAuthLogin(issuer, ...) works with any OpenID Connect provider that serves discovery. The class methods set up google, microsoft, github and keycloak.

Source code in python/oxbrook/_login.py
def __init__(
    self,
    issuer: str,
    *,
    client_id: str,
    client_secret: str | None,
    sessions: Any,
    scopes: Iterable[str] = ("openid", "email", "profile"),
    on_login: Callable[[Any, Login], Any] | None = None,
    key: str = "user_id",
    redirect_uri: str | None = None,
    after_login: str = "/",
    after_logout: str = "/",
    params: Mapping[str, str] | None = None,
    trusted_origins: Iterable[str] | None = None,
    discovery_url: str | None = None,
    allow_http: bool = False,
    timeout: float = 10,
    name: str = "oidc",
) -> None:
    self._setup(
        client_id=client_id, client_secret=client_secret, sessions=sessions, scopes=scopes,
        on_login=on_login, key=key, redirect_uri=redirect_uri, after_login=after_login,
        after_logout=after_logout, params=params, trusted_origins=trusted_origins,
        allow_http=allow_http, timeout=timeout, name=name,
    )
    self._openid(OIDC(
        issuer, audience=client_id, discovery_url=discovery_url, allow_http=allow_http,
        timeout=timeout, cache_size=0, name=name,
    ))

load async

load() -> None

Fetch the provider's discovery document and keys now, raising if that fails: from a lifespan, to find an unreachable provider at startup.

Source code in python/oxbrook/_login.py
async def load(self) -> None:
    """Fetch the provider's discovery document and keys now, raising if
    that fails: from a lifespan, to find an unreachable provider at startup."""
    if self.verifier is not None:
        await self.verifier.load()

google classmethod

google(
    *,
    client_id: str,
    client_secret: str,
    sessions: Any,
    **options: Any,
) -> OAuthLogin

Sign in with Google.

The OAuth client comes from the Google Cloud console, as a "Web application" with the callback URL as an authorized redirect URI. claims["hd"] is the Workspace domain, for an app that admits one organisation's accounts only. params={"access_type": "offline"} asks for a refresh token.

Source code in python/oxbrook/_login.py
@classmethod
def google(cls, *, client_id: str, client_secret: str, sessions: Any,
           **options: Any) -> "OAuthLogin":
    """Sign in with Google.

    The OAuth client comes from the Google Cloud console, as a "Web
    application" with the callback URL as an authorized redirect URI.
    `claims["hd"]` is the Workspace domain, for an app that admits one
    organisation's accounts only. `params={"access_type": "offline"}`
    asks for a refresh token.
    """
    options.setdefault("name", "google")
    flow = cls("https://accounts.google.com", client_id=client_id,
               client_secret=client_secret, sessions=sessions, **options)
    # Google's ID tokens name their issuer in either form.
    flow.verifier._issuers = ["https://accounts.google.com", "accounts.google.com"]
    return flow

microsoft classmethod

microsoft(
    *,
    client_id: str,
    client_secret: str,
    sessions: Any,
    tenant: str = "common",
    authority: str = "https://login.microsoftonline.com",
    **options: Any,
) -> OAuthLogin

Sign in with Microsoft: work and school accounts, personal ones, or both.

tenant says whose accounts may log in: common (the default) any Microsoft account, organizations any work or school account, consumers personal accounts only, or a directory's tenant id for that organisation alone. For the first two the ID token's issuer names the person's own tenant, and is checked against its tid claim. authority is for a national cloud.

Microsoft does not verify the email claim, so email_verified is False: key accounts on subject, and claims["tid"] with it for a multi-tenant app.

Source code in python/oxbrook/_login.py
@classmethod
def microsoft(
    cls,
    *,
    client_id: str,
    client_secret: str,
    sessions: Any,
    tenant: str = "common",
    authority: str = "https://login.microsoftonline.com",
    **options: Any,
) -> "OAuthLogin":
    """Sign in with Microsoft: work and school accounts, personal ones, or both.

    `tenant` says whose accounts may log in: `common` (the default) any
    Microsoft account, `organizations` any work or school account,
    `consumers` personal accounts only, or a directory's tenant id for
    that organisation alone. For the first two the ID token's issuer
    names the person's own tenant, and is checked against its `tid`
    claim. `authority` is for a national cloud.

    Microsoft does not verify the `email` claim, so `email_verified` is
    False: key accounts on `subject`, and `claims["tid"]` with it for a
    multi-tenant app.
    """
    options.setdefault("name", "microsoft")
    authority = _bare(authority, "authority", scheme=True)
    tenant = _segment(tenant, "tenant").lower()
    verifier_options = {
        "allow_http": options.get("allow_http", False),
        "timeout": options.get("timeout", 10),
        "cache_size": 0,
        "name": options["name"],
    }
    discovery = f"{authority}/{tenant}/v2.0/.well-known/openid-configuration"
    if tenant in ("common", "organizations"):
        verifier: OIDC = _AnyTenant(
            authority, discovery, refuse_consumers=tenant == "organizations",
            audience=client_id, **verifier_options,
        )
    else:
        if tenant != "consumers" and not _GUID.fullmatch(tenant):
            raise ValueError(
                f"tenant is 'common', 'organizations', 'consumers' or a tenant id "
                f"(a GUID); got {tenant!r}. A domain name does not name one issuer"
            )
        tid = _CONSUMERS if tenant == "consumers" else tenant
        verifier = OIDC(f"{authority}/{tid}/v2.0", audience=client_id,
                        discovery_url=discovery, **verifier_options)
    flow = cls.__new__(cls)
    flow._setup(
        client_id=client_id, client_secret=client_secret, sessions=sessions,
        **{"scopes": ("openid", "email", "profile"), **_common(options)},
    )
    flow._openid(verifier)
    return flow

keycloak classmethod

keycloak(
    url: str,
    realm: str,
    *,
    client_id: str,
    client_secret: str | None,
    sessions: Any,
    **options: Any,
) -> OAuthLogin

A Keycloak realm: OAuthLogin.keycloak("https://sso.example.com", "acme", ...).

The client needs the standard flow enabled, the callback URL among its valid redirect URIs, and PKCE's S256 method allowed.

Source code in python/oxbrook/_login.py
@classmethod
def keycloak(cls, url: str, realm: str, *, client_id: str, client_secret: str | None,
             sessions: Any, **options: Any) -> "OAuthLogin":
    """A Keycloak realm: `OAuthLogin.keycloak("https://sso.example.com", "acme", ...)`.

    The client needs the standard flow enabled, the callback URL among its
    valid redirect URIs, and PKCE's `S256` method allowed.
    """
    options.setdefault("name", "keycloak")
    issuer = f"{_bare(url, 'url', scheme=True)}/realms/{_segment(realm, 'realm')}"
    return cls(issuer, client_id=client_id, client_secret=client_secret,
               sessions=sessions, **options)

github classmethod

github(
    *,
    client_id: str,
    client_secret: str,
    sessions: Any,
    server: str = "https://github.com",
    api: str = "https://api.github.com",
    **options: Any,
) -> OAuthLogin

Sign in with GitHub, through an OAuth app.

GitHub is OAuth 2 without OpenID Connect: there is no ID token, so who logged in is read from its API with the access token instead. subject is the account's numeric id as a string — the login name can be changed and then taken by someone else. The email is the primary verified address when the user:email scope is granted.

For GitHub Enterprise Server, server="https://github.example.com" and api="https://github.example.com/api/v3".

Source code in python/oxbrook/_login.py
@classmethod
def github(
    cls,
    *,
    client_id: str,
    client_secret: str,
    sessions: Any,
    server: str = "https://github.com",
    api: str = "https://api.github.com",
    **options: Any,
) -> "OAuthLogin":
    """Sign in with GitHub, through an OAuth app.

    GitHub is OAuth 2 without OpenID Connect: there is no ID token, so
    who logged in is read from its API with the access token instead.
    `subject` is the account's numeric id as a string — the login name
    can be changed and then taken by someone else. The email is the
    primary verified address when the `user:email` scope is granted.

    For GitHub Enterprise Server, `server="https://github.example.com"`
    and `api="https://github.example.com/api/v3"`.
    """
    options.setdefault("name", "github")
    allow_http = options.get("allow_http", False)
    server = _bare(server, "server", scheme=True)
    api = _bare(api, "api", scheme=True)
    _jwks.check_url(server, allow_http, "server")
    _jwks.check_url(api, allow_http, "api")
    flow = cls.__new__(_GitHub)
    flow._setup(
        client_id=client_id, client_secret=client_secret, sessions=sessions,
        **{"scopes": ("read:user", "user:email"), **_common(options)},
    )
    flow.token_auth = "post"
    flow._authorize_url = f"{server}/login/oauth/authorize"
    flow._token_url = f"{server}/login/oauth/access_token"
    flow.api = api
    flow.issuer = None
    return flow

routes

routes(
    prefix: str = "",
    *,
    login: str = "/login",
    callback: str = "/callback",
    logout: str = "/logout",
) -> Any

A router with the three routes, all public: include it in the app.

GET login starts a login, GET callback is where the provider sends the person back, and POST logout ends the session. Two providers need two prefixes, such as /auth/google and /auth/github.

Source code in python/oxbrook/_login.py
def routes(
    self,
    prefix: str = "",
    *,
    login: str = "/login",
    callback: str = "/callback",
    logout: str = "/logout",
) -> Any:
    """A router with the three routes, all public: include it in the app.

    `GET login` starts a login, `GET callback` is where the provider sends
    the person back, and `POST logout` ends the session. Two providers
    need two prefixes, such as `/auth/google` and `/auth/github`.
    """
    from ._routers import Router

    for path in (login, callback, logout):
        if not isinstance(path, str) or not path.startswith("/") or "{" in path:
            raise ValueError(f"a login route is a fixed path starting with '/', got {path!r}")
    # Public whatever the app's default: nobody is logged in yet.
    router = Router(prefix=prefix, auth=None)
    # The routes write the session, so they carry its middleware: an app
    # that installed it too is not written twice, since each layer
    # writes only what its own handlers changed.
    router.middleware(self.sessions.middleware)
    flow = self

    async def begin(request):
        return await flow._begin(request, login, callback)

    async def finish(request):
        return await flow._finish(request)

    async def end(request):
        return await flow._logout(request)

    # Named after the provider: a handler's name is its OpenAPI
    # operationId, and `google_login` reads better in a generated client
    # than the `login_get_auth_google_login` two same-named ones would get.
    for fn, action in ((begin, "login"), (finish, "callback"), (end, "logout")):
        fn.__name__ = fn.__qualname__ = f"{self.name}_{action}"
    router.get(login)(begin)
    router.get(callback)(finish)
    router.post(logout)(end)
    return router

Login dataclass

Login(
    provider: str,
    subject: str,
    email: str | None = None,
    email_verified: bool = False,
    name: str | None = None,
    claims: Mapping[str, Any] = dict(),
    tokens: Mapping[str, Any] = dict(),
)

Who the provider says logged in, as on_login receives it.

subject is the provider's stable id for the person: key accounts on (provider, subject), never on the email address, which a person can change and some providers do not verify. email_verified is True only when the provider said so. claims is the verified ID token's claims, or for GitHub the user as its API describes them. tokens is the provider's token response — the access token, and a refresh token if one was asked for — for an app that calls the provider's API later; it is not kept anywhere unless the app keeps it, and it is left out of repr.

provider instance-attribute

provider: str

subject instance-attribute

subject: str

email class-attribute instance-attribute

email: str | None = None

email_verified class-attribute instance-attribute

email_verified: bool = False

name class-attribute instance-attribute

name: str | None = None

claims class-attribute instance-attribute

claims: Mapping[str, Any] = field(default_factory=dict)

tokens class-attribute instance-attribute

tokens: Mapping[str, Any] = field(
    default_factory=dict, repr=False
)

LoginFailed

LoginFailed(status: int, detail: str, **kwargs: Any)

Bases: HTTPError

A login that could not be completed.

400 for a callback that does not belong to a login this browser started (or one already finished, or too old), 403 when the provider or the app's on_login refused the person, 502 or 503 when the provider could not be reached or answered nonsense. detail is written for the person; why, exactly, goes to the oxbrook.auth log. Register an exception handler for it to show a page rather than problem details.

Source code in python/oxbrook/_login.py
def __init__(self, status: int, detail: str, **kwargs: Any) -> None:
    super().__init__(status, detail, {"cache-control": "no-store"}, **kwargs)

Unauthenticated

Unauthenticated(
    detail: str | None = None,
    headers: dict[str, Any] | None = None,
    **kwargs: Any,
)

Bases: HTTPError

401: the request carries no acceptable credential.

Raised by a scheme for a credential that is present and wrong, which stops the search: the next scheme is not tried. detail reaches the client, so say what kind of wrong it is — expired, invalid — and log the rest.

Source code in python/oxbrook/auth.py
def __init__(
    self, detail: str | None = None, headers: dict[str, Any] | None = None, **kwargs: Any
) -> None:
    super().__init__(401, detail, headers, **kwargs)

Forbidden

Forbidden(
    detail: str | None = None,
    headers: dict[str, Any] | None = None,
    *,
    scopes: Iterable[str] = (),
    roles: Iterable[str] = (),
    **kwargs: Any,
)

Bases: HTTPError

403: the caller is known, and may not do this.

Raised by the framework when a principal fails a requirement, and the way a handler refuses a rule about a particular record: raise Forbidden() when the note belongs to someone else. Retrying with the same credential will not help, which is what separates it from 401.

Source code in python/oxbrook/auth.py
def __init__(
    self,
    detail: str | None = None,
    headers: dict[str, Any] | None = None,
    *,
    scopes: Iterable[str] = (),
    roles: Iterable[str] = (),
    **kwargs: Any,
) -> None:
    super().__init__(403, detail, headers, **kwargs)
    #: The scopes the caller lacked, when that is why.
    self.scopes = tuple(scopes)
    #: The roles the caller lacked, when that is why.
    self.roles = tuple(roles)

scopes instance-attribute

scopes = tuple(scopes)

roles instance-attribute

roles = tuple(roles)

Requirement dataclass

Requirement(
    all_of: frozenset[str] = frozenset(),
    any_of: frozenset[str] = frozenset(),
    check: Callable[..., Any] | None = None,
    roles: frozenset[str] = frozenset(),
)

What .requires(...) asks of a principal.

all_of class-attribute instance-attribute

all_of: frozenset[str] = frozenset()

any_of class-attribute instance-attribute

any_of: frozenset[str] = frozenset()

check class-attribute instance-attribute

check: Callable[..., Any] | None = None

roles class-attribute instance-attribute

roles: frozenset[str] = frozenset()

met async

met(found: Principal, request: Any) -> bool
Source code in python/oxbrook/auth.py
async def met(self, found: Principal, request: Any) -> bool:
    if not self.all_of <= found.scopes:
        return False
    if self.any_of and not self.any_of & found.scopes:
        return False
    if not self.roles <= found.roles:
        return False
    if self.check is not None:
        return bool(await _call(self.check, found, request))
    return True

missing

missing(found: Principal) -> list[str]

The scopes that would have satisfied it, for the challenge.

Source code in python/oxbrook/auth.py
def missing(self, found: Principal) -> list[str]:
    """The scopes that would have satisfied it, for the challenge."""
    lacking = sorted(self.all_of - found.scopes)
    if self.any_of and not self.any_of & found.scopes:
        lacking.extend(sorted(self.any_of))
    return lacking

missing_roles

missing_roles(found: Principal) -> list[str]
Source code in python/oxbrook/auth.py
def missing_roles(self, found: Principal) -> list[str]:
    return sorted(self.roles - found.roles)

principal

principal(request: Any) -> Principal | None

Who authentication found for this request, or None.

A dependency, who: Principal = Depends(principal), and a plain function for middleware. None on a route with no auth=, and for an anonymous caller on one declared optional(...).

Source code in python/oxbrook/auth.py
def principal(request: Any) -> Principal | None:
    """Who authentication found for this request, or None.

    A dependency, `who: Principal = Depends(principal)`, and a plain function
    for middleware. None on a route with no `auth=`, and for an anonymous
    caller on one declared `optional(...)`.
    """
    return request.locals.get(PRINCIPAL)

optional

optional(auth: Any) -> _Optional

Accept anonymous callers too.

@app.get("/feed", auth=optional(tokens))
async def feed(_: Request, who=Depends(principal)): ...   # None if anonymous

Only a request with no credential is anonymous. One carrying a wrong credential is still refused: an expired token is not the same as none, and treating it so would hide from the client that it needs a new one.

Source code in python/oxbrook/auth.py
def optional(auth: Any) -> _Optional:
    """Accept anonymous callers too.

        @app.get("/feed", auth=optional(tokens))
        async def feed(_: Request, who=Depends(principal)): ...   # None if anonymous

    Only a request with no credential is anonymous. One carrying a wrong
    credential is still refused: an expired token is not the same as none, and
    treating it so would hide from the client that it needs a new one.
    """
    if isinstance(auth, _Optional):
        raise TypeError("optional() of optional() is the same thing; use one")
    return _Optional(_checked(auth, "optional()"))