Skip to content

0.15: typed services and enforced plugin contracts

The async Python API now covers email OTP, token-based verification, JWT minting, and audit queries without constructing a FastAPI Request. Install the relevant plugins as before. The existing HTTP paths and existing command managers remain available, with the security corrections below.

Typed service namespaces

  • auth.otp: send, check, sign_in, verify_email, request_password_reset, reset_password, request_email_change, change_email
  • auth.verification: send and confirm; also available as auth.api.verification
  • auth.jwt: issue and jwks; requires the JWT extra and plugin
  • auth.audit: list and list_all; requires the audit plugin
  • auth.plugins.get(EmailOtpApi | JwtApi | AuditLogsApi): use an individual API class as the argument to obtain the plugin-contributed, statically typed API

Import service classes and request models from fastauth.runtime.services. Existing request-model imports remain supported. Requests and results are Pydantic models. Flow exceptions are the same exceptions mapped to HTTP error codes; Pydantic validation errors correspond to HTTP request validation errors. Services fail with FeatureNotEnabledError when the required plugin is absent.

from pydantic import SecretStr

from fastauth.api.commands import BearerCredentialDelivery
from fastauth.runtime.services import EmailOtpPurpose, SendOtpRequest, SignInOtpRequest

await auth.otp.send(SendOtpRequest(email="person@example.com", purpose=EmailOtpPurpose.SIGN_IN))
# The application receives the user's code through its own input boundary.
result = await auth.otp.sign_in(
    SignInOtpRequest(
        email="person@example.com",
        otp=SecretStr(submitted_code),
        delivery=BearerCredentialDelivery(),
    )
)
assert result.credentials is not None
session_token = SecretStr(result.credentials.token.root)
public_keys = await auth.jwt.jwks()
application_jwt = await auth.jwt.issue(session_token)
events = await auth.audit.list(session_token)

VerifyEmailRequest now accepts the same optional delivery discriminator as sign-in. Its default remains cookie delivery; explicit bearer delivery returns credentials and, when enabled, a refresh token. Both HTTP and SDK validate the email/password plugin's allow_bearer_tokens setting before consuming the token. Python calls do not set browser cookies; choose bearer delivery when Python needs the returned credentials.

OTP email changes take an actual session token, and require the email-change option to be enabled. JWT issuance and audit reads also resolve actual tokens through the configured session strategy. AuditQuery supports typed event, identifier and pagination filters, with a maximum page size of 100. list_all requires the authenticated user to be in AuditLogsOptions.admin_user_ids. Audit delivery remains best-effort; this release does not add a durable outbox.

Trusted SDK calls and custom endpoints

ID-based UserPrincipal, SessionPrincipal, user-management and API-key management methods are trusted server APIs. A supplied ID is a reference, not proof of authentication. Keep provisioning, storage-level audit queries, and maintenance inside application-authorized server code. Never copy an untrusted body user_id into a principal as an authentication shortcut. Token-taking service methods resolve the configured session strategy; application resource authorization remains the application's responsibility.

The SDK intentionally does not apply IP rate limits automatically: background jobs and trusted application calls need not represent a network request. RequestContext carries metadata and does not itself enable rate limiting. At a custom network entry point, opt into the shared boundary explicitly:

from fastauth.api.commands import RequestContext
from fastauth.web.fastapi import client_ip

# Choose a canonical relative path so the same limiter rule/bucket is used.
await auth.actions.check(
    "/sign-in/email",
    context=RequestContext(ip_address=client_ip(request, auth.context)),
)
result = await auth.sign_in.email(email, password)

Alternatively, await auth.actions.run(path, async_operation, context=context) checks the limiter before invoking an async callable returning a Pydantic model. The boundary rejects a missing IP when limiting is enabled. Use validated proxy-aware request metadata, not arbitrary forwarded headers. The boundary is abuse control, not an authorization check. Do not apply it a second time to a built-in route: the router already consumes its limiter once per request.

Production inspection reports a warning when the enabled rate limiter uses process-local memory. Select database-backed limiting for a shared budget across workers; each process's memory budget is independent.

API-key protected custom routes

auth.depends.api_key(required_permissions=PermissionSet(...)) verifies a key from x-api-key (or header_name=...), applies the plugin's verifier and usage limits, and returns ApiKeyView. Missing, invalid, or under-scoped keys reject with 401. Register auth.add_middleware(app) to install the FastAuth exception handler on application-owned routes as well as the security middleware.

from typing import Annotated
from fastapi import Depends
from fastauth.api.responses import ApiKeyView
from fastauth.domain.value_objects import PermissionSet

ReadKey = Annotated[
    ApiKeyView,
    Depends(
        auth.depends.api_key(required_permissions=PermissionSet({"files": frozenset({"read"})}))
    ),
]

OpenAPI describes this actual header dependency. The existing /api-key/verify endpoint takes its key in the request body and remains a public verification endpoint, not an API-key-header-protected resource.

Omitted and null profile fields

The Python manager, command API and HTTP PATCH now agree:

Input name / image metadata username
Omitted Preserve Preserve Preserve
Explicit None / JSON null Clear Validation error Validation error
Value Replace Replace object Apply username-change policy

For example, auth.users.update(uid, image=None) clears the image without changing the name. Previously Python silently omitted some explicit nulls. If an application used None to mean “leave untouched”, omit the argument instead. A dynamic caller may use the immutable OMITTED sentinel from fastauth.runtime.sdk_managers.

Plugin security and OpenAPI

  • auth_required=True is enforced before plugin request hooks, endpoint hooks, middleware, or the handler. Session cookie and bearer alternatives appear in the mounted OpenAPI schema
  • server_only=True removes the endpoint from HTTP routing and OpenAPI while retaining plugin metadata/server API access
  • csrf_policy=None or "inherit" uses the application's configured CSRF middleware. "require" and "required" enforce trusted-origin checks at the route boundary even if the host omitted/disabled the middleware. Bearer-only requests remain exempt; mixed cookie/bearer requests require a trusted origin
  • Other CSRF policy strings are rejected at startup. There is no implicit “disable protection” metadata mode
  • Route names and effective operation IDs must be unique. Previously ambiguous names could alias security metadata or generate unusable client operations
  • Explicit operation_id, deprecated, openapi_extra, and error_codes are now emitted. Error responses use ErrorResponse; declared error codes appear in x-fastauth-error-codes. Core operation IDs remain stable across prefixes
  • OpenAPI generation is scoped to the mounted app, so generating an offline schema first does not leak unprefixed paths into a later mounted schema

Security exception to the usual deprecation window: the unauthenticated global POST /api-key/delete-all-expired HTTP endpoint is no longer mounted. Use the existing trusted ApiKeysApi.delete_expired() or maintenance API from an application-authorized job. Also, previously descriptive security flags now restrict access as declared; relying on their non-enforcement was unsafe.

User mutation hooks

User BEFORE_UPDATE / AFTER_UPDATE hooks cover profile updates, token-based email verification, OTP sign-in auto-verification, OTP email verification, token-based email-change request/confirmation/expired-pending cleanup, and OTP email-change request/confirmation. An already-verified/no-op path does not promise a write or update hooks.

The shared account-deletion path covers both password and confirmation-token deletion with user BEFORE_DELETE / AFTER_DELETE hooks. Before-delete can abort, but cannot redirect deletion to a replacement user's ID.

Before-update receives the proposed user; a returned User replaces it, and None preserves it. After hooks run only after successful persistence and see the stored result. Before-hook exceptions abort the write. After-hook exceptions propagate but cannot roll back a committed mutation. Hook authors are trusted; do not mutate IDs or privileged fields casually.

These are application-flow hooks, not automatic adapter interceptors. Direct adapter writes do not invoke them. Password changes mutate credential Account records; this release does not promise account, session, token, or API-key mutation hooks. Existing create-hook semantics remain documented by their flows.

JWT session principals in trusted SDK commands

With the first-party JWT plugin and JWT session strategy, password change, password setup and revoke-other-sessions accept the logical session ID returned by authentication. These sessions have no database session row, so the SDK no longer requires one. Database sessions retain their existing user-owned row lookup; a JWT-looking ID does not bypass that check for a database strategy.

SessionPrincipal remains an application-authorized reference, not proof that a JWT was verified, is unexpired, or belongs to a particular user. Authenticate at the custom request boundary and derive both IDs from that result:

actor = await auth.policy.authenticate(submitted_session_token)
await auth.passwords.change(
    user_id=actor.user.id,
    session_id=actor.session.id,
    current_password=current_password,
    new_password=new_password,
)

Changing/setting a password or revoking other sessions preserves the current logical refresh family and revokes the user's other refresh families, as the HTTP routes do. Already-issued stateless access JWTs retain their normal expiry semantics; this does not introduce per-token instant revocation. Accepted legacy access tokens retain their deterministic legacy-jwt: reference until expiry; this does not restore legacy refresh families invalidated during migration.