Ir para o conteúdo

tempest_fastapi_sdk.api

A integração com o FastAPI: app factory, middlewares, routers prontos, dependências, OAuth, cookies, SPA e webhooks.

« Admin, dados e API


register_exception_handlers

register_exception_handlers(
    app: FastAPI,
    *,
    log_traceback: bool = True,
    include_traceback: bool = False,
    log_level: int = ERROR,
    catalog: MessageCatalog | None = None,
    default_locale: str = DEFAULT_LOCALE,
    locale_resolver: LocaleResolver | None = None,
    logger: Logger | None = None,
    on_server_error: ServerErrorCallback | None = None,
    envelope_validation_errors: bool = False,
    envelope_client_errors: bool = False,
    redact_exception: ExceptionRedactor | None = redact_database_errors,
    envelope_builder: ErrorEnvelopeBuilder | None = None,
) -> None

Register the SDK's exception handlers on a FastAPI app.

Wires three handlers, in order of specificity:

  • :class:AppException → :func:app_exception_handler. Every domain-specific subclass returned by routers, services and repositories is serialized consistently.
  • :class:starlette.exceptions.HTTPException → :func:make_http_exception_handler factory. raise HTTPException(500, ...) would otherwise bypass the SDK's catch-all (Starlette intercepts HTTPException inside its own middleware), so this handler restores the log + envelope behavior for 5xx HTTPExceptions while leaving 4xx untouched.
  • :class:Exception (catch-all) → traceback logger + generic 500 envelope. Without this, FastAPI's default returns the string "Internal Server Error" with no log entry beyond the access line, leaving operators blind to real failures.

The catch-all is also installed as :class:~tempest_fastapi_sdk.ErrorEnvelopeMiddleware, appended as the innermost user middleware. Starlette runs the Exception handler inside ServerErrorMiddleware, outside every middleware the app added, so on its own the 500 envelope never passes through CORSMiddleware: it leaves without Access-Control-Allow-Origin and without X-Request-ID, the browser discards it, and fetch rejects with TypeError: Failed to fetch. From the innermost slot every middleware decorates the 500 as it decorates a 200, whatever order add_middleware, :func:~tempest_fastapi_sdk.apply_cors and this function are called in — add_middleware always inserts outside it. The handler stays registered for an exception raised by a middleware itself, which the innermost layer cannot see, and skips the exception the layer already answered, so each 500 is logged and reported to on_server_error once.

Parameters:

Name Type Description Default
app FastAPI

The FastAPI application to wire.

required
log_traceback bool

Whether the 5xx handlers attach the full traceback to the log record. Defaults to True (always emit the trace). Pass False to silence the trace when an APM / Sentry / equivalent is already capturing the failure.

True
include_traceback bool

When True, the unhandled-500 response body includes the formatted traceback under details.traceback. Use only in development.

False
log_level int

Logging level used by the 5xx handlers. Defaults to :data:logging.ERROR.

ERROR
catalog MessageCatalog | None

When set, the :class:AppException handler localizes detail against this catalog (see :func:make_app_exception_handler). Use :func:tempest_fastapi_sdk.default_message_catalog for the built-in PT-BR + EN strings, optionally :meth:MessageCatalog.merge-d with domain codes.

None
default_locale str

Locale used when Accept-Language is absent or unmatched. Defaults to "pt-BR".

DEFAULT_LOCALE
locale_resolver LocaleResolver | None

Optional callable taking the request and returning a locale tag (or None to fall back to Accept-Language negotiation). Forwarded to the :class:AppException, :class:HTTPException and :class:RequestValidationError handlers. Pass :func:make_locale_resolver to read ?lang=, request.state.locale and request.state.user.locale before falling back to Accept-Language.

None
logger Logger | None

Where every handler logs. None uses the SDK's own logger, which a service configuring LogUtils(..., scope="logger") does not cover. Pass LogUtils(...).logger. See :func:make_unhandled_exception_handler for the measurement.

None
on_server_error ServerErrorCallback | None

Called with (request, exc) after any 5xx response is built, as a background task. Fires on all three 5xx paths and never on a 4xx; a failure inside it is logged and swallowed.

None
envelope_validation_errors bool

Whether to register the :class:fastapi.exceptions.RequestValidationError handler, putting the 422 in the envelope and localizing it by pydantic error type. Also rewrites the HTTPValidationError component of the OpenAPI schema so it does not contradict the runtime. Off by default: the 422 body changes shape, which breaks a client that models detail as an array.

False
envelope_client_errors bool

Whether every 4xx answers the envelope — the 422 included, so this implies envelope_validation_errors. A raw HTTPException(403), the 401 from a security dependency, an unknown route and a wrong method all reach this SDK's handler and answered a bare {"detail": "<English phrase>"} with no code before v0.285.0. Off by default for the same reason as above.

A detail the caller wrote is preserved; only the framework's own status phrase is localized. See :func:make_http_exception_handler.

False
redact_exception ExceptionRedactor | None

Maps the caught exception to the one the 5xx log records of all three handlers carries in exc_info. Defaults to :func:~tempest_fastapi_sdk.redact_database_errors, which replaces a sqlalchemy.exc.DBAPIError anywhere in the chain with a summary: the Postgres DETAIL line quotes the value the client sent, and hide_parameters=True does not remove it. None logs the exception as raised. The response and on_server_error always receive the original.

redact_database_errors
envelope_builder ErrorEnvelopeBuilder | None

Builds the body of every error response from an :class:~tempest_fastapi_sdk.ErrorEnvelopeContext — the :class:AppException, every :class:HTTPException (4xx included, so an unknown route and a wrong method too, as if envelope_client_errors were on), the unhandled 500 and, when its handler is registered, the 422. Status code and headers are kept. A builder that raises is logged and the SDK envelope is answered instead. None keeps the SDK envelope. The OpenAPI schema keeps describing the SDK envelope.

None

Raises:

Type Description
RuntimeError

If app already built its middleware stack (it served a request or started), where a new layer can no longer be added. Checked before anything is registered, so a refused call leaves app untouched.

Notes

Calling this twice installs the envelope layer once; the second call replaces the handler it renders with.

Starlette types add_exception_handler to accept only callables keyed by the broad Exception, while these handlers narrow their second argument to AppException / StarletteHTTPException for the SDK consumer's benefit. The type: ignore at each call is therefore safe: the narrowing is exactly what the registration key guarantees.

make_app_exception_handler

make_app_exception_handler(
    *,
    log_level: int = INFO,
    catalog: MessageCatalog | None = None,
    default_locale: str = DEFAULT_LOCALE,
    locale_resolver: LocaleResolver | None = None,
    logger: Logger | None = None,
    on_server_error: ServerErrorCallback | None = None,
    redact_exception: ExceptionRedactor | None = redact_database_errors,
    envelope_builder: ErrorEnvelopeBuilder | None = None,
) -> AppExceptionHandler

Build the handler for :class:AppException subclasses.

Serializes the exception to the SDK envelope and emits an INFO-level log line (no traceback — 4xx is normal client flow). 5xx AppException subclasses bump up to log_level with a traceback and the :data:HTTP_500_MARKER flag so 500.log captures them.

An exception class that declares its own log_level (an expected answer, such as 503 INTEGRATION_DISABLED) is logged at that level instead, with no traceback, no marker and no on_server_error call.

When a catalog is supplied, the detail field is localized: the locale comes from locale_resolver when it names one the catalog supports, otherwise it is negotiated from the request's Accept-Language header (falling back to default_locale), and the exception's message_key (or its code) is resolved against the catalog. A missing translation falls back to the exception's literal detail, so partial catalogs never blank out a message.

An exception that declares a field adds it to the envelope, so a 409 or a 401 about one input says which one. The key is omitted (never null) when there is no culprit input, which is also the correct answer for invalid credentials — naming the field there turns the response into an account-enumeration oracle.

Parameters:

Name Type Description Default
log_level int

Level used only for 5xx AppException records (the 4xx path always logs at INFO regardless, since elevating client errors to WARN/ERROR adds noise). Defaults to :data:logging.INFO; pass logging.ERROR (or pass log_level=logging.ERROR through :func:register_exception_handlers) when 5xx AppException subclasses should trigger paging.

INFO
catalog MessageCatalog | None

Message catalog used to localize detail. None keeps the literal message.

None
default_locale str

Locale used when Accept-Language is absent or matches nothing in the catalog.

DEFAULT_LOCALE
locale_resolver LocaleResolver | None

Optional callable taking the request and returning a locale tag (or None to fall back to Accept-Language negotiation). Takes precedence over Accept-Language whenever it returns a locale the catalog supports. See :func:make_locale_resolver.

None
logger Logger | None

Where this handler logs. None uses the SDK's own tempest_fastapi_sdk.api.handlers logger — which a service that configures logging with LogUtils(..., scope="logger") does not cover: measured, the records then reach neither 500.log nor error.log. Pass LogUtils(...).logger to route them into the service's own configuration.

Typed as logging.Logger and not as the :class:~tempest_fastapi_sdk.RetryLogger protocol on purpose. That protocol carries warning and error only, with no extra= and no exc_info=, and these handlers pass both plus the 500.log marker. Measured, no single type spans the two candidates: LogUtils.error(extra=...) stores a field named extra, and logging.Logger.error(request_id=...) raises TypeError.

None
on_server_error ServerErrorCallback | None

Called with (request, exc) after a 5xx response is built, as a background task, so it never delays or alters the response. A failure inside it is logged and swallowed — a notifier that raises propagates up the ASGI stack and replaces the original exception in whatever the server logs.

None
redact_exception ExceptionRedactor | None

Maps the caught exception to the one the 5xx log record carries in exc_info. Defaults to :func:~tempest_fastapi_sdk.redact_database_errors, which replaces a sqlalchemy.exc.DBAPIError anywhere in the chain with a summary: the Postgres DETAIL line quotes the value the client sent, and hide_parameters=True does not remove it. None logs the exception as raised. The response and on_server_error always receive the original.

redact_database_errors
envelope_builder ErrorEnvelopeBuilder | None

Builds the response body from an :class:~tempest_fastapi_sdk.ErrorEnvelopeContext in place of the SDK envelope. Status code and headers stay this handler's; a builder that raises is logged and the SDK envelope is answered instead. None keeps the SDK envelope.

None

Returns:

Name Type Description
AppExceptionHandler AppExceptionHandler

An async (request, exc) -> JSONResponse

AppExceptionHandler

callable.

Notes

The request id is looked up in three places, in order: the contextvar, which works for plain ASGI middlewares; the inbound X-Request-ID header, needed because BaseHTTPMiddleware spawns a child task whose contextvars do not always reach the exception handler; and finally None.

make_http_exception_handler

make_http_exception_handler(
    *,
    log_traceback: bool = True,
    log_level: int = ERROR,
    logger: Logger | None = None,
    on_server_error: ServerErrorCallback | None = None,
    catalog: MessageCatalog | None = None,
    default_locale: str = DEFAULT_LOCALE,
    locale_resolver: LocaleResolver | None = None,
    envelope_client_errors: bool = False,
    redact_exception: ExceptionRedactor | None = redact_database_errors,
    envelope_builder: ErrorEnvelopeBuilder | None = None,
) -> HTTPExceptionHandler

Build the handler for raw :class:starlette.exceptions.HTTPException.

Without this, raise HTTPException(500, "...") (or 404, 403, …) bypasses the SDK's Exception catch-all entirely: Starlette intercepts HTTPException instances inside its ExceptionMiddleware and routes them to its own default — a bare JSONResponse({"detail": exc.detail}) with no log entry. Operators see the 500 in the access log and no trace.

This handler closes that gap for 5xx HTTPExceptions:

  1. Whenever exc.status_code >= 500, the failure is logged at log_level (ERROR by default) under tempest_fastapi_sdk.api.handlers. The record is flagged with :data:HTTP_500_MARKER so configure_logging(log_dir=…) routes it to the dedicated 500.log alongside the trace.
  2. The response keeps the original status_code / headers and adds the SDK envelope shape (detail / code / details), so frontends consuming the same envelope across :class:AppException and raw HTTPException don't need to branch.

4xx HTTPExceptions are returned untouched (Starlette's default behavior), since those represent normal client-side outcomes that don't deserve a stack trace.

Parameters:

Name Type Description Default
log_traceback bool

Whether to attach exc_info=exc to the 5xx log record. True by default.

True
log_level int

Logging level used for 5xx records.

ERROR
catalog MessageCatalog | None

Catalog used to localize a generic 4xx detail when envelope_client_errors is on. This handler had no catalog parameter at all before v0.285.0, which is why a service configuring one still answered {"detail": "Forbidden"} in English.

None
default_locale str

Locale used when Accept-Language is absent or matches nothing in the catalog.

DEFAULT_LOCALE
locale_resolver LocaleResolver | None

Optional callable taking the request and returning a locale tag (or None to fall back to Accept-Language negotiation). See :func:make_locale_resolver.

None
envelope_client_errors bool

Whether a 4xx answers the SDK envelope (detail / code / details) instead of Starlette's bare {"detail": ...}. Off by default: adding code is additive, but a client that pins the exact body shape still sees a change.

False
logger Logger | None

Where this handler logs. None uses the SDK's own tempest_fastapi_sdk.api.handlers logger — which a service that configures logging with LogUtils(..., scope="logger") does not cover: measured, the records then reach neither 500.log nor error.log. Pass LogUtils(...).logger to route them into the service's own configuration.

Typed as logging.Logger and not as the :class:~tempest_fastapi_sdk.RetryLogger protocol on purpose. That protocol carries warning and error only, with no extra= and no exc_info=, and these handlers pass both plus the 500.log marker. Measured, no single type spans the two candidates: LogUtils.error(extra=...) stores a field named extra, and logging.Logger.error(request_id=...) raises TypeError.

None
on_server_error ServerErrorCallback | None

Called with (request, exc) after a 5xx response is built, as a background task, so it never delays or alters the response. A failure inside it is logged and swallowed — a notifier that raises propagates up the ASGI stack and replaces the original exception in whatever the server logs.

None
redact_exception ExceptionRedactor | None

Maps the caught exception to the one the 5xx log record carries in exc_info. Defaults to :func:~tempest_fastapi_sdk.redact_database_errors, which replaces a sqlalchemy.exc.DBAPIError anywhere in the chain with a summary: the Postgres DETAIL line quotes the value the client sent, and hide_parameters=True does not remove it. None logs the exception as raised. The response and on_server_error always receive the original.

redact_database_errors
envelope_builder ErrorEnvelopeBuilder | None

Builds the response body from an :class:~tempest_fastapi_sdk.ErrorEnvelopeContext in place of the SDK envelope. Status code and headers stay this handler's; a builder that raises is logged and the SDK envelope is answered instead. None keeps the SDK envelope. Setting it also envelopes every 4xx, as if envelope_client_errors were on: a service that shapes its own body wants the 404/405 in it too.

None

Returns:

Name Type Description
HTTPExceptionHandler HTTPExceptionHandler

An async

HTTPExceptionHandler

(request, exc) -> JSONResponse callable ready to pass to

HTTPExceptionHandler

meth:FastAPI.add_exception_handler.

Notes

4xx responses are logged at INFO with no traceback and no 500.log marker, so an operator can still see which request failed without paying for a stack trace on normal client errors.

make_unhandled_exception_handler

make_unhandled_exception_handler(
    *,
    log_traceback: bool = True,
    include_traceback: bool = False,
    log_level: int = ERROR,
    logger: Logger | None = None,
    on_server_error: ServerErrorCallback | None = None,
    redact_exception: ExceptionRedactor | None = redact_database_errors,
    envelope_builder: ErrorEnvelopeBuilder | None = None,
) -> UnhandledExceptionHandler

Build the catch-all handler for non-:class:AppException errors.

Default FastAPI/Starlette behavior on uncaught exceptions is to return a bare Internal Server Error string and emit nothing beyond the access log line — the actual traceback never reaches the logger and never reaches the operator. This handler closes that gap:

  1. Logs the failure at log_level (ERROR by default) under the tempest_fastapi_sdk.api.handlers logger. When log_traceback=True (the default), the full traceback is attached via exc_info so the application's LogUtils / configure_logging setup serializes it. The record is flagged with :data:tempest_fastapi_sdk.core.logging.HTTP_500_MARKER so configure_logging(log_dir=...) can route it to a dedicated 500.log.
  2. Returns the canonical SDK JSON envelope with code="INTERNAL_SERVER_ERROR" and status_code=500.
  3. When include_traceback=True (development only) appends the formatted traceback under details.traceback so the failure is visible in the browser too. Leave it off in production — the body would leak module paths, secrets in repr output and SQL fragments.

Parameters:

Name Type Description Default
log_traceback bool

Whether to attach the full traceback to the log record via exc_info. Defaults to True — we want operators to see the cause every time. Pass False only when the trace would be noisy AND the failure is already being captured elsewhere (e.g. an APM agent).

True
include_traceback bool

Whether to surface the traceback in the response body. Off in production.

False
log_level int

Logging level used by the catch-all handler.

ERROR
logger Logger | None

Where this handler logs. None uses the SDK's own tempest_fastapi_sdk.api.handlers logger — which a service that configures logging with LogUtils(..., scope="logger") does not cover: measured, the records then reach neither 500.log nor error.log. Pass LogUtils(...).logger to route them into the service's own configuration.

Typed as logging.Logger and not as the :class:~tempest_fastapi_sdk.RetryLogger protocol on purpose. That protocol carries warning and error only, with no extra= and no exc_info=, and these handlers pass both plus the 500.log marker. Measured, no single type spans the two candidates: LogUtils.error(extra=...) stores a field named extra, and logging.Logger.error(request_id=...) raises TypeError.

None
on_server_error ServerErrorCallback | None

Called with (request, exc) after a 5xx response is built, as a background task, so it never delays or alters the response. A failure inside it is logged and swallowed — a notifier that raises propagates up the ASGI stack and replaces the original exception in whatever the server logs.

None
redact_exception ExceptionRedactor | None

Maps the caught exception to the one the 5xx log record carries in exc_info. Defaults to :func:~tempest_fastapi_sdk.redact_database_errors, which replaces a sqlalchemy.exc.DBAPIError anywhere in the chain with a summary: the Postgres DETAIL line quotes the value the client sent, and hide_parameters=True does not remove it. None logs the exception as raised. The response and on_server_error always receive the original.

redact_database_errors
envelope_builder ErrorEnvelopeBuilder | None

Builds the response body from an :class:~tempest_fastapi_sdk.ErrorEnvelopeContext in place of the SDK envelope. Status code and headers stay this handler's; a builder that raises is logged and the SDK envelope is answered instead. None keeps the SDK envelope.

None

Returns:

Name Type Description
UnhandledExceptionHandler UnhandledExceptionHandler

An async

UnhandledExceptionHandler

(request, exc) -> JSONResponse callable ready to pass to

UnhandledExceptionHandler

meth:FastAPI.add_exception_handler.

redact_database_errors

redact_database_errors(error: BaseException) -> BaseException

Return error, or a stand-in when a database error is in it.

The default redact_exception of every SDK 5xx handler. Walks the __cause__/__context__ chain and exception-group members; when none is a sqlalchemy.exc.DBAPIError the original comes back untouched, so a non-database 500 logs exactly as before. Otherwise the chain is rebuilt from :class:RedactedError links that keep every frame and replace the database error's text with a summary — for an IntegrityError, unique violation; constraint=...; table=...; columns=... — ending in :data:~tempest_fastapi_sdk.WITHHELD_NOTICE.

What is lost, on purpose: the driver's exception (asyncpg's UniqueViolationError and SQLAlchemy's adapter around it), whose text repeats the server sentence. Its type survives in the summary as driver=....

Example:

>>> from sqlalchemy.exc import IntegrityError
>>> from tempest_fastapi_sdk import redact_database_errors
>>>
>>> def logged(error: IntegrityError) -> str:
...     return str(redact_database_errors(error))

Parameters:

Name Type Description Default
error BaseException

The exception a handler caught.

required

Returns:

Name Type Description
BaseException BaseException

error itself, or its redacted copy.

RedactedError

RedactedError(original_type: str, text: str)

Bases: Exception

Stand-in for one link of an exception chain, safe to log.

The traceback module formats an exception from its type, its text, its frames and its __cause__/__context__ links. A stand-in keeps the frames (__traceback__ is the original's, so every File ..., line ... entry is unchanged) and the chain shape, and replaces only the text. The original type is not lost: it opens the text, as sqlalchemy.exc.IntegrityError: ....

Attributes:

Name Type Description
original_type str

Dotted name of the type this link stands in for.

Build the stand-in.

Parameters:

Name Type Description Default
original_type str

Dotted name of the replaced type.

required
text str

What the log line says after the type.

required

ExceptionRedactor module-attribute

ExceptionRedactor = Callable[[BaseException], BaseException]

Map the exception a handler caught to the one its log record carries.

Receives the original exception and returns what goes into exc_info: the same object when there is nothing to hide, or a stand-in whose text is safe to write to disk. Must not raise and must not mutate its argument — the original is still the one on_server_error receives.

error_responses

error_responses(
    *exceptions: type[AppException],
    catalog: MessageCatalog | None = None,
    locale: str = DEFAULT_LOCALE,
    descriptions: Mapping[int, str] | None = None,
) -> dict[int | str, dict[str, Any]]

Build the FastAPI responses= dict for a set of exceptions.

Reads status_code / code / message / details_example off each class — no instantiation, so no knowledge of each __init__ signature is needed. This is why the SDK documents declaring code in the class body: an exception that only receives its code at the raise site reports the inherited generic value here, and :class:~tempest_fastapi_sdk.InheritedErrorCodeWarning flags that at class creation.

OpenAPI allows exactly one response object per status code, so exceptions are grouped by status and their codes distinguished through the examples map — the shape Swagger UI and ReDoc render as a selector. Two 404s with different codes are therefore both visible, which a plain {404: {...}} entry could never express::

{
    404: {
        "model": ErrorResponseSchema,
        "description": "SERVICE_NOT_FOUND | CATEGORY_NOT_FOUND",
        "content": {"application/json": {"examples": {
            "SERVICE_NOT_FOUND": {"summary": ..., "value": {...}},
            "CATEGORY_NOT_FOUND": {"summary": ..., "value": {...}},
        }}},
    },
}

Usage::

from tempest_fastapi_sdk import error_responses

@router.post(
    "/{service_id}/candidates",
    status_code=201,
    responses=error_responses(
        ServiceNotFoundException,
        CategoryNotFoundException,
        ServiceFullException,
    ),
)
async def apply_to_service(service_id: UUID) -> CandidateResponseSchema:
    ...

Parameters:

Name Type Description Default
*exceptions type[AppException]

The exception classes the route can raise. Order decides the order of the examples map; duplicates are collapsed.

()
catalog MessageCatalog | None

Catalog used to fill each example's detail, keeping the text out of the route declaration. None (the default) uses the class-level message verbatim, so the generated spec never picks a language implicitly — pass :func:tempest_fastapi_sdk.default_message_catalog (merged with the project's codes) to localize.

None
locale str

Locale resolved against catalog. Ignored when catalog is None.

DEFAULT_LOCALE
descriptions Mapping[int, str] | None

Per-status description overrides. Unlisted statuses keep the generated "CODE_A | CODE_B" summary.

None

Returns:

Type Description
dict[int | str, dict[str, Any]]

dict[int | str, dict[str, Any]]: A mapping ready to hand to

dict[int | str, dict[str, Any]]

responses= on any FastAPI route decorator. Empty when no

dict[int | str, dict[str, Any]]

exceptions are given, so an unconditional

dict[int | str, dict[str, Any]]

responses=error_responses(*maybe_empty) stays valid.

Raises:

Type Description
TypeError

If an argument is not an :class:AppException subclass. Passing an instance is the likely mistake, and silently producing an empty schema would be worse than failing at import.

Notes

Two classes may legitimately share a code — a base and a narrowing subclass. An examples map cannot hold two entries under one name, so the duplicate key is qualified with the class name and both examples survive.

raises

raises(
    *exceptions: type[AppException],
    catalog: MessageCatalog | None = None,
    locale: str = DEFAULT_LOCALE,
) -> Callable[[EndpointT], EndpointT]

Declare the exceptions a route handler's flow can raise.

Same information as :func:error_responses, expressed next to the handler instead of inside the route decorator's argument list::

@router.post("/{service_id}/candidates", status_code=201)
@raises(
    ServiceNotFoundException,
    ServiceFullException,
    CandidateAlreadyExistsException,
)
async def apply_to_service(service_id: UUID) -> CandidateResponseSchema:
    ...

The decorator only tags the function — it returns the same object, never a wrapper, so FastAPI still sees the original signature, annotations and dependencies. Turning the tag into responses= is :class:TempestAPIRouter's job; on a plain APIRouter the tag is inert, and responses=error_responses(...) is the way to go.

Note the decorator order: @raises must sit below @router.post so it runs first and the route decorator receives an already-tagged function.

Parameters:

Name Type Description Default
*exceptions type[AppException]

The exception classes the handler's flow can raise.

()
catalog MessageCatalog | None

Forwarded to :func:error_responses.

None
locale str

Forwarded to :func:error_responses.

DEFAULT_LOCALE

Returns:

Type Description
Callable[[EndpointT], EndpointT]

Callable[[EndpointT], EndpointT]: A decorator that attaches a

Callable[[EndpointT], EndpointT]

class:RaisesSpec to the endpoint and returns it unchanged.

TempestAPIRouter

Bases: APIRouter

APIRouter that turns :func:raises tags into responses=.

A drop-in replacement for fastapi.APIRouter: every argument, method and behavior is inherited, and the only addition is that :meth:add_api_route expands a handler's :func:raises tag into the responses mapping :func:error_responses would have produced.

::

from tempest_fastapi_sdk import TempestAPIRouter, raises

router: TempestAPIRouter = TempestAPIRouter(prefix="/api/jobs")

@router.post("/{service_id}/candidates", status_code=201)
@raises(ServiceNotFoundException, ServiceFullException)
async def apply_to_service(service_id: UUID) -> CandidateResponseSchema:
    ...

Injection happens before APIRoute is constructed, so the declared model reaches components.schemas as a proper $ref (mutating route.responses afterwards would only carry the description — FastAPI builds the response fields in the route's constructor). app.include_router(router) preserves the result: FastAPI copies each route's responses onto the parent.

An explicit responses= on the route decorator wins per status code, so a hand-written entry can always override the generated one.

add_api_route

add_api_route(path: str, endpoint: Callable[..., Any], **kwargs: Any) -> None

Register a route, expanding the endpoint's :func:raises tag.

Parameters:

Name Type Description Default
path str

The route path, relative to the router prefix.

required
endpoint Callable[..., Any]

The handler.

required
**kwargs Any

Every other APIRouter.add_api_route argument, forwarded untouched. responses is merged on top of the generated mapping so an explicit entry takes precedence for its status code.

{}

RaisesSpec dataclass

RaisesSpec(
    exceptions: tuple[type[AppException], ...],
    catalog: MessageCatalog | None,
    locale: str,
)

The error contract :func:raises attaches to an endpoint.

Attributes:

Name Type Description
exceptions tuple[type[AppException], ...]

The exception classes the handler's flow can raise, in declaration order.

catalog MessageCatalog | None

Catalog used to fill each example's detail. None uses the class-level message.

locale str

Locale resolved against catalog.

declared_raises

declared_raises(endpoint: Callable[..., Any]) -> RaisesSpec | None

Return the :class:RaisesSpec attached to an endpoint, if any.

Parameters:

Name Type Description Default
endpoint Callable[..., Any]

A route handler, decorated with :func:raises or not.

required

Returns:

Type Description
RaisesSpec | None

RaisesSpec | None: The attached spec, or None when the

RaisesSpec | None

handler carries none.

prune_orphan_enum_schemas

prune_orphan_enum_schemas(app: FastAPI) -> None

Make app.openapi() leave out the enum components nothing uses.

Wraps app.openapi the way :func:~tempest_fastapi_sdk.api.error_docs.describe_validation_envelope does, so the pruning survives the schema being regenerated. Calling it twice is harmless: the second pass finds nothing to remove.

Parameters:

Name Type Description Default
app FastAPI

The application whose schema to prune.

required

drop_orphan_enum_schemas

drop_orphan_enum_schemas(document: dict[str, Any]) -> list[str]

Remove, in place, every enum component no $ref points at.

Parameters:

Name Type Description Default
document dict[str, Any]

The OpenAPI document.

required

Returns:

Type Description
list[str]

list[str]: The names removed, sorted.

make_signed_path_dependency

make_signed_path_dependency(
    *, secret: str, purpose: str
) -> Callable[..., Coroutine[Any, Any, None]]

Build a dependency that accepts only URLs signed by :func:sign_path.

The returned coroutine reads expires and signature from the query string and verifies them against the decoded request path (request.scope["path"]) — the same string :func:sign_path signed and the route matched. Attach it with dependencies=[Depends(...)] and the handler only runs for an authentic, unexpired URL; nothing else about the caller is checked, because the mapper that issued the URL already authorized them.

Both query parameters are declared, so they show up in the OpenAPI schema of the route. They are read as strings and validated here rather than by FastAPI, so a missing or non-numeric expires answers the same 403 as a forged one instead of a 422 that names the parameter. That includes an expires longer than Python's int-conversion limit (4300 digits), whose int() raises ValueError and would otherwise be a 500.

Parameters:

Name Type Description Default
secret str

The secret the URLs are signed with.

required
purpose str

The purpose the URLs are signed for. A URL signed for another purpose is rejected.

required

Returns:

Type Description
Callable[..., Coroutine[Any, Any, None]]

Callable[..., Coroutine[Any, Any, None]]: An async FastAPI dependency

Callable[..., Coroutine[Any, Any, None]]

that returns None on success and raises

Callable[..., Coroutine[Any, Any, None]]

class:InvalidSignedURLException or

Callable[..., Coroutine[Any, Any, None]]

class:ExpiredSignedURLException (both 403) otherwise.

Raises:

Type Description
ValueError

If secret or purpose is empty — at build time, so a missing setting fails the boot instead of every request.

make_mfa_required_dependency

make_mfa_required_dependency(
    tokens: JWTUtils | Callable[[Request], JWTUtils],
    *,
    methods: Collection[str] = MFA_AMR_METHODS,
    bearer_scheme: HTTPBearer | None = None,
    cookie_name: str | None = None,
    strict: bool = False,
    legacy_claims: Collection[str] = (),
    unauthorized_message: str = MISSING_TOKEN_MESSAGE,
    forbidden_message: str = message,
) -> Callable[..., Coroutine[Any, Any, dict[str, Any]]]

Build a FastAPI dependency that admits only sessions that passed MFA.

Reads the access token the same way :func:make_bearer_token_dependency does and checks its amr claim (RFC 8176), which :class:~tempest_fastapi_sdk.UserAuthService stamps on every access token: ["pwd"] after a password login, ["pwd", "otp"] after /auth/mfa/verify or /auth/mfa/confirm. The token passes when amr holds at least one of methods.

A token without amr — minted before the claim existed, or by a refresh of a session whose origin was never recorded — is refused, so the rollout window never counts an unknown session as MFA. Those sessions get in again by running the two-step login.

Use it next to the dependency that loads the user, on the routes where a stolen password must not be enough::

require_mfa = make_mfa_required_dependency(jwt)

@router.post("/staff", dependencies=[Depends(require_mfa)])
async def create_staff(...) -> ...: ...

Parameters:

Name Type Description Default
tokens JWTUtils | Callable[[Request], JWTUtils]

The JWT helper used to verify the token, or a factory called with each request that returns it.

required
methods Collection[str]

amr values that count as a second factor. Defaults to :data:~tempest_fastapi_sdk.MFA_AMR_METHODS ({"otp"}, which covers TOTP and recovery codes). Add "hwk" when your WebAuthn ceremony requires user verification and a passkey login should satisfy the gate.

MFA_AMR_METHODS
bearer_scheme HTTPBearer | None

Override the bearer scheme.

None
cookie_name str | None

When set, fall back to this cookie for the access token if the Authorization header is absent — the cookie delivery mode of :func:~tempest_fastapi_sdk.make_auth_router.

None
strict bool

Forwarded to :func:make_bearer_token_dependency.

False
legacy_claims Collection[str]

Forwarded to :func:make_bearer_token_dependency.

()
unauthorized_message str

Message of the :class:UnauthorizedException raised when the token is missing or invalid.

MISSING_TOKEN_MESSAGE
forbidden_message str

Message of the :class:~tempest_fastapi_sdk.MFARequiredException (403, code MFA_REQUIRED) raised when the token is valid but no second factor is recorded on it.

message

Returns:

Type Description
Callable[..., Coroutine[Any, Any, dict[str, Any]]]

Callable[..., Coroutine[Any, Any, dict[str, Any]]]: An async FastAPI

Callable[..., Coroutine[Any, Any, dict[str, Any]]]

dependency yielding the decoded claims of an MFA session.

RouteDocs

RouteDocs(docs_locale: str | None = None)

The catalog, bound to the language one router is built in.

A factory builds one at the top (route_docs = RouteDocs(docs_locale)) and reads every operation's text through it. An unknown key raises :class:KeyError while the router is being built, so a route whose text is missing fails the first test that mounts it rather than shipping with an empty summary.

Attributes:

Name Type Description
locale DocsLocale

The resolved language.

Resolve the language and bind its tables.

Parameters:

Name Type Description Default
docs_locale str | None

Passed to :func:resolve_docs_locale.

None

summary

summary(key: str) -> str | None

Return the operation summary.

Parameters:

Name Type Description Default
key str

The operation key ("auth.login").

required

Returns:

Type Description
str | None

str | None: The summary, or None to let FastAPI derive it.

description

description(key: str, **params: str) -> str | None

Return the operation description, formatted when asked.

Parameters:

Name Type Description Default
key str

The operation key.

required
**params str

Placeholder values (prefix=...). Without any, the text is returned as stored, so a literal brace (/activate/{token}) needs no escaping.

{}

Returns:

Type Description
str | None

str | None: The description, or None to let FastAPI use

str | None

the endpoint docstring.

text

text(key: str) -> str

Return a parameter or response description.

Parameters:

Name Type Description Default
key str

The text key ("logs.read_logs.page").

required

Returns:

Name Type Description
str str

The description.

Raises:

Type Description
KeyError

When the catalog has no such text.

RouteDoc dataclass

RouteDoc(summary: str | None = None, description: str | None = None)

The OpenAPI text of one operation, in one language.

Attributes:

Name Type Description
summary str | None

The operation's summary. None lets FastAPI derive it from the endpoint name — kept for the English entries of routes that never declared one, so their document is unchanged.

description str | None

The operation's description. None lets FastAPI use the endpoint docstring, for the same reason. May hold :meth:str.format placeholders ({prefix}) that the router fills in.

resolve_docs_locale

resolve_docs_locale(docs_locale: str | None = None) -> DocsLocale

Decide the language a router documents itself in.

Parameters:

Name Type Description Default
docs_locale str | None

The factory's docs_locale= argument. None reads API_DOCS_LOCALE through :class:~tempest_fastapi_sdk.settings.ServerSettings (the environment and the .env file), whose default is "en-US".

None

Returns:

Name Type Description
DocsLocale DocsLocale

"en-US" or "pt-BR".

Raises:

Type Description
ValueError

When the argument names a language the catalog does not carry.

ValidationError

When API_DOCS_LOCALE does.

RequestIDMiddleware

RequestIDMiddleware(app: ASGIApp, header_name: str = 'X-Request-ID')

Bases: BaseHTTPMiddleware

Bind an X-Request-ID header to the request-scoped context.

Reads the inbound header (or generates a fresh UUID v4 when absent), stores it via :func:set_request_id so log records written during the request carry the request_id field, and echoes the same value back on the response so callers can trace end-to-end across services.

Parameters:

Name Type Description Default
app ASGIApp

The wrapped ASGI application.

required
header_name str

The header to read/write. Defaults to "X-Request-ID".

'X-Request-ID'

dispatch async

dispatch(
    request: Request, call_next: Callable[[Request], Awaitable[Response]]
) -> Response

Run the wrapped handler with a bound request ID.

Parameters:

Name Type Description Default
request Request

The inbound request.

required
call_next Callable[[Request], Awaitable[Response]]

The downstream ASGI handler.

required

Returns:

Name Type Description
Response Response

The handler's response with the request ID

Response

echoed in the configured header.

PublicSchemeMiddleware

PublicSchemeMiddleware(app: ASGIApp, scheme: Literal['http', 'https', ''] = '')

Overwrite scope["scheme"] with the scheme the browser used.

Starlette builds every absolute URL — request.url_for, and so the action of each admin panel form — from scope["scheme"]. Behind a proxy that terminates TLS that scope says http, because the proxy speaks plain HTTP to the app, and an HTTPS page renders <form action="http://.../admin/login">: the browser flags the password field as not secure.

The usual fix, uvicorn's --forwarded-allow-ips, trusts X-Forwarded-Proto and X-Forwarded-For from the listed peers. When the app port is published, a request that skips the proxy arrives from the Docker gateway, so trusting that subnet lets any client forge the forwarded headers — including the client address the rate limit keys on. Here the scheme is declared in configuration (SERVER_PUBLIC_SCHEME) and nothing the client sends changes it.

Register it outermost, so every layer below builds URLs in the same scheme. It writes one scope key and logs nothing. lifespan scopes pass through untouched, and websocket scopes get ws/wss.

Attributes:

Name Type Description
app ASGIApp

The wrapped application.

scheme str

"http", "https", or "" for passthrough.

Wrap app and stamp scheme on every connection.

Parameters:

Name Type Description Default
app ASGIApp

The application to wrap.

required
scheme Literal['http', 'https', '']

The scheme the service is publicly reached by. "" leaves the scope as the connection describes it, which is what local development without a proxy wants.

''

Raises:

Type Description
ValueError

When scheme is not "http", "https" or "".

ErrorEnvelopeMiddleware

ErrorEnvelopeMiddleware(app: ASGIApp, handler: ErrorEnvelopeHandler)

Answer an unhandled exception from inside the user middleware stack.

Starlette runs the handler registered for :class:Exception inside ServerErrorMiddleware, the outermost layer of the stack, so the response it builds never passes back through CORSMiddleware, RequestIDMiddleware or any other middleware the application added. The browser then discards the 500 for lack of Access-Control-Allow-Origin and fetch rejects with TypeError: Failed to fetch: no status, no code, no X-Request-ID to correlate with the server log.

This layer catches the exception below every user middleware and sends the envelope from there, so each of them decorates the 500 as it decorates a 200. It never decides CORS itself: an origin outside the allow-list still gets no header, because CORSMiddleware is still the one answering that question.

After sending the envelope the exception is re-raised, the same contract ServerErrorMiddleware keeps: the ASGI server still logs it, and a TestClient built with the default raise_server_exceptions=True still raises it in the test. On the way out ServerErrorMiddleware sees a response already started and does not answer a second time. It still calls its handler, though, so the exception is flagged first and the handler that :func:~tempest_fastapi_sdk.register_exception_handlers leaves there skips it: each 500 is logged and reported to on_server_error once.

When the failure happens after the response already started (a stream that breaks mid-body), the status is already on the wire and a second response cannot be sent. The handler still runs, so the failure is logged, and the background task of the response it builds runs here — that is where :func:~tempest_fastapi_sdk.register_exception_handlers attaches on_server_error, and a response that is never sent never runs its background. The exception is then flagged and re-raised. Before this, measured, a broken stream was logged but never reached on_server_error.

:func:~tempest_fastapi_sdk.register_exception_handlers installs this layer itself, as the innermost user middleware, so its position does not depend on the order of the add_middleware / apply_cors calls around it.

Parameters:

Name Type Description Default
app ASGIApp

The downstream ASGI application.

required
handler ErrorEnvelopeHandler

Renders the envelope for the exception; normally the callable built by :func:~tempest_fastapi_sdk.make_unhandled_exception_handler.

required

Wrap app with the envelope handler.

Parameters:

Name Type Description Default
app ASGIApp

The downstream ASGI application.

required
handler ErrorEnvelopeHandler

Renders the envelope.

required

IdempotencyMiddleware

IdempotencyMiddleware(
    app: ASGIApp,
    *,
    store: IdempotencyStore,
    ttl_seconds: int = 24 * 3600,
    header_name: str = IDEMPOTENCY_HEADER,
    principal_resolver: Callable[[Request], str] | None = None,
    cache_server_errors: bool = False,
    credential_headers: tuple[str, ...] = DEFAULT_CREDENTIAL_HEADERS,
    allow_anonymous: bool = False,
)

Bases: BaseHTTPMiddleware

ASGI middleware caching responses by Idempotency-Key.

Only mutating verbs (POST / PUT / PATCH / DELETE) are eligible. The key is scoped per (caller, method, path, key) so a key reused across different endpoints — or by a different caller — doesn't collide, and a hit replays only when the method, path, query and body match the request that created the entry (422 otherwise). Requests without credentials are not cached unless allow_anonymous=True.

Add to FastAPI like any other ASGI middleware:

from tempest_fastapi_sdk import (
    IdempotencyMiddleware,
    MemoryIdempotencyStore,
)

app.add_middleware(
    IdempotencyMiddleware,
    store=MemoryIdempotencyStore(),
    ttl_seconds=24 * 3600,
)

Initialize the middleware.

Parameters:

Name Type Description Default
app ASGIApp

The wrapped ASGI app.

required
store IdempotencyStore

Backend used to cache responses. Pass :class:MemoryIdempotencyStore for single-replica deployments, :class:RedisIdempotencyStore otherwise.

required
ttl_seconds int

How long to keep cached responses. Stripe defaults to 24 hours — long enough to cover client retries with exponential backoff.

24 * 3600
header_name str

Header carrying the idempotency key. Defaults to the canonical Idempotency-Key.

IDEMPOTENCY_HEADER
principal_resolver Callable[[Request], str] | None

Returns the caller identity folded into the cache key. None (default) digests the credential_headers, which is right whenever those carry the identity. Supply your own when identity lives elsewhere, and derive it from a credential the resolver verifies (a signed token's subject): the middleware runs before any auth dependency, so a value read from a plain client header (a tenant id) isolates nothing. An empty string means anonymous. Returning a constant restores cross-caller sharing and is unsafe on a multi-tenant endpoint.

None
cache_server_errors bool

Whether a 5xx is stored and replayed. False (default) lets the client's retry actually reach the handler — a transient failure cached for ttl_seconds would otherwise pin that key to the error for as long as the entry lives.

False
credential_headers tuple[str, ...]

Request headers digested into the caller identity when principal_resolver is None. The default covers Authorization, Cookie, X-Token (the header of make_token_dependency) and X-API-Key; add the header your own auth reads when it is none of those.

DEFAULT_CREDENTIAL_HEADERS
allow_anonymous bool

Whether requests without an identity (no credential header, or a resolver returning "") share one cached scope. False (default) passes them to the handler uncached: anonymous endpoints such as login carry the credential in the body, and a shared scope would replay one caller's response to another.

False

Raises:

Type Description
ValueError

When credential_headers is empty.

dispatch async

dispatch(
    request: Request, call_next: Callable[[Request], Awaitable[Response]]
) -> Response

Replay cached responses when the same key reappears.

Parameters:

Name Type Description Default
request Request

The inbound request.

required
call_next Callable[[Request], Awaitable[Response]]

The next handler in the middleware chain.

required

Returns:

Name Type Description
Response Response

The replayed response on a hit, otherwise the handler's own.

MemoryIdempotencyStore

MemoryIdempotencyStore()

In-process :class:IdempotencyStore with TTL eviction.

Single-replica only — a second replica won't see entries stored by the first. Suitable for dev, tests, and small services that haven't scaled out yet.

The eviction is best-effort: TTLs are checked on access; no background thread cleans the dict. Memory grows linearly with cached requests until they expire, so set a sensible TTL.

Initialize the in-memory store.

get async

get(key: str) -> CachedResponse | None

Return the cached response, evicting if expired.

Parameters:

Name Type Description Default
key str

The idempotency key from the request header.

required

Returns:

Type Description
CachedResponse | None

CachedResponse | None: The stored response, or None on a miss.

set async

set(key: str, response: CachedResponse, *, ttl_seconds: int) -> None

Store the response with an expiry.

Parameters:

Name Type Description Default
key str

The idempotency key from the request header.

required
response CachedResponse

The response to remember for replays.

required
ttl_seconds int

How long the entry stays replayable.

required

RedisIdempotencyStore

RedisIdempotencyStore(client: _RedisLike, *, prefix: str = 'idem:')

:class:IdempotencyStore backed by an async redis client.

The cached payload is encoded as JSON so the schema stays portable across SDK versions: {"status_code", "headers", "body_b64", "media_type"} with the body base64-encoded because Redis values are bytes.

Use this in production / multi-replica deployments. Requires the [cache] extra so the redis async client is available.

Initialize.

Parameters:

Name Type Description Default
client _RedisLike

Async Redis-like client exposing get(key) / set(key, value, ex) (e.g. redis.asyncio.Redis or any equivalent).

required
prefix str

Key prefix so idempotency entries don't collide with other cached data.

'idem:'

get async

get(key: str) -> CachedResponse | None

Fetch and decode the cached response.

Parameters:

Name Type Description Default
key str

The idempotency key from the request header.

required

Returns:

Type Description
CachedResponse | None

CachedResponse | None: The stored response, or None on a miss.

set async

set(key: str, response: CachedResponse, *, ttl_seconds: int) -> None

Serialize and write with EXPIRE.

Parameters:

Name Type Description Default
key str

The idempotency key from the request header.

required
response CachedResponse

The response to remember for replays.

required
ttl_seconds int

How long the entry stays replayable.

required

IDEMPOTENCY_HEADER module-attribute

IDEMPOTENCY_HEADER: str = 'Idempotency-Key'

Header name canonical to the industry: Stripe, AWS and GitHub all use it.

BodySizeLimitMiddleware

BodySizeLimitMiddleware(
    app: ASGIApp, *, max_bytes: int, exclude_paths: tuple[str, ...] = ()
)

Pure ASGI middleware enforcing max_bytes per request.

Two checks happen:

  1. Header check — Content-Length greater than the cap short-circuits immediately with a 413 response. This catches the common case where the client knows the size.
  2. Streaming check — for chunked / unknown-length uploads the middleware tracks bytes seen in the http.request messages and aborts once the cap is crossed.

Excluded paths bypass the check entirely (typical use: an upload endpoint that intentionally accepts larger bodies and enforces its own per-route limit).

Initialize.

Parameters:

Name Type Description Default
app ASGIApp

The wrapped ASGI app.

required
max_bytes int

Hard cap on the request body in bytes. 0 disables the check (do not ship to production).

required
exclude_paths tuple[str, ...]

Path prefixes that bypass the limit. Match is startswith so the more specific the better.

()

AccessLogMiddleware

AccessLogMiddleware(
    app: ASGIApp,
    *,
    logger_name: str = "tempest.access",
    level: int = INFO,
    exempt_paths: tuple[str, ...] = (),
    exempt_prefixes: tuple[str, ...] = (),
    redact: Callable[[str], str] | None = None,
    trusted_ip_header: str | None = None,
    request_id_header: str = "X-Request-ID",
    redact_capability_urls: bool = True,
    include_layer_timings: bool = False,
)

Emit one log record per HTTP request, with structured fields.

The record's message is human-readable (GET /api/users 200 12.4ms) so a plain formatter stays useful, while method, path, query, status, duration and client IP also go through extra= — which is what makes them real keys under :class:JSONFormatter and therefore filterable in :func:make_logs_router rather than trapped inside an interpolated string.

Level is level for anything the app answered below 500, and ERROR for a server error — whether the app rendered it itself or an exception propagated out. Finding failed requests by level is the point of writing them at all.

The request_id field is resolved from two sources, because neither alone survives every registration order. Measured on 2026-08-30:

AccessLogMiddleware inside RequestIDMiddleware   context variable: set
                                                 response header:  not yet written
AccessLogMiddleware outside RequestIDMiddleware  context variable: cleared
                                                 response header:  present

RequestIDMiddleware is a BaseHTTPMiddleware: it stamps the header onto the response after the downstream app returns, so an inner middleware's send wrapper has already run. It also clears the context variable as it unwinds, so an outer one finds nothing there. Reading both covers both, and the line carries the id either way.

Attributes:

Name Type Description
app ASGIApp

The wrapped ASGI application.

logger Logger

Where the lines are written.

level int

Level used for non-error responses.

Initialize.

Parameters:

Name Type Description Default
app ASGIApp

The wrapped ASGI application.

required
logger_name str

Logger the records are written to. A dedicated name lets a service route access lines to their own handler, or silence them, without touching the rest of its logging.

'tempest.access'
level int

Level for responses below 500. Server errors are always logged at logging.ERROR.

INFO
exempt_paths tuple[str, ...]

Exact paths that produce no line at all.

()
exempt_prefixes tuple[str, ...]

Path prefixes that bypass the middleware. ("/api/sse",) covers /api/sse/stream. Matching is textual, so it also covers /api/sse-legacy. The case this exists for is a streaming endpoint: an SSE connection held open for an hour would otherwise be logged once, on close, as a request that took an hour, and those live under a prefix.

Until 0.286.0 exempt_paths matched by prefix here and by equality in the other four middlewares. It is equality everywhere now; a prefix exemption moves to exempt_prefixes.

()
redact Callable[[str], str] | None

Applied to the path and to the query string, separately, before either reaches the record, after the capability redaction below. None adds nothing to it. Use it whenever a secret of your own can appear in a URL — the middleware sees the request before any handler can refuse it.

None
trusted_ip_header str | None

Single edge-set header naming the client IP (e.g. "x-real-ip"), passed through to :func:get_client_ip_from_scope. None uses the transport peer. Never point this at a bare X-Forwarded-For: that header is appended to whatever the client sent, so its leftmost entry is attacker-controlled and the log would attribute requests to an address the caller chose.

None
request_id_header str

Response header the correlation id is read from when the context variable is empty. Must match :class:RequestIDMiddleware's header_name; the default is the same on both sides.

'X-Request-ID'
redact_capability_urls bool

Hide the credentials the SDK itself puts in URLs — the token segment of /activate/{token}, /password-reset/{token}, /email-change/{token} and /email-verify/{token}, and every signature= / *token= query value — with :func:~tempest_fastapi_sdk.core.redaction.redact_capability_url. Default True: a reset token in the access log is a takeover for anyone who can read the log. Set False only when nothing that reads the log may not also redeem those links.

True
include_layer_timings bool

When True, bind a per-request layer timing accumulator around the downstream app and attach layers: {"<layer>_ms": <ms>, ...} to the access log record whenever at least one :func:~tempest_fastapi_sdk.core.timing.timed or :func:~tempest_fastapi_sdk.core.timing.instrument_layer call ran during the request. Omitted when no timings were recorded so uninstrumented endpoints keep the exact same access log payload. Default False: opt in to get the summary; timed and instrument_layer still log their own lines either way.

False

HoneypotBanMiddleware

HoneypotBanMiddleware(
    app: ASGIApp,
    *,
    store: BanStore,
    patterns: tuple[Pattern[str], ...] = DEFAULT_HONEYPOT_PATTERNS,
    query_patterns: tuple[Pattern[str], ...] = DEFAULT_HONEYPOT_QUERY_PATTERNS,
    ban_seconds: int = 86400,
    trusted_ip_header: str | None = None,
    exempt_paths: tuple[str, ...] = (),
    exempt_prefixes: tuple[str, ...] = (),
    status_code: int = 403,
)

Ban an IP the first time it requests a path only a scanner wants.

A banned IP is answered before routing, before authentication and before the rate limiter — the cheapest possible rejection, which is the point of banning rather than limiting.

Two decisions are baked in rather than left to the consumer:

It fails open. Every call into the store is guarded: a store that raises is logged at WARNING and the request proceeds. A blocklist that cannot reach Redis must let traffic through, because getting this backwards turns a cache outage into a full outage. The failure stays visible in the logs rather than being swallowed.

The client IP comes from a single trusted header. Behind nginx, X-Forwarded-For is appended to whatever the client sent, so its leftmost entry is attacker-controlled — a hand-rolled blocklist that reads it directly bans the wrong IP, and can be made to ban a real user. trusted_ip_header is passed to :func:~tempest_fastapi_sdk.utils.client_ip.get_client_ip_from_scope, which reads one edge-set header and otherwise falls back to the transport peer.

The response deliberately says nothing about the ban: a scanner that learns it is banned learns to rotate.

Attributes:

Name Type Description
app ASGIApp

The wrapped ASGI application.

store BanStore

Where bans are recorded and read.

patterns tuple[Pattern[str], ...]

The path signatures in force.

query_patterns tuple[Pattern[str], ...]

The query-string signatures in force.

ban_seconds int

How long a ban lasts.

Initialize.

Parameters:

Name Type Description Default
app ASGIApp

The wrapped ASGI application.

required
store BanStore

Where bans live. :class:MemoryBanStore for a single worker or a test; :class:RedisBanStore for anything with replicas.

required
patterns tuple[Pattern[str], ...]

Signatures matched against the request path. Defaults to :data:DEFAULT_HONEYPOT_PATTERNS. Until 0.334.1 these were matched against path?query; a custom pattern that targets the query moves to query_patterns.

DEFAULT_HONEYPOT_PATTERNS
query_patterns tuple[Pattern[str], ...]

Signatures matched against the raw query string alone. Defaults to :data:DEFAULT_HONEYPOT_QUERY_PATTERNS.

DEFAULT_HONEYPOT_QUERY_PATTERNS
ban_seconds int

Ban duration. Defaults to 24 hours, long enough to outlast a scan pass and short enough that a recycled address is not punished for its predecessor.

86400
trusted_ip_header str | None

Single edge-set header naming the client IP (e.g. "x-real-ip"). None uses the transport peer. Never point this at a bare X-Forwarded-For.

None
exempt_paths tuple[str, ...]

Exact paths checked before the patterns, for the service that legitimately serves something the curated list flags.

()
exempt_prefixes tuple[str, ...]

Path prefixes that bypass the middleware. ("/api/sse",) covers /api/sse/stream. Matching is textual, so it also covers /api/sse-legacy.

Until 0.286.0 exempt_paths matched by prefix here. It is equality now; a prefix exemption moves to exempt_prefixes.

()
status_code int

Status returned to a banned or offending caller.

403

matches

matches(target: str) -> bool

Report whether target carries a scanner signature.

The path (everything before the first ?) is checked against :attr:patterns, the query string against :attr:query_patterns.

Parameters:

Name Type Description Default
target str

The request path, with ?query appended when the request carried one.

required

Returns:

Name Type Description
bool bool

True when any configured pattern matches its part.

DEFAULT_HONEYPOT_PATTERNS module-attribute

DEFAULT_HONEYPOT_PATTERNS: tuple[Pattern[str], ...] = _compile_patterns()

Curated scanner signatures, matched against the request path.

A single hit is treated as proof of a scanner, so the set errs towards paths no deployed application serves. It is overridable precisely because the judgement is not universal — a service that legitimately serves /wp-admin exists somewhere, and it passes its own patterns.

DEFAULT_HONEYPOT_QUERY_PATTERNS module-attribute

DEFAULT_HONEYPOT_QUERY_PATTERNS: tuple[Pattern[str], ...] = _compile_patterns(
    _HONEYPOT_QUERY_SOURCES
)

Curated scanner signatures, matched against the raw query string.

Kept apart from :data:DEFAULT_HONEYPOT_PATTERNS because the query carries user input: only shapes no honest client produces belong here.

BanStore

Bases: Protocol

Where bans live between requests.

Two methods, both of which the middleware is allowed to see fail: an outage must not take the API down with it. See :class:HoneypotBanMiddleware for how failures are absorbed.

is_banned async

is_banned(ip: str) -> bool

Report whether ip currently has an active ban.

Parameters:

Name Type Description Default
ip str

The resolved client IP.

required

Returns:

Name Type Description
bool bool

True while the ban is in force.

ban async

ban(ip: str, *, ttl_seconds: int, reason: str) -> None

Record a ban for ip lasting ttl_seconds.

Parameters:

Name Type Description Default
ip str

The resolved client IP.

required
ttl_seconds int

How long the ban stays in force.

required
reason str

The request target that triggered it, stored so an operator reviewing the ban can see what earned it.

required

MemoryBanStore

MemoryBanStore()

In-process :class:BanStore, useful for a single worker and tests.

Bans are held in a dict of expiry timestamps and are lost on restart, which is the trade a service accepts by not running Redis. Expired entries are dropped when read rather than swept, so the dict tracks the set of distinct offenders rather than growing with every hit.

Initialize an empty ban table.

is_banned async

is_banned(ip: str) -> bool

Report whether ip has an unexpired ban.

Parameters:

Name Type Description Default
ip str

The resolved client IP.

required

Returns:

Name Type Description
bool bool

True while the ban is in force.

ban async

ban(ip: str, *, ttl_seconds: int, reason: str) -> None

Record a ban for ip.

Parameters:

Name Type Description Default
ip str

The resolved client IP.

required
ttl_seconds int

How long the ban stays in force.

required
reason str

The request target that triggered it. Unused here — an in-process store has no operator to review — and accepted so this class satisfies :class:BanStore.

required

RedisBanStore

RedisBanStore(client: _RedisLike, *, prefix: str = 'honeypot:ban:')

:class:BanStore backed by an async redis client.

This is the shape a real deployment wants: the ban is shared by every replica the moment it is written, and Redis owns the expiry, so a restart does not hand the scanner a clean slate. Requires the [cache] extra.

Initialize.

Parameters:

Name Type Description Default
client _RedisLike

Async Redis-like client exposing get(key) / set(key, value, ex=...) (e.g. redis.asyncio.Redis or fakeredis.aioredis).

required
prefix str

Key prefix so ban entries do not collide with other cached data.

'honeypot:ban:'

is_banned async

is_banned(ip: str) -> bool

Report whether ip currently has an active ban.

Parameters:

Name Type Description Default
ip str

The resolved client IP.

required

Returns:

Name Type Description
bool bool

True while the key exists.

ban async

ban(ip: str, *, ttl_seconds: int, reason: str) -> None

Write the ban with a Redis-managed TTL.

Parameters:

Name Type Description Default
ip str

The resolved client IP.

required
ttl_seconds int

How long the ban stays in force.

required
reason str

The request target that triggered it.

required

GracefulShutdownMiddleware

GracefulShutdownMiddleware(
    *,
    drain_timeout: float = 30.0,
    retry_after: int = 5,
    exempt_paths: Sequence[str] = (),
    exempt_prefixes: Sequence[str] = (),
)

Track in-flight requests and reject new ones with 503 while draining.

Wire :meth:dispatch via app.add_middleware(BaseHTTPMiddleware, dispatch=shutdown.dispatch) and call :meth:begin_drain while the server still accepts connections — under uvicorn that means before SIGTERM, since the lifespan shutdown runs after the listener closed and in-flight requests finished (see the module docstring).

Attributes:

Name Type Description
drain_timeout float

Seconds :meth:wait_drained waits for in-flight requests before giving up.

retry_after int

Retry-After header value on the 503s served while draining.

Initialize the helper.

Parameters:

Name Type Description Default
drain_timeout float

Max seconds to wait for in-flight requests in :meth:wait_drained. Defaults to 30.0.

30.0
retry_after int

Retry-After seconds advertised on the 503 served while draining. Defaults to 5.

5
exempt_paths Sequence[str]

Exact paths that keep being served during drain. Usually unnecessary — letting health endpoints return 503 is what makes a load balancer deregister the instance. Defaults to none.

()
exempt_prefixes Sequence[str]

Path prefixes that keep being served during drain. ("/api/sse",) covers /api/sse/stream. Matching is textual, so it also covers /api/sse-legacy.

()

in_flight property

in_flight: int

Return the number of requests currently being served.

Returns:

Name Type Description
int int

The in-flight request count.

is_draining property

is_draining: bool

Return whether draining has begun.

Returns:

Name Type Description
bool bool

True once :meth:begin_drain (or a signal) fired.

dispatch async

dispatch(
    request: Request, call_next: Callable[[Request], Awaitable[Response]]
) -> Response

Starlette BaseHTTPMiddleware dispatch hook.

Serves 503 for new non-exempt requests once draining; otherwise counts the request as in-flight while it runs.

Parameters:

Name Type Description Default
request Request

The incoming request.

required
call_next Callable[[Request], Awaitable[Response]]

The downstream handler.

required

Returns:

Name Type Description
Response Response

The downstream response, or a 503 while

Response

draining.

begin_drain

begin_drain() -> None

Flip into draining mode (idempotent).

New non-exempt requests get 503 from now on. Call it while the server still accepts connections (under uvicorn: before SIGTERM, e.g. from a SIGUSR1 handler that a pre-stop hook fires); from the lifespan shutdown it refuses nothing.

wait_drained async

wait_drained() -> bool

Wait until in-flight requests finish or the timeout elapses.

Returns:

Name Type Description
bool bool

True if everything drained in time, False if

bool

attr:drain_timeout elapsed with requests still running.

install_signal_handlers

install_signal_handlers(signals: Sequence[int] = (SIGTERM, SIGINT)) -> None

Chain a drain trigger onto the given signals via signal.signal.

Under uvicorn, hook a signal uvicorn leaves alone (SIGUSR1), not the default SIGTERM / SIGINT it handles itself. The defaults are for servers that do not manage signals. Best-effort: a no-op when called off the main thread.

Parameters:

Name Type Description Default
signals Sequence[int]

Signals to hook. Defaults to SIGTERM and SIGINT.

(SIGTERM, SIGINT)

CSRFMiddleware

CSRFMiddleware(
    app: ASGIApp,
    *,
    cookie_name: str = CSRF_COOKIE_NAME,
    header_name: str = CSRF_HEADER_NAME,
    exclude_paths: tuple[str, ...] = (),
)

Bases: BaseHTTPMiddleware

Double-submit cookie CSRF guard.

On unsafe methods (POST / PUT / PATCH / DELETE) the request MUST carry:

  1. The CSRF cookie (csrf_token by default).
  2. The CSRF header (X-CSRF-Token by default) with the same value.

Missing or mismatched values return 403 with the SDK envelope. Excluded paths bypass the check — typical use: /api/ routes that use Authorization: Bearer (not susceptible to CSRF), or webhook callbacks whose authentication is signature-based.

Safe methods (GET / HEAD / OPTIONS) always pass.

Initialize.

Parameters:

Name Type Description Default
app ASGIApp

Wrapped app.

required
cookie_name str

Name of the CSRF cookie.

CSRF_COOKIE_NAME
header_name str

Name of the CSRF header.

CSRF_HEADER_NAME
exclude_paths tuple[str, ...]

Path prefixes that bypass the check (e.g. ("/api/", "/webhooks/")).

()

dispatch async

dispatch(
    request: Request, call_next: Callable[[Request], Awaitable[Response]]
) -> Response

Enforce the double-submit check on unsafe methods.

Parameters:

Name Type Description Default
request Request

The inbound request.

required
call_next Callable[[Request], Awaitable[Response]]

The next handler in the middleware chain.

required

Returns:

Name Type Description
Response Response

The downstream response, after this middleware ran.

make_csrf_token_dependency

make_csrf_token_dependency(
    *,
    cookie_name: str = CSRF_COOKIE_NAME,
    secure: bool = True,
    samesite: Literal["lax", "strict", "none"] = "lax",
    max_age: int | None = None,
) -> Callable[[Request, Response], str]

Build a FastAPI dependency that issues + returns the CSRF token.

Use this on the route that renders the login page (or the HTML shell that triggers form submissions). It returns the token so the template can embed it as a hidden input, and when the cookie is absent it sets it on the outgoing response — the double-submit check needs both halves, and a dependency that only returned the value left the cookie missing, so every later POST answered 403.

The cookie is deliberately not HttpOnly: a browser client has to read it to echo the value in the X-CSRF-Token header, which is the whole double-submit mechanism. That is safe as long as the value is only a CSRF token — never put anything else in this cookie.

Parameters:

Name Type Description Default
cookie_name str

Cookie key — must match CSRFMiddleware(cookie_name=…).

CSRF_COOKIE_NAME
secure bool

Emit the Secure flag. Keep True in production; set False only for a plain-HTTP dev server.

True
samesite Literal['lax', 'strict', 'none']

SameSite policy. "none" requires secure=True.

'lax'
max_age int | None

Cookie lifetime in seconds. None (default) makes it a session cookie.

None

Returns:

Type Description
Callable[[Request, Response], str]

Callable[[Request, Response], str]: FastAPI dependency.

generate_csrf_token

generate_csrf_token(n_bytes: int = 32) -> str

Mint a fresh CSRF token.

Parameters:

Name Type Description Default
n_bytes int

Entropy bytes. 32 yields a 43-char URL-safe string; bring this above 16 to stay above the birthday-bound on the cookie set.

32

Returns:

Name Type Description
str str

URL-safe base64 token without padding.

RateLimitMiddleware

RateLimitMiddleware(
    app: ASGIApp,
    *,
    max_requests: int = 60,
    window_seconds: float = 60.0,
    key_func: Callable[[Request], str] | None = None,
    trusted_ip_header: str | None = None,
    store: RateLimitStore | None = None,
    policy: RateLimitPolicy | None = None,
    quota_store: QuotaStore | None = None,
    exempt_paths: tuple[str, ...] = (),
    exempt_prefixes: tuple[str, ...] = (),
    retry_after_header: bool = True,
    limit_headers: bool = True,
    error_message: str = "Too many requests",
    error_code: str = code,
)

Bases: BaseHTTPMiddleware

Rate limiter with pluggable store, key and limit policy.

Each unique key (by default the client IP) is allowed at most max_requests requests inside every window_seconds window. Excess requests are rejected with 429 Too Many Requests and a Retry-After header.

By default counting happens in-process (:class:MemoryRateLimitStore) — fine for a single worker. Pass store=RedisRateLimitStore(redis) to share counters across replicas. Pass a key_func (e.g. :func:key_by_jwt_subject) to limit per authenticated principal instead of per IP.

Token buckets and per-plan quotas. max_requests / window_seconds describe a single sliding window. Pass policy= (a :class:~tempest_fastapi_sdk.api.middlewares.quota.RateLimitPolicy) to apply a list of limits resolved per request instead — a token bucket, a per-minute limit stacked under a daily ceiling, or a different list per plan. The two are alternatives: with policy= set, max_requests / window_seconds / store are unused, and the counters live in quota_store.

Running behind a proxy: the default IP key is the direct transport peer, which is the proxy once a reverse proxy fronts the app — so every client collapses into one bucket. Pass trusted_ip_header (e.g. "x-real-ip") naming a header your edge sets from its own connection (never a client-supplied X-Forwarded-For, which is spoofable). See :func:tempest_fastapi_sdk.utils.get_client_ip.

Attributes:

Name Type Description
max_requests int

Maximum requests inside the window.

window_seconds float

Length of the sliding window.

Initialize the middleware.

Parameters:

Name Type Description Default
app ASGIApp

The underlying ASGI app.

required
max_requests int

Maximum requests per window.

60
window_seconds float

Window length in seconds.

60.0
key_func Callable[[Request], str] | None

Build a rate-limit key from the request. Overrides trusted_ip_header. Defaults to the resolved client IP. See the key_by_* factories for per-user / per-tenant / per-API-key strategies.

None
trusted_ip_header str | None

When set (and key_func is not), the rate-limit key is the client IP resolved from this single edge-set header (e.g. "x-real-ip"), falling back to the transport peer. None keys on the transport peer only — correct only when the app is not behind a proxy.

None
store RateLimitStore | None

Counter backend for the single-window mode. Defaults to an in-process :class:MemoryRateLimitStore; pass :class:RedisRateLimitStore for multi-replica deploys. Unused when policy is set.

None
policy RateLimitPolicy | None

Resolves a list of limits per request — token buckets, stacked windows, per-plan quotas. See :class:~tempest_fastapi_sdk.api.middlewares.quota.PlanRateLimitPolicy and :class:~tempest_fastapi_sdk.api.middlewares.quota.StaticRateLimitPolicy. None (default) keeps the single-window behavior.

None
quota_store QuotaStore | None

Counter backend for the policy mode. Defaults to an in-process :class:~tempest_fastapi_sdk.api.middlewares.quota.MemoryQuotaStore; pass :class:~tempest_fastapi_sdk.api.middlewares.quota.RedisQuotaStore for multi-replica deploys. Ignored without policy.

None
exempt_paths tuple[str, ...]

Exact paths to skip entirely (e.g. ("/health/liveness", "/health/readiness")).

()
exempt_prefixes tuple[str, ...]

Path prefixes that bypass the middleware. ("/api/sse",) covers /api/sse/stream. Matching is textual, so it also covers /api/sse-legacy. Prefer exempt_paths here: an exemption is a hole in the rate limit, and a prefix makes a hole larger than the route you meant to name.

()
retry_after_header bool

Whether to add a Retry-After header on 429 responses.

True
limit_headers bool

Whether to advertise the limit with RateLimit-Limit / RateLimit-Remaining / RateLimit-Reset. RateLimit-Reset is emitted only when its value is known: always in policy mode, and on 429 in single-window mode — the sliding-window store does not report a reset for an accepted request, and a guessed number is worse than an absent header.

True
error_message str

detail of the 429 envelope. Prose for humans -- clients branch on code.

'Too many requests'
error_code str

code of the 429 envelope, the stable identifier a client branches on. Defaults to :class:~tempest_fastapi_sdk.TooManyRequestsException's own TOO_MANY_REQUESTS, so a route documented with error_responses(TooManyRequestsException) matches what the middleware actually sends.

code

Raises:

Type Description
ValueError

If max_requests < 1, window_seconds <= 0, or both policy and store are passed (the two select different counter backends, so honoring one would silently ignore the other).

dispatch async

dispatch(request: Request, call_next: Callable[[Request], Any]) -> Response

Apply the rate limit before forwarding to the route handler.

Parameters:

Name Type Description Default
request Request

The inbound request.

required
call_next Callable

Next handler in the middleware chain.

required

Returns:

Name Type Description
Response Response

The downstream response, or a 429 when the limit

Response

is exceeded.

RateLimitStore

Bases: Protocol

Backend that counts hits per key inside a sliding window.

hit async

hit(key: str, max_requests: int, window_seconds: float) -> RateLimitResult

Register one hit for key and report whether it is allowed.

Parameters:

Name Type Description Default
key str

The rate-limit bucket key.

required
max_requests int

Maximum hits allowed in the window.

required
window_seconds float

Sliding-window length in seconds.

required

Returns:

Name Type Description
RateLimitResult RateLimitResult

The decision for this hit.

RateLimitResult dataclass

RateLimitResult(allowed: bool, remaining: int, retry_after: int)

Outcome of a single rate-limit check.

Attributes:

Name Type Description
allowed bool

True when the request fits under the limit.

remaining int

Requests still allowed in the current window (0 when rejected).

retry_after int

Seconds the caller should wait before retrying (0 when allowed). Always >= 1 on rejection.

MemoryRateLimitStore

MemoryRateLimitStore()

In-process sliding-window store backed by per-key timestamp logs.

State lives in this worker's memory only — correct for a single process (dev, or one reverse-proxy worker). For multi-replica deployments use :class:RedisRateLimitStore so every worker shares the same counters.

Initialize an empty store.

hit async

hit(key: str, max_requests: int, window_seconds: float) -> RateLimitResult

Register a hit and prune timestamps older than the window.

Parameters:

Name Type Description Default
key str

The rate-limit bucket key.

required
max_requests int

Maximum hits allowed in the window.

required
window_seconds float

Sliding-window length in seconds.

required

Returns:

Name Type Description
RateLimitResult RateLimitResult

The decision for this hit.

FailOpenRateLimitStore

FailOpenRateLimitStore(inner: RateLimitStore)

Wrap a store so that an outage lets requests through.

Measured on 2026-08-23: with a store whose hit raises, the exception propagates out of :class:RateLimitMiddleware and the caller gets a 500. For most endpoints that is defensible — a limiter that cannot count is a limiter that cannot protect. For some it is exactly backwards.

The clearest case is an error-reporting endpoint: the moment the counter store is unwell is the moment errors spike, and rejecting the reports then destroys the evidence of the incident being reported. Losing the report is worse than serving traffic above the ceiling.

This wrapper makes that trade explicit at the call site instead of leaving it to whether Redis happens to be up:

store = FailOpenRateLimitStore(RedisRateLimitStore(redis))

It does not swallow the outage silently — every failure is logged at WARNING with the key, so "the ceiling is not being enforced" stays visible in the logs.

Attributes:

Name Type Description
inner RateLimitStore

The store doing the real counting.

Wrap a counter store.

Parameters:

Name Type Description Default
inner RateLimitStore

The store to guard.

required

hit async

hit(key: str, max_requests: int, window_seconds: float) -> RateLimitResult

Count one hit, allowing the request when counting fails.

Parameters:

Name Type Description Default
key str

The rate-limit bucket key.

required
max_requests int

Maximum hits allowed in the window.

required
window_seconds float

Sliding-window length in seconds.

required

Returns:

Name Type Description
RateLimitResult RateLimitResult

The inner store's decision, or an allowing

RateLimitResult

result when the inner store raised.

RedisRateLimitStore

RedisRateLimitStore(
    redis: RedisLike, *, namespace: str = "ratelimit", fail_open: bool = True
)

Distributed sliding-window store backed by a Redis sorted set.

Every key maps to a sorted set whose members are individual request timestamps (in milliseconds). A single Lua script prunes expired members, counts the survivors and conditionally adds the new hit, so the check is atomic across replicas — no race between count and add.

The timestamps come from the Redis server's clock (TIME, read inside the script), not from the calling process, so replicas whose wall clocks disagree still share one window. A step on the Redis host's clock still moves every window at once.

When the backend raises and fail_open is True (the default), the request is allowed rather than locking every caller out on a transient Redis outage.

Initialize the store.

Parameters:

Name Type Description Default
redis RedisLike

Async Redis client (e.g. redis.asyncio.Redis).

required
namespace str

Prefix for every Redis key.

'ratelimit'
fail_open bool

Allow the request when the backend errors.

True

hit async

hit(key: str, max_requests: int, window_seconds: float) -> RateLimitResult

Register a hit atomically via the sliding-window Lua script.

Parameters:

Name Type Description Default
key str

The rate-limit bucket key.

required
max_requests int

Maximum hits allowed in the window.

required
window_seconds float

Sliding-window length in seconds.

required

Returns:

Name Type Description
RateLimitResult RateLimitResult

The decision for this hit. On a backend

RateLimitResult

error this is allowed when fail_open is set.

Raises:

Type Description
Exception

Propagates the backend error when fail_open is False.

key_by_ip

key_by_ip(*, trusted_header: str | None = None) -> Callable[[Request], str]

Build a key function that buckets by client IP.

Parameters:

Name Type Description Default
trusted_header str | None

Single edge-set header to resolve the real client IP from (e.g. "x-real-ip"). None uses the transport peer only.

None

Returns:

Type Description
Callable[[Request], str]

Callable[[Request], str]: A key function yielding "ip:<addr>".

key_by_jwt_subject

key_by_jwt_subject(
    jwt: _JWTDecoder,
    *,
    fallback_to_ip: bool = True,
    trusted_ip_header: str | None = None,
) -> Callable[[Request], str]

Build a key function that buckets by the JWT sub claim.

Convenience wrapper over :func:key_by_jwt_claim for per-user limits, yielding keys like "user:<sub>".

Parameters:

Name Type Description Default
jwt _JWTDecoder

A decoder exposing decode_or_none.

required
fallback_to_ip bool

Key by client IP for anonymous traffic.

True
trusted_ip_header str | None

Header to resolve the client IP from when falling back.

None

Returns:

Type Description
Callable[[Request], str]

Callable[[Request], str]: The key function.

key_by_jwt_claim

key_by_jwt_claim(
    jwt: _JWTDecoder,
    claim: str,
    *,
    scope: str | None = None,
    fallback_to_ip: bool = True,
    trusted_ip_header: str | None = None,
) -> Callable[[Request], str]

Build a key function that buckets by a claim in the bearer token.

The token is decoded opportunistically (no exception on a missing/invalid token) — anonymous traffic falls back to the client IP so it is still limited.

Parameters:

Name Type Description Default
jwt _JWTDecoder

A decoder exposing decode_or_none(token) -> dict | None (e.g. :class:tempest_fastapi_sdk.utils.JWTUtils).

required
claim str

Claim whose value is the bucket key (e.g. "tenant_id").

required
scope str | None

Prefix for the key. Defaults to claim.

None
fallback_to_ip bool

Key by client IP when no valid token carries the claim.

True
trusted_ip_header str | None

Header to resolve the client IP from when falling back.

None

Returns:

Type Description
Callable[[Request], str]

Callable[[Request], str]: The key function.

key_by_header

key_by_header(
    header_name: str,
    *,
    is_known: Callable[[str], bool],
    scope: str = "key",
    fallback_to_ip: bool = True,
    trusted_ip_header: str | None = None,
) -> Callable[[Request], str]

Build a key function that buckets by a verified header value.

Useful for per-API-key limits (e.g. header_name="x-api-key"). The middleware computes the key before any auth dependency runs, so the header value is still whatever the client sent. is_known is what turns it into an identity: only a value it accepts gets its own bucket. Any other value is treated like a missing header, so a client that sends a fresh made-up value on every request stays in its IP bucket instead of getting a fresh budget (and a fresh store entry) each time.

Parameters:

Name Type Description Default
header_name str

Header whose value is the bucket key.

required
is_known Callable[[str], bool]

Synchronous check that the value names a real principal (a lookup in the set of issued API keys, a checksum on the key format). Runs on every request, so keep it cheap; it receives the stripped header value.

required
scope str

Prefix for the key (keeps namespaces from colliding, e.g. "apikey:<value>").

'key'
fallback_to_ip bool

When the header is absent or not known, key by client IP instead of collapsing every such caller into one bucket.

True
trusted_ip_header str | None

Header to resolve the client IP from when falling back.

None

Returns:

Type Description
Callable[[Request], str]

Callable[[Request], str]: The key function.

RateLimitKeyFunc module-attribute

RateLimitKeyFunc = Callable[
    [Request], RateLimitKeyResult | Awaitable[RateLimitKeyResult]
]

A key function: sync or async, receiving the request.

The middleware's key_by_* factories (sync, one key) fit, and so does :func:key_by_body_field (async, zero or one key).

RateLimitKeyResult module-attribute

RateLimitKeyResult = str | Sequence[str]

What a route rate-limit key function returns: one key, or several.

make_rate_limit_dependency

make_rate_limit_dependency(
    store: RateLimitStore | Callable[[Request], RateLimitStore],
    *,
    max_requests: int,
    window_seconds: float,
    key: RateLimitKeyFunc | Sequence[RateLimitKeyFunc] | None = None,
    trusted_ip_header: str | None = None,
    scope: str | None = None,
    limit_headers: bool = True,
    retry_after_header: bool = True,
    error_message: str = "Too many requests",
    error_code: str = code,
) -> Callable[[Request, Response], Coroutine[Any, Any, None]]

Build a dependency that rate-limits the route it is attached to.

Attach with dependencies=[Depends(limit)] on one route (or a router). Each request is counted against every key the key functions produce; the first key over max_requests inside window_seconds refuses the request with 429. Keys are checked in order and the check stops at the first refusal, so a refused request does not spend the budget of the keys after it.

The refusal raises :class:~tempest_fastapi_sdk.TooManyRequestsException carrying the same details (retry_after_seconds, limit) and headers (Retry-After, RateLimit-*) that :class:~tempest_fastapi_sdk.RateLimitMiddleware writes, built by the same helpers; the app's :func:~tempest_fastapi_sdk.register_exception_handlers turns it into the envelope. With a MessageCatalog registered there, detail is localized by code — the middleware's is not, since it answers outside the exception handlers.

An accepted request gets RateLimit-Limit / RateLimit-Remaining (the lowest across the keys) on its response, through the Response FastAPI injects into dependencies. A handler that returns its own Response object discards those, as FastAPI does for every header set that way.

Buckets are prefixed with scope — by default the method and path template of the route ("POST /api/invites"), so the same dependency attached to two routes gives each its own budget, and a route-level bucket never collides with the middleware's bucket for the same IP in a shared store. Pass one scope string to several routes to make them share a budget.

Parameters:

Name Type Description Default
store RateLimitStore | Callable[[Request], RateLimitStore]

Counter backend — :class:~tempest_fastapi_sdk.MemoryRateLimitStore for one process, :class:~tempest_fastapi_sdk.RedisRateLimitStore to share counters across replicas — or a factory called with each request that returns it, for a store built after import.

required
max_requests int

Requests allowed per key inside the window.

required
window_seconds float

Sliding-window length in seconds.

required
key RateLimitKeyFunc | Sequence[RateLimitKeyFunc] | None

Key function, or several, each returning one key or a sequence of keys (sync or async). [key_by_ip(trusted_header="x-real-ip"), key_by_body_field("email")] limits per IP and per e-mail. None keys on the client IP resolved with trusted_ip_header. A request for which no function produces a key is not limited.

None
trusted_ip_header str | None

Single edge-set header holding the real client IP (e.g. "x-real-ip") for the default key. None uses the transport peer, which is the proxy once one fronts the app — every client then shares one bucket. Only valid without key; pass it to :func:~tempest_fastapi_sdk.key_by_ip inside key instead.

None
scope str | None

Prefix of every bucket. None uses the route's "<METHOD> <path template>".

None
limit_headers bool

Whether to emit RateLimit-*.

True
retry_after_header bool

Whether to emit Retry-After on 429.

True
error_message str

detail of the 429 envelope.

'Too many requests'
error_code str

code of the 429 envelope. Defaults to :class:~tempest_fastapi_sdk.TooManyRequestsException's TOO_MANY_REQUESTS, matching the middleware.

code

Returns:

Type Description
Callable[[Request, Response], Coroutine[Any, Any, None]]

Callable[[Request, Response], Coroutine[Any, Any, None]]: The

Callable[[Request, Response], Coroutine[Any, Any, None]]

async dependency.

Raises:

Type Description
ValueError

If max_requests < 1, window_seconds <= 0, or both key and trusted_ip_header are passed (the header would be silently ignored).

key_by_body_field

key_by_body_field(
    field: str,
    *,
    scope: str | None = None,
    normalize: bool = True,
    hash_value: bool = True,
) -> Callable[[Request], Coroutine[Any, Any, list[str]]]

Build an async key function that buckets by a field of the JSON body.

The body is read with await request.body(). FastAPI reads the body before resolving dependencies and Starlette caches it on the request, so the endpoint still receives its validated payload — the dependency does not consume the stream.

A body that is not JSON, is not an object, or lacks the field (or carries a non-string, non-number value) yields no key, not an error: the endpoint's own validation answers that request with 422, and the other keys of the dependency still count it.

Parameters:

Name Type Description Default
field str

Top-level JSON field whose value is the key (e.g. "email").

required
scope str | None

Prefix of the key. Defaults to field.

None
normalize bool

Strip surrounding whitespace and lowercase the value, so " Ana@X.com" and "ana@x.com" share a bucket.

True
hash_value bool

Store the SHA-256 hex of the value instead of the value itself, so the counter backend never holds the e-mail address (or whatever personal data the field carries) in clear text.

True

Returns:

Type Description
Callable[[Request], Coroutine[Any, Any, list[str]]]

Callable[[Request], Coroutine[Any, Any, list[str]]]: The key

Callable[[Request], Coroutine[Any, Any, list[str]]]

function, yielding ["<scope>:<value>"] or [].

RateLimitRule dataclass

RateLimitRule(
    max_requests: int, window_seconds: float, burst: int | None = None, scope: str = ""
)

One limit applied to a rate-limit key.

With burst unset the rule is a sliding window: at most max_requests requests in any window_seconds interval. With burst set it is a token bucket whose capacity is burst and which refills max_requests / window_seconds tokens per second — so RateLimitRule(600, 60.0, burst=100) sustains 10 requests per second while absorbing a burst of 100.

Attributes:

Name Type Description
max_requests int

Requests allowed per window (sliding window), or tokens refilled per window (token bucket).

window_seconds float

Length of the window, in seconds.

burst int | None

Token-bucket capacity. None (default) selects the sliding-window algorithm.

scope str

Sub-key isolating this rule's counters from the other rules applied to the same principal. Empty (default) derives a deterministic scope from the rule's own numbers, which is unique as long as two rules in one list differ.

is_bucket property

is_bucket: bool

Whether this rule uses the token-bucket algorithm.

Returns:

Name Type Description
bool bool

True when burst is set.

capacity property

capacity: int

Token-bucket capacity, or the window limit for a window rule.

Returns:

Name Type Description
int int

burst when set, else max_requests.

refill_per_second property

refill_per_second: float

Tokens restored per second by the bucket.

Returns:

Name Type Description
float float

max_requests / window_seconds.

effective_scope property

effective_scope: str

Sub-key used to isolate this rule's counters.

Returns:

Name Type Description
str str

scope when set, else a deterministic label built

str

from the rule's numbers (e.g. "600/60s+b100").

QuotaResult dataclass

QuotaResult(
    allowed: bool,
    limit: int,
    remaining: int,
    reset_seconds: int,
    retry_after: int,
    scope: str,
)

Outcome of evaluating a whole rule list against one key.

limit / remaining / reset_seconds describe the binding rule — the one with the least headroom, which is the number a client should pace itself against.

Attributes:

Name Type Description
allowed bool

True when every rule accepted the request.

limit int

max_requests of the binding rule.

remaining int

Requests still allowed under the binding rule.

reset_seconds int

Seconds until the binding rule's counters are fully restored (window elapsed, or bucket refilled to capacity).

retry_after int

Seconds to wait before retrying. 0 when allowed, always >= 1 when rejected.

scope str

:attr:RateLimitRule.effective_scope of the binding rule — names which limit produced these numbers.

QuotaStore

Bases: Protocol

Backend evaluating a list of rules against one key, atomically.

Atomicity across the whole list is the contract: when any rule rejects, no rule may record the request. Otherwise a caller blocked by a daily ceiling would still burn per-minute tokens, and the per-minute limit would drain without a single request being served.

consume async

consume(key: str, rules: Sequence[RateLimitRule]) -> QuotaResult

Charge one request against every rule in rules.

Parameters:

Name Type Description Default
key str

The principal's rate-limit key.

required
rules Sequence[RateLimitRule]

Limits to apply together.

required

Returns:

Name Type Description
QuotaResult QuotaResult

The decision, described by the binding rule.

MemoryQuotaStore

MemoryQuotaStore(*, clock: Callable[[], float] = monotonic)

In-process quota store covering both algorithms.

Counters live in this worker's memory only — correct for a single process. Use :class:RedisQuotaStore when more than one replica must share the quota, otherwise each replica grants the full limit and the effective ceiling is limit x replicas.

Idle keys are swept every :data:_GC_EVERY consumes. Each key records the instant its state becomes indistinguishable from absent — the window's last hit falling out, or the bucket refilling to capacity — and only keys past that instant are dropped. Sweeping on a fixed age instead would hand free capacity to a slow bucket: one refilling at 10 tokens/minute with a burst of 1000 takes over an hour to fill, so evicting it early resets it to full.

Initialize an empty store.

Parameters:

Name Type Description Default
clock Callable[[], float]

Source of the current time, in seconds. Only differences between two readings are used, so any steadily advancing clock works. Defaults to time.monotonic, which a step of the wall clock does not move; pass a controllable clock to make refill deterministic in tests.

monotonic

consume async

consume(key: str, rules: Sequence[RateLimitRule]) -> QuotaResult

Charge one request against every rule under a single lock.

Evaluation is two-phase: every rule is inspected first and the request is recorded only when all of them accept, so a rejection by one rule never consumes another rule's budget.

Parameters:

Name Type Description Default
key str

The principal's rate-limit key.

required
rules Sequence[RateLimitRule]

Limits to apply together.

required

Returns:

Name Type Description
QuotaResult QuotaResult

The decision, described by the binding rule.

Raises:

Type Description
ValueError

If rules is empty.

RedisQuotaStore

RedisQuotaStore(redis: RedisLike, *, namespace: str = 'quota', fail_open: bool = True)

Distributed quota store — every rule evaluated in one Lua call.

A sliding-window rule maps to a sorted set of request timestamps; a token-bucket rule maps to a hash holding tokens and the time ts of the last refill. The script decides every rule first and only writes when all of them accept, so the whole list is atomic — which a client-side loop over several single-rule calls cannot be.

Every timestamp comes from the Redis server's own clock (TIME, read inside the script), never from the calling process, so the replicas sharing a quota cannot disagree about how much time passed. A wall-clock step on an application host no longer refills a bucket or empties a window. What remains is the server's clock: a step on the Redis host still moves every key it holds at once.

When the backend raises and fail_open is True (the default), the request is allowed rather than locking every caller out on a transient Redis outage.

Initialize the store.

Parameters:

Name Type Description Default
redis RedisLike

Async Redis client (e.g. redis.asyncio.Redis).

required
namespace str

Prefix for every Redis key.

'quota'
fail_open bool

Allow the request when the backend errors.

True

consume async

consume(key: str, rules: Sequence[RateLimitRule]) -> QuotaResult

Charge one request against every rule via the Lua script.

Parameters:

Name Type Description Default
key str

The principal's rate-limit key.

required
rules Sequence[RateLimitRule]

Limits to apply together.

required

Returns:

Name Type Description
QuotaResult QuotaResult

The decision, described by the binding rule. On

QuotaResult

a backend error this is allowed when fail_open is

QuotaResult

set.

Raises:

Type Description
ValueError

If rules is empty.

Exception

Propagates the backend error when fail_open is False.

RateLimitPolicy

Bases: Protocol

Resolves which limits apply to a given request.

rules_for

rules_for(request: Request) -> Sequence[RateLimitRule]

Return the rules to charge this request against.

Parameters:

Name Type Description Default
request Request

The inbound request.

required

Returns:

Type Description
Sequence[RateLimitRule]

Sequence[RateLimitRule]: Limits applied together. Must not

Sequence[RateLimitRule]

be empty — an empty list would silently disable the limit.

PlanRateLimitPolicy

PlanRateLimitPolicy(
    plans: Mapping[str, Sequence[RateLimitRule]],
    *,
    resolve: Callable[[Request], str | None],
    default_plan: str,
)

Per-plan quotas — one rule list per tier, resolved per request.

The resolver runs on the raw request (the middleware executes before FastAPI resolves dependencies), so it reads the plan from a token claim or a header. A plan name the mapping does not know falls back to default_plan instead of raising: an unknown tier must be limited, not served unlimited, and a request is the wrong place to discover a configuration typo.

Initialize the policy.

Parameters:

Name Type Description Default
plans Mapping[str, Sequence[RateLimitRule]]

Rule list per plan name (e.g. {"free": [...], "pro": [...]}).

required
resolve Callable[[Request], str | None]

Extracts the plan name from the request. None selects default_plan.

required
default_plan str

Plan used for anonymous traffic and for names missing from plans.

required

Raises:

Type Description
ValueError

If plans is empty, if default_plan is not one of its keys, or if any plan carries no rule. Each would only surface as unlimited traffic at runtime.

plan_for

plan_for(request: Request) -> str

Return the plan name applied to request.

Parameters:

Name Type Description Default
request Request

The inbound request.

required

Returns:

Name Type Description
str str

The resolved plan name, or default_plan when the

str

resolver yields None or an unknown name.

rules_for

rules_for(request: Request) -> Sequence[RateLimitRule]

Return the rule list of the request's plan.

Parameters:

Name Type Description Default
request Request

The inbound request.

required

Returns:

Type Description
Sequence[RateLimitRule]

Sequence[RateLimitRule]: The plan's limits.

StaticRateLimitPolicy

StaticRateLimitPolicy(rules: Sequence[RateLimitRule])

One rule list for every request — quotas without tiers.

The simplest way to use a token bucket or stack a per-minute limit under a daily ceiling when the service has a single tier.

Initialize the policy.

Parameters:

Name Type Description Default
rules Sequence[RateLimitRule]

Limits applied to every request.

required

Raises:

Type Description
ValueError

If rules is empty.

rules_for

rules_for(request: Request) -> Sequence[RateLimitRule]

Return the configured rules.

Parameters:

Name Type Description Default
request Request

The inbound request (unused).

required

Returns:

Type Description
Sequence[RateLimitRule]

Sequence[RateLimitRule]: The configured limits.

plan_by_jwt_claim

plan_by_jwt_claim(
    jwt: _JWTDecoder, claim: str = "plan"
) -> Callable[[Request], str | None]

Build a plan resolver reading a claim from the bearer token.

The token is decoded opportunistically — a missing or invalid token yields None, which the policy maps to its default plan, so anonymous traffic is still limited.

Parameters:

Name Type Description Default
jwt _JWTDecoder

A decoder exposing decode_or_none (e.g. :class:tempest_fastapi_sdk.utils.JWTUtils).

required
claim str

Claim holding the plan name. Defaults to "plan".

'plan'

Returns:

Type Description
Callable[[Request], str | None]

Callable[[Request], str | None]: The resolver.

plan_by_header

plan_by_header(header_name: str) -> Callable[[Request], str | None]

Build a plan resolver reading the plan name from a header.

Only safe when the header is set by your own edge (an API gateway that already authenticated the caller). A client-supplied header lets anyone name their own tier.

Parameters:

Name Type Description Default
header_name str

Header carrying the plan name.

required

Returns:

Type Description
Callable[[Request], str | None]

Callable[[Request], str | None]: The resolver.

key_by_plan_principal

key_by_plan_principal(
    policy: PlanRateLimitPolicy, key_func: Callable[[Request], str]
) -> Callable[[Request], str]

Prefix a principal key with the plan that resolved for it.

Useful when a principal can move between tiers and you want the upgrade to take effect immediately: the new plan writes to fresh counters instead of inheriting the exhausted ones. The trade-off is that a caller able to choose their plan (a client-supplied header) could reset their own counters by switching — pair it with a resolver your edge controls.

Parameters:

Name Type Description Default
policy PlanRateLimitPolicy

Policy resolving the plan name.

required
key_func Callable[[Request], str]

Principal key function (e.g. :func:~tempest_fastapi_sdk.key_by_jwt_subject).

required

Returns:

Type Description
Callable[[Request], str]

Callable[[Request], str]: A key function yielding

Callable[[Request], str]

"<plan>:<principal key>".

GoogleOAuthClient

GoogleOAuthClient(
    *,
    client_id: str,
    client_secret: str,
    redirect_uri: str,
    scopes: list[str] | None = None,
    http_client: HTTPClient | None = None,
    extra_audiences: Sequence[str] = (),
)

Bases: _BaseOAuthClient

Google identity client (OIDC-compatible).

Default scopes: openid email profile.

authorize_url property

authorize_url: str

Google's authorize endpoint.

Returns:

Name Type Description
str str

The configured endpoint URL.

token_url property

token_url: str

Google's token endpoint.

Returns:

Name Type Description
str str

The configured endpoint URL.

userinfo_url property

userinfo_url: str | None

OIDC-flavored userinfo endpoint.

Returns:

Type Description
str | None

str | None: The endpoint URL, or None when the provider advertises none.

tokeninfo_url property

tokeninfo_url: str | None

Google's tokeninfo endpoint, which reports aud and azp.

Returns:

Type Description
str | None

str | None: The endpoint the audience check queries.

GitHubOAuthClient

GitHubOAuthClient(
    *,
    client_id: str,
    client_secret: str,
    redirect_uri: str,
    scopes: list[str] | None = None,
    http_client: HTTPClient | None = None,
    extra_audiences: Sequence[str] = (),
)

Bases: _BaseOAuthClient

GitHub OAuth client.

GitHub doesn't issue an id_token — the user identity comes from GET /user. Default scopes: read:user user:email.

authorize_url property

authorize_url: str

GitHub's authorize endpoint.

Returns:

Name Type Description
str str

The configured endpoint URL.

token_url property

token_url: str

GitHub's token endpoint.

Returns:

Name Type Description
str str

The configured endpoint URL.

userinfo_url property

userinfo_url: str | None

GitHub's user-info endpoint.

Returns:

Type Description
str | None

str | None: The endpoint URL, or None when the provider advertises none.

emails_url property

emails_url: str

GitHub's endpoint listing the account's addresses and their status.

Returns:

Name Type Description
str str

The endpoint URL.

verify_token_audience async

verify_token_audience(tokens: OAuthTokens) -> None

Ask GitHub whether the token belongs to this OAuth app.

GitHub publishes no tokeninfo endpoint. What it does publish is POST /applications/{client_id}/token, authenticated with the app's own client_id:client_secret — it answers 200 only for a token that app issued, and 404 for anybody else's. That is the same question :meth:_BaseOAuthClient.verify_token_audience asks, so the refusals it raises are the same ones.

Parameters:

Name Type Description Default
tokens OAuthTokens

The bundle the caller presented.

required

Raises:

Type Description
OAuthTokenAudienceMismatchException

When GitHub does not recognize the token as this application's (404).

OAuthTokenRejectedException

When GitHub refuses the check for any other reason.

fetch_user async

fetch_user(tokens: OAuthTokens) -> OAuthUser

Resolve the token to an identity whose email GitHub verified.

GET /user returns the public profile email, which GitHub does not require to be verified, and no verification flag at all. The account will only sign in or be created on an address the provider states it verified, so this also reads GET /user/emails (scope user:email, in the default scopes) and picks, in order: the primary address when verified; otherwise the profile address, carrying the verified flag GitHub reports for it. When the list cannot be read — the scope was not granted, or GitHub answers an error — the profile is returned as GET /user gave it, with email_verified left None, which the service treats as "not verified".

Parameters:

Name Type Description Default
tokens OAuthTokens

Bundle returned by :meth:exchange_code.

required

Returns:

Name Type Description
OAuthUser OAuthUser

Normalized identity.

Raises:

Type Description
OAuthError

When GET /user rejects the token.

OIDCProvider

OIDCProvider(
    *,
    client_id: str,
    client_secret: str,
    redirect_uri: str,
    authorize_url: str,
    token_url: str,
    userinfo_url: str | None = None,
    tokeninfo_url: str | None = None,
    introspection_url: str | None = None,
    provider_name: str = "oidc",
    scopes: list[str] | None = None,
    http_client: HTTPClient | None = None,
    extra_audiences: Sequence[str] = (),
    token_verifier: OIDCTokenVerifier | None = None,
)

Bases: _BaseOAuthClient

Generic OIDC provider — works with any conformant IdP.

Pass the authorize / token / userinfo endpoints explicitly, or fetch them once at boot from the IdP's discovery document at ${issuer}/.well-known/openid-configuration and pass the URLs in. Default scopes: openid email profile.

With a token_verifier, the access token is checked offline against the realm's published signing keys: the audience check and the identity both come from the verified claims, and neither tokeninfo_url nor userinfo_url is called. Without one, the provider asks the IdP, exactly as before.

Initialize.

Parameters:

Name Type Description Default
client_id str

App client id at the IdP.

required
client_secret str

App client secret.

required
redirect_uri str

Registered callback URL.

required
authorize_url str

IdP's authorize endpoint.

required
token_url str

IdP's token endpoint.

required
userinfo_url str | None

IdP's userinfo endpoint. None requires you to override :meth:_parse_user to read claims from the id_token.

None
tokeninfo_url str | None

A tokeninfo endpoint called as GET <url>?access_token=<token> (Google's shape), used to check which application a presented token was issued to. Not for RFC 7662 introspection: measured on Keycloak 26.3, that GET answers 405 and every token is refused — use introspection_url.

None
introspection_url str | None

The IdP's RFC 7662 introspection endpoint (Keycloak: <issuer>/protocol/openid-connect/token/introspect). Called as POST token=<token> authenticated with client_id / client_secret in the form body, the same client_secret_post the code exchange uses. None of this, tokeninfo_url and token_verifier leaves POST /auth/oauth/{provider}/token refusing for this provider — the redirect flow is unaffected.

None
provider_name str

Key embedded in :attr:OAuthUser.provider (e.g. "oidc:auth0").

'oidc'
scopes list[str] | None

Scopes to request.

None
http_client HTTPClient | None

Shared client.

None
extra_audiences Sequence[str]

Other client ids of the same application whose tokens the token-in-hand route accepts.

()
token_verifier OIDCTokenVerifier | None

Offline verifier for the realm's signed access tokens. When set, :meth:verify_token_audience and :meth:fetch_user read the verified claims instead of calling tokeninfo_url / userinfo_url. None keeps the round-trip behavior.

None

Raises:

Type Description
ValueError

When both tokeninfo_url and introspection_url are given: they are two ways to ask the same question, and silently preferring one would hide a misconfiguration.

authorize_url property

authorize_url: str

The provider's authorization endpoint, from discovery or config.

Returns:

Name Type Description
str str

The configured endpoint URL.

token_url property

token_url: str

The provider's token endpoint, from discovery or config.

Returns:

Name Type Description
str str

The configured endpoint URL.

userinfo_url property

userinfo_url: str | None

The provider's userinfo endpoint, when it advertises one.

Returns:

Type Description
str | None

str | None: The endpoint URL, or None when the provider advertises none.

tokeninfo_url property

tokeninfo_url: str | None

The IdP's token-introspection endpoint, when one was wired.

Returns:

Type Description
str | None

str | None: The endpoint URL, or None — which keeps

str | None

POST /auth/oauth/{provider}/token refusing for this

str | None

provider, since its audience cannot be checked.

introspection_url property

introspection_url: str | None

The IdP's RFC 7662 introspection endpoint, when one was wired.

Returns:

Type Description
str | None

str | None: The endpoint URL, or None.

verify_token_audience async

verify_token_audience(tokens: OAuthTokens) -> None

Refuse a token minted for another application, or forged.

With a token_verifier the token's signature, iss, exp and audience are checked offline against the realm's signing keys. Without one, an introspection_url is asked by RFC 7662 POST (see :meth:_introspect), and without that the tokeninfo_url is asked by GET, as in :meth:_BaseOAuthClient.verify_token_audience.

Parameters:

Name Type Description Default
tokens OAuthTokens

The bundle the caller presented.

required

Raises:

Type Description
OAuthTokenRejectedException

When the token is malformed, signed by an unknown key, expired or from another issuer — or when the IdP refuses it.

OAuthTokenAudienceMismatchException

When the token was issued to a different client.

OAuthProviderUnavailableException

When the realm's signing keys or its introspection endpoint cannot be read.

OAuthError

When the introspection endpoint refuses our client credentials.

OAuthAudienceUnverifiableException

When no verifier, introspection_url or tokeninfo_url is configured.

fetch_user async

fetch_user(tokens: OAuthTokens) -> OAuthUser

Resolve the access token to a normalized :class:OAuthUser.

With a token_verifier the identity is read from the verified access-token claims with no round-trip to the IdP. The token is verified again here rather than trusted from an earlier call — the signing key is cached, so the second check costs no request. The claims only carry email / name when the realm puts them in the access token.

Parameters:

Name Type Description Default
tokens OAuthTokens

The bundle to resolve.

required

Returns:

Name Type Description
OAuthUser OAuthUser

Normalized identity.

Raises:

Type Description
OAuthTokenRejectedException

When offline verification refuses the token.

OAuthTokenAudienceMismatchException

When the token was issued to a different client.

OAuthProviderUnavailableException

When the realm's signing keys cannot be read.

OAuthError

When the userinfo endpoint rejects the token (no verifier configured).

OAuthUser dataclass

OAuthUser(
    provider: str,
    subject: str,
    email: str | None = None,
    email_verified: bool | None = None,
    name: str | None = None,
    picture: str | None = None,
    raw: dict[str, Any] = dict(),
)

Normalized user identity returned by every provider.

Different IdPs use different field names (sub vs id, picture vs avatar_url, name vs login). This dataclass is the single shape the rest of the application sees.

Attributes:

Name Type Description
provider str

Provider key ("google", "github", "oidc:auth0" …). Useful when multiple providers feed the same user table.

subject str

Stable per-provider user id. Combine with provider for a globally-unique key.

email str | None

The email the provider returned, if any. Some IdPs gate this behind extra scopes. Not necessarily verified — check email_verified before trusting it.

email_verified bool | None

Whether the provider states it has verified email. None means the provider said nothing either way, which is not the same as True.

name str | None

Human-readable display name.

picture str | None

Avatar / profile picture URL.

raw dict[str, Any]

Full provider payload for advanced cases (custom claims, role mappings).

OAuthTokens dataclass

OAuthTokens(
    access_token: str,
    token_type: str,
    refresh_token: str | None = None,
    id_token: str | None = None,
    expires_in: int | None = None,
    scope: str | None = None,
    raw: dict[str, Any] = dict(),
)

Tokens returned by the IdP after the authorization-code exchange.

Attributes:

Name Type Description
access_token str

Bearer token to call provider APIs.

token_type str

Usually "Bearer".

refresh_token str | None

Refresh token when offline access was requested.

id_token str | None

OIDC id token (JWT). Present on OIDC flows, absent on plain OAuth2.

expires_in int | None

Lifetime of access_token in seconds.

scope str | None

Space-separated scopes granted.

raw dict[str, Any]

Full token-endpoint response.

OAuthError

OAuthError(
    message: str | None = None,
    *,
    code: str | None = None,
    status_code: int | None = None,
    details: dict[str, Any] | None = None,
    headers: dict[str, str] | None = None,
    message_key: str | None = None,
    message_params: dict[str, Any] | None = None,
    field: str | None = None,
)

Bases: AppException

Raised when an OAuth exchange fails — wraps the IdP message.

OAuthProviderUnavailableException

OAuthProviderUnavailableException(
    message: str | None = None,
    *,
    code: str | None = None,
    status_code: int | None = None,
    details: dict[str, Any] | None = None,
    headers: dict[str, str] | None = None,
    message_key: str | None = None,
    message_params: dict[str, Any] | None = None,
    field: str | None = None,
)

Bases: OAuthError

Raised when the IdP cannot answer whether a token is valid.

The failure of token verification that is not the caller's fault: the realm is unreachable, answered with an error status, or served something that is not a usable JWK Set or introspection response. details["reason"] names which call failed. It answers 502 because retrying later can succeed — unlike a token signed by a key nobody published, which is refused with :class:~tempest_fastapi_sdk.exceptions.oauth.OAuthTokenRejectedException (401) since retrying the same value can never work.

Subclasses :class:OAuthError, so except OAuthError keeps catching every provider-side failure.

OIDCTokenVerifier

OIDCTokenVerifier(
    issuer: str,
    jwks_url: str,
    *,
    algorithms: Sequence[str] = ("RS256",),
    required_claims: Sequence[str] = ALWAYS_REQUIRED_CLAIMS,
    leeway: float = 0,
    lifespan: float = 300,
    min_refresh_interval: float = 60,
    http_client: HTTPClient | None = None,
)

Verify realm-signed JWT access tokens against the realm's JWK Set.

The key set is fetched with the injected async :class:~tempest_fastapi_sdk.utils.http_client.HTTPClient and parsed with jwt.PyJWKSet.from_dict. jwt.PyJWKClient is deliberately not used: its fetch is blocking I/O (it would need a thread per refresh), and it refetches the key set once per unknown kid, so a stream of tokens carrying forged kid values turns into the same stream of requests to the IdP. Here a miss triggers at most one refresh per min_refresh_interval, and concurrent misses share it.

The alg list is closed and never read from the token: the header is attacker-controlled, so none or HS256 (verifying an RSA public key as an HMAC secret) are refused before any key is looked up. aud is checked by the SDK rather than by PyJWT, over aud, azp and client_id together — Keycloak puts the resource the token addresses in aud (usually "account") and names the client in azp, so PyJWT's verify_aud would refuse every legitimate token.

Attributes:

Name Type Description
issuer str

The iss every token must carry.

jwks_url str

Where the realm publishes its JWK Set.

algorithms tuple[str, ...]

Signing algorithms accepted.

required_claims tuple[str, ...]

Claims a token must carry; always includes :data:ALWAYS_REQUIRED_CLAIMS.

leeway float

Clock skew tolerated on exp / nbf / iat, in seconds.

lifespan float

Seconds a fetched key set is trusted before the next verification refreshes it.

min_refresh_interval float

Minimum seconds between two fetches of the key set, whatever triggers them.

Initialize.

Parameters:

Name Type Description Default
issuer str

The realm's issuer, exactly as it appears in the iss claim (for Keycloak, https://<host>/realms/<realm>).

required
jwks_url str

The realm's JWK Set endpoint — the jwks_uri of its discovery document (for Keycloak, <issuer>/protocol/openid-connect/certs).

required
algorithms Sequence[str]

Signing algorithms accepted. Closed on purpose; none is refused even if listed.

('RS256',)
required_claims Sequence[str]

Claims a token must carry. exp, iss and sub are added when omitted.

ALWAYS_REQUIRED_CLAIMS
leeway float

Clock skew tolerated, in seconds.

0
lifespan float

Seconds a fetched key set is trusted.

300
min_refresh_interval float

Minimum seconds between two key-set fetches. Bounds what forged kid values can cost the IdP: one request per interval, not one per token.

60
http_client HTTPClient | None

Shared client for the key-set fetch. None builds a dedicated one (timeout 10s, breaker off); close it with :meth:aclose.

None

Raises:

Type Description
ImportError

When the [oidc] extra (PyJWT with cryptography) is missing.

ValueError

When algorithms is empty or only none, or when a duration is negative.

aclose async

aclose() -> None

Close the underlying HTTP client when this verifier owns it.

verify async

verify(token: str, *, accepted_audiences: Iterable[str]) -> dict[str, Any]

Verify token and return its claims.

Order matters and is part of the contract: the header is parsed and its alg checked before any key-set request, so a malformed or alg: none token costs the IdP nothing.

Parameters:

Name Type Description Default
token str

The compact JWT the caller presented.

required
accepted_audiences Iterable[str]

Client ids this application answers to, compared against aud, azp and client_id.

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: The verified claims.

Raises:

Type Description
OAuthTokenRejectedException

When the token is not a JWT, its alg is not accepted, its kid is unknown, or its signature, iss, exp or a required claim is invalid.

OAuthTokenAudienceMismatchException

When the token was issued to another client.

OAuthAudienceUnverifiableException

When accepted_audiences holds no client id.

OAuthProviderUnavailableException

When the key set cannot be read.

ALWAYS_REQUIRED_CLAIMS module-attribute

ALWAYS_REQUIRED_CLAIMS: tuple[str, ...] = ('exp', 'iss', 'sub')

Claims every verified token must carry, whatever the caller configures.

exp is the one that matters most: PyJWT checks it only when present, so a token without it would otherwise verify forever.

generate_oauth_state

generate_oauth_state(n_bytes: int = 32) -> str

Mint a CSRF-grade state for the authorize URL.

The state ties the inbound callback to the originating session — store it server-side (or in a signed cookie) before redirecting, then compare on callback. Any mismatch means a forged redirect; reject with 400.

Parameters:

Name Type Description Default
n_bytes int

Entropy bytes. Default 32.

32

Returns:

Name Type Description
str str

URL-safe random token.

OAuthClient

Bases: Protocol

The three calls the bundled auth router makes on a provider.

Every client in this module satisfies it, and so does anything else that speaks the same three moves — which is the point: the router resolves /auth/oauth/{provider}/… against a mapping the application registered, so a provider the SDK does not ship, or a stub that never touches the network in tests, is wired the same way Google is. Naming the shape as a protocol keeps _BaseOAuthClient private without forcing consumers to subclass it.

Attributes:

Name Type Description
provider_name str

Key this client answers to. Stored on every linked-identity row, so changing it after accounts exist orphans them.

build_authorize_url

build_authorize_url(*, state: str, **extra: str) -> str

Render the URL the browser must be redirected to.

Parameters:

Name Type Description Default
state str

CSRF state to echo back on the callback.

required
**extra str

Extra query parameters.

{}

Returns:

Name Type Description
str str

The provider's authorize URL.

exchange_code async

exchange_code(code: str) -> OAuthTokens

Swap an authorization code for tokens.

Parameters:

Name Type Description Default
code str

The code query parameter from the callback.

required

Returns:

Name Type Description
OAuthTokens OAuthTokens

The provider's token bundle.

fetch_user async

fetch_user(tokens: OAuthTokens) -> OAuthUser

Resolve tokens to a normalized identity.

Parameters:

Name Type Description Default
tokens OAuthTokens

The bundle from :meth:exchange_code.

required

Returns:

Name Type Description
OAuthUser OAuthUser

The normalized identity.

apply_cors

apply_cors(
    app: FastAPI,
    settings: CORSSettings | None = None,
    *,
    origins: list[str] | None = None,
    origin_regex: str | None = None,
    allow_credentials: bool | None = None,
    allow_methods: list[str] | None = None,
    allow_headers: list[str] | None = None,
    expose_headers: list[str] | None = None,
    max_age: int | None = None,
) -> None

Attach CORSMiddleware to app using SDK conventions.

All overrides are optional; when provided they take precedence over the matching field on settings. When neither is provided, a permissive default suitable for local development is used (origins=["*"], no credentials).

Parameters:

Name Type Description Default
app FastAPI

The application to mutate.

required
settings CORSSettings | None

Source of the defaults. When None, a fresh :class:CORSSettings instance is built.

None
origins list[str] | None

Override for :attr:CORSSettings.CORS_ORIGINS.

None
origin_regex str | None

Override for :attr:CORSSettings.CORS_ORIGIN_REGEX. Matched against the request Origin for session-varying origins (dev tunnels, preview deploys). An empty string disables it.

None
allow_credentials bool | None

Override.

None
allow_methods list[str] | None

Override.

None
allow_headers list[str] | None

Override.

None
expose_headers list[str] | None

Override.

None
max_age int | None

Override.

None

make_health_router

make_health_router(
    *,
    db: AsyncDatabaseManager | None = None,
    checks: dict[str, HealthCheck] | None = None,
    prefix: str = "/health",
    tag: str = "health",
    version: str | None = None,
    expose_checks: bool = True,
    timeout: float | None = 3.0,
    docs_locale: str | None = None,
) -> APIRouter

Build the canonical /health router.

Two endpoints are mounted:

  • GET <prefix>/liveness — always returns {"status": "ok"} so orchestrators can confirm the process is up. Should not depend on any external resource (Kubernetes treats failed liveness probes as "restart the pod"). This endpoint takes precedence over readiness for that reason.
  • GET <prefix>/readiness — runs every configured check concurrently, each bounded by timeout, and returns 200 only when all pass. Returns 503 when at least one fails, raises or times out. One hung dependency fails only its own check, and the response still arrives after about timeout.

A failing check is logged with its name and the exception type only. The exception message is never logged, because driver messages often carry the connection DSN with its credentials.

Parameters:

Name Type Description Default
db AsyncDatabaseManager | None

When provided, a database check is registered automatically using :meth:AsyncDatabaseManager.health_check.

None
checks dict[str, HealthCheck] | None

Extra readiness checks keyed by name (e.g. "redis", "rabbitmq").

None
prefix str

The URL prefix for the router. Defaults to "/health" — keep it at the application root, not under /api.

'/health'
tag str

OpenAPI tag applied to both endpoints.

'health'
version str | None

When provided, attached to the readiness payload as version.

None
expose_checks bool

Whether to surface the per-dependency breakdown in the readiness payload. Defaults to True for development ergonomics; set False in production so unauthenticated probes don't reveal which backends (database, Redis, RabbitMQ, etc.) the service depends on.

True
timeout float | None

Seconds each readiness check may take before it is cancelled and counted as failed. Defaults to 3 seconds; keep it below the probe timeout of the orchestrator. None disables the bound. Cancellation only interrupts a check at an await: a check that blocks the event loop with synchronous I/O cannot be timed out.

3.0
docs_locale str | None

Language of the OpenAPI summary and description text — "en-US" or "pt-BR". None (default) reads API_DOCS_LOCALE through :class:~tempest_fastapi_sdk.settings.ServerSettings, whose default is "en-US".

None

Returns:

Name Type Description
APIRouter APIRouter

A router ready to include_router(...) on the

APIRouter

FastAPI app.

Raises:

Type Description
ValueError

When timeout is not positive.

make_logs_router

make_logs_router(
    *,
    log_dir: str | Path = "logs",
    token_secret: str = "",
    allow_unauthenticated: bool = False,
    dependencies: Sequence[Callable[..., Any] | Depends] | None = None,
    prefix: str = "/logs",
    tag: str = "logs",
    header_name: str = "X-Token",
    default_page_size: int = 20,
    max_page_size: int = 200,
    max_records_per_file: int = DEFAULT_MAX_RECORDS_PER_FILE,
    docs_locale: str | None = None,
) -> APIRouter

Build a router that serves the on-disk JSON logs, paginated.

Mounts GET <prefix> which reads the files produced by :func:tempest_fastapi_sdk.configure_logging (called with log_dir=...) through :func:read_log_entries and returns a :class:BasePaginationSchema of :class:LogEntrySchema, newest records first. DELETE <prefix> empties the same files through :func:clear_log_files. The router is a shell over those two functions; a service that wants another response contract calls them directly.

Authentication. Both endpoints run the same gate, built from two independent pieces:

  • token_secret — a shared secret checked in the header_name header via :func:make_token_dependency. An empty value turns this piece off.
  • dependencies — FastAPI dependencies of the service's own auth (an admin JWT check, a role dependency). Each item is either the callable or a ready Depends(...) / Security(...); both spellings are accepted, and a ready one is not wrapped twice.

The pieces add up: with both set, a request needs the header and has to pass every dependency. With only dependencies, they replace the header — no X-Token is read and none is required. With neither, construction is refused unless allow_unauthenticated=True.

The refusal is fail-closed on purpose. make_token_dependency reads an empty secret as "nothing to check", so a router built from a settings field the environment left empty would still answer 200 and the missing gate would look like a working endpoint, while GET hands out tracebacks and request metadata and DELETE truncates the files. Raising turns that gap into a startup error, and the opt-out is a named flag the reader of the call site sees. An empty dependencies list does not count as a gate.

Leading and trailing whitespace in token_secret is stripped before the check and before the comparison. A whitespace-only value is not a secret, and a padded one locks clients out: httpx refuses to send a header value with surrounding whitespace, and uvicorn's h11 parser strips it on arrival.

Parameters:

Name Type Description Default
log_dir str | Path

Directory holding the log files. Must match the log_dir passed to configure_logging. Defaults to "logs".

'logs'
token_secret str

Shared secret expected in the header_name header. Required unless dependencies is non-empty or allow_unauthenticated is True.

''
allow_unauthenticated bool

Build the router without any gate, answering every request that reaches it. Meant for a local run nothing else can reach. Has no effect when token_secret or dependencies is set. Defaults to False.

False
dependencies Sequence[Callable[..., Any] | Depends] | None

Extra dependencies run on both routes, after the X-Token check when there is one. Callables are wrapped in Depends; Depends(...) / Security(...) objects are used as given. Defaults to None.

None
prefix str

URL prefix for the router. Defaults to "/logs" — mount it at the application root, not under /api.

'/logs'
tag str

OpenAPI tag applied to the endpoints.

'logs'
header_name str

Auth header name. Defaults to "X-Token".

'X-Token'
default_page_size int

Page size when the caller omits it.

20
max_page_size int

Upper bound enforced on page_size.

200
max_records_per_file int

How many of the newest records are read from each file per request. See :data:DEFAULT_MAX_RECORDS_PER_FILE — the bound is what keeps a large log directory from being read into memory whole. When it bites, a warning is logged naming the source.

DEFAULT_MAX_RECORDS_PER_FILE
docs_locale str | None

Language of the OpenAPI summary and description text — "en-US" or "pt-BR". None (default) reads API_DOCS_LOCALE through :class:~tempest_fastapi_sdk.settings.ServerSettings, whose default is "en-US".

None

Returns:

Name Type Description
APIRouter APIRouter

A router ready to include_router(...) on the app.

Raises:

Type Description
ValueError

When token_secret is empty or whitespace-only, dependencies is empty or None, and allow_unauthenticated is False. Also when log_dir is an empty string — file logging is off, and the router would otherwise read and truncate the current working directory.

resolve_log_files

resolve_log_files(
    log_dir: str | Path, source: LogSource, *, include_http_500: bool = False
) -> list[Path]

Resolve which files a source selector points at.

Public because the mapping from a level name to a file name is the SDK's layout decision, not the caller's: a service that wants to truncate, archive, ship or count these files was re-deriving {"info": "info.log", ...} from :data:LEVEL_LOG_FILES by hand, and that copy drifts the day a level is added.

include_http_500 is the one place the two callers disagree. Reading "all" must not include 500.log, because every record in it is also in error.log and the page would list it twice. Truncating "all" must include it, because a clear that silently left the 500 stream behind is the surprising outcome.

Parameters:

Name Type Description Default
log_dir str | Path

Directory holding the log files.

required
source LogSource

The requested source selector.

required
include_http_500 bool

Whether "all" also covers 500.log. Ignored for every other selector.

False

Returns:

Type Description
list[Path]

list[Path]: The files the selector covers, existing or not —

list[Path]

callers decide whether a missing file is skipped or created.

Raises:

Type Description
ValueError

When log_dir is an empty string (file logging off), which :class:~pathlib.Path would turn into the current working directory.

read_log_entries

read_log_entries(
    log_dir: str | Path,
    source: LogSource = "all",
    *,
    q: str | None = None,
    start: datetime | None = None,
    end: datetime | None = None,
    max_records_per_file: int = DEFAULT_MAX_RECORDS_PER_FILE,
) -> LogReadResult

Read, filter and sort the on-disk JSON logs, newest first.

The read behind GET /logs and the admin log page, public so a service that needs another response contract does not rewrite it. Rewriting it is how the per-file memory bound gets lost: a hand-written reader that loads each file whole works on a fresh log directory and kills the worker on a multi-gigabyte one.

Each level file is read together with its rotated backups (:func:rotated_log_files): info.log.1 under size-based rotation, info.log.2026-10-20 under configure_logging(rotate_when=...). Only the newest max_records_per_file records of each level file, backups included, are read through a bounded :class:collections.deque; truncated reports when the bound cut a file. Missing files and malformed lines are skipped.

The function is synchronous file I/O. From an async route, run it off the event loop:

result = await asyncio.to_thread(read_log_entries, "logs", "error")

Parameters:

Name Type Description Default
log_dir str | Path

Directory holding the log files — the log_dir passed to configure_logging.

required
source LogSource

Which file(s) to read. "all" merges every level and leaves 500.log out, since each of its records is also in error.log. Defaults to "all".

'all'
q str | None

Case-insensitive substring the message must contain.

None
start datetime | None

Keep records at or after this instant. A value without an offset is read as UTC.

None
end datetime | None

Keep records at or before this instant. A value without an offset is read as UTC.

None
max_records_per_file int

How many of the newest records are read from each level file, its rotated backups included. Defaults to :data:DEFAULT_MAX_RECORDS_PER_FILE.

DEFAULT_MAX_RECORDS_PER_FILE

Returns:

Name Type Description
LogReadResult LogReadResult

The matching records, newest first, and whether the

LogReadResult

per-file bound cut any file. An empty log_dir string (file

LogReadResult

logging off) reads as no files — never as the current directory.

clear_log_files

clear_log_files(
    log_dir: str | Path, source: LogSource = "all", *, delete_backups: bool = False
) -> list[str]

Empty the log files a source selector points at.

The truncate behind DELETE /logs, public for the same reason as :func:read_log_entries. Files are truncated in place, not unlinked: the handlers :func:tempest_fastapi_sdk.configure_logging attached hold an open descriptor on each path, and deleting the file would leave them writing to an inode nothing can read back. A missing file is created empty, so the post-condition is the same either way.

Unlike reading, "all" covers 500.log as well: a clear that left the 500 stream behind is the surprising outcome.

Rotated backups (:func:rotated_log_files — info.log.1 or info.log.2026-10-20) are left alone by default, as they always were: deleting them is unrecoverable, and a caller that only meant "start a clean view" should not lose a week of history. Since :func:read_log_entries reads them, the page keeps showing the older periods after a default clear. Pass delete_backups=True to remove them too — no handler holds them open, so unlinking is safe.

The function is synchronous file I/O. From an async route, run it off the event loop:

cleared = await asyncio.to_thread(clear_log_files, "logs", "info")

Parameters:

Name Type Description Default
log_dir str | Path

Directory holding the log files.

required
source LogSource

Which file(s) to truncate. Defaults to "all".

'all'
delete_backups bool

Also delete the rotated backups of each file. Defaults to False.

False

Returns:

Type Description
list[str]

list[str]: The names of the files that were emptied, in

list[str]

func:resolve_log_files order — each followed, under

list[str]

delete_backups=True, by the names of the backups deleted next

list[str]

to it.

Raises:

Type Description
ValueError

When log_dir is an empty string (file logging off) — truncating the current working directory's files is never the intent.

OSError

When a path cannot be opened for writing, or a backup cannot be deleted.

LogReadResult dataclass

LogReadResult(entries: list[dict[str, Any]] = list(), truncated: bool = False)

The outcome of :func:read_log_entries.

Attributes:

Name Type Description
entries list[dict[str, Any]]

The matching records, already filtered and sorted newest first. Each one is the JSON object the formatter wrote, verbatim — every extra={...} key included. Empty when nothing matched, or when no selected file exists.

truncated bool

Whether at least one selected file held more records than max_records_per_file, so its oldest records were not read. A partial view must never read as a complete one, so callers surface it (the router logs a WARNING).

DEFAULT_MAX_RECORDS_PER_FILE module-attribute

DEFAULT_MAX_RECORDS_PER_FILE: int = 20000

How many of the newest records are read from each log file per request.

A bound is required, not tuning: without one the endpoint materialized every line of every selected file before paginating, so a service whose log directory had grown to gigabytes answered with a dead worker. 20k records per file is far past any page a caller can reach (the largest page is max_page_size) while keeping the read a bounded, predictable cost.

render_entries_markdown

render_entries_markdown(
    entries: list[dict[str, Any]],
    *,
    source: str = "all",
    query: str | None = None,
    truncated_from: int | None = None,
) -> str

Render log records as a markdown document ready to paste into an issue.

Built for the "a 500 happened, hand me the trace" loop: the on-disk records already carry the formatted traceback under exception (the SDK's exception handlers log with exc_info=True), but reading it out of a paginated HTML table or a JSON blob is painful. This lays each record out with its context fields and puts the traceback in a fenced pytb block.

Parameters:

Name Type Description Default
entries list[dict[str, Any]]

The records to render, in the order they should appear (the callers pass newest-first).

required
source str

The log source the export came from, echoed in the header so a pasted document says what it is.

'all'
query str | None

The message filter that produced the selection, also echoed — an export of a filtered view is otherwise indistinguishable from a complete one.

None
truncated_from int | None

When the selection was capped, the total number of matching records. Stated in the header rather than left implicit, so a partial export never reads as an exhaustive one.

None

Returns:

Name Type Description
str str

The markdown document. A header is always present, so an empty selection still produces something self-describing.

render_entries_json

render_entries_json(entries: list[dict[str, Any]]) -> str

Render log records as a pretty-printed JSON array.

The records are emitted verbatim — every field the application logged, traceback included — so the output can be fed to tooling rather than read. Non-serializable values fall back to their str() form so one exotic extra= value cannot fail the whole export.

Parameters:

Name Type Description Default
entries list[dict[str, Any]]

The records to render.

required

Returns:

Name Type Description
str str

The JSON document, indented for diff-friendliness.

PrometheusMiddleware

PrometheusMiddleware(
    app: ASGIApp,
    *,
    registry: CollectorRegistry,
    latency_buckets: tuple[float, ...] = DEFAULT_LATENCY_BUCKETS,
)

Bases: BaseHTTPMiddleware

ASGI middleware tracking HTTP requests on three core metrics.

Registered series:

  • http_requests_total{method, path, status} (Counter) — every request counts here once the response status is known.
  • http_request_duration_seconds{method, path} (Histogram) — end-to-end latency in seconds.
  • http_requests_in_progress{method} (Gauge) — live inflight count, decremented in a finally so dropped connections never leave stale gauges.

The path label uses the route template (e.g. /orders/{order_id}) when the request hit a FastAPI route, not the raw URL, and "<unmatched>" when it hit none (every 404 shares that one value). The method label is the request method when it is a standard one (GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, CONNECT, TRACE) and "OTHER" for any other token. Neither label takes a value the client chooses freely, so the number of series is bounded by routes x methods x statuses.

Initialize the middleware.

Parameters:

Name Type Description Default
app ASGIApp

The wrapped ASGI app.

required
registry CollectorRegistry

Shared registry. Reuse the same instance for make_prometheus_router so the /metrics endpoint scrapes these series.

required
latency_buckets tuple[float, ...]

Histogram bucket upper bounds in seconds.

DEFAULT_LATENCY_BUCKETS

Raises:

Type Description
ImportError

When the [prometheus] extra is missing.

dispatch async

dispatch(
    request: Request, call_next: Callable[[Request], Awaitable[Response]]
) -> Response

Wrap the request with counters, gauge, and latency timer.

Parameters:

Name Type Description Default
request Request

The inbound request.

required
call_next Callable[[Request], Awaitable[Response]]

The next handler in the middleware chain.

required

Returns:

Name Type Description
Response Response

The downstream response, after this middleware ran.

make_prometheus_router

make_prometheus_router(
    *,
    registry: CollectorRegistry,
    path: str = "/metrics",
    dependencies: list[Callable[..., Any] | Depends] | None = None,
) -> APIRouter

Build the GET /metrics router scraping registry.

The endpoint is unauthenticated by default: without dependencies anyone who reaches the port can scrape it, and metric labels leak the service's route structure. Gate it with a header-based dependency such as :func:make_token_dependency.

Each item of dependencies may be a bare dependency callable (wrapped in Depends here) or an already-built Depends(...) / Security(...) marker (attached as-is, never wrapped twice).

Parameters:

Name Type Description Default
registry CollectorRegistry

The same registry passed to :class:PrometheusMiddleware and any custom metric.

required
path str

Endpoint path. Defaults to /metrics.

'/metrics'
dependencies list[Callable[..., Any] | Depends] | None

FastAPI dependencies attached to the route. None (default) leaves the endpoint open.

None

Returns:

Name Type Description
APIRouter APIRouter

Mount with app.include_router(router).

Raises:

Type Description
ImportError

When the [prometheus] extra is missing.

TypeError

When dependencies contains :func:require_x_token, whose parameters FastAPI would read from the query string.

Examples:

>>> from tempest_fastapi_sdk import (
...     make_prometheus_registry,
...     make_prometheus_router,
...     make_token_dependency,
... )
>>> router = make_prometheus_router(
...     registry=make_prometheus_registry(),
...     dependencies=[make_token_dependency("scrape-secret")],
... )
>>> [route.path for route in router.routes]
['/metrics']

make_prometheus_registry

make_prometheus_registry() -> CollectorRegistry

Build a fresh :class:CollectorRegistry.

Use this once at app boot, share the registry across the middleware and any custom metric you register, then pass it to :func:make_prometheus_router.

Returns:

Name Type Description
CollectorRegistry CollectorRegistry

An empty registry, decoupled from the

CollectorRegistry

prometheus_client default singleton so tests don't bleed

CollectorRegistry

metrics between runs.

Raises:

Type Description
ImportError

When the [prometheus] extra is missing.

BusinessMetrics

BusinessMetrics(registry: CollectorRegistry, *, namespace: str = '')

A typed factory for application metrics on the shared registry.

Wraps prometheus_client's Counter / Gauge / Histogram so a service declares its own business metrics — orders placed, queue depth, job duration — without repeating the registry= wiring or reaching for the global default registry. Metrics land on the same /metrics endpoint as the built-in request collectors.

Creation is de-duplicated by name, so calling a factory twice with the same name (module re-import, tests, hot reload) returns the same metric instead of raising Duplicated timeseries.

No magic: the returned objects are the real prometheus_client metrics — .inc() / .set() / .observe() / .labels(...) behave exactly as upstream documents.

Example
registry = make_prometheus_registry()
metrics = BusinessMetrics(registry, namespace="shop")
orders = metrics.counter("orders_total", "Orders placed", labelnames=["status"])
orders.labels(status="paid").inc()

Attributes:

Name Type Description
namespace str

Optional prefix applied to every metric name ("shop" → shop_orders_total).

Bind the factory to a registry.

Parameters:

Name Type Description Default
registry CollectorRegistry

The shared registry (from :func:make_prometheus_registry) so the metrics show up on the same /metrics endpoint.

required
namespace str

Optional name prefix for every metric.

''

Raises:

Type Description
ImportError

When the [prometheus] extra is missing.

counter

counter(name: str, documentation: str, *, labelnames: Sequence[str] = ()) -> Counter

Register (or fetch) a monotonically increasing counter.

Parameters:

Name Type Description Default
name str

The metric name.

required
documentation str

The HELP text.

required
labelnames Sequence[str]

Optional label names.

()

Returns:

Name Type Description
Counter Counter

The prometheus_client counter.

gauge

gauge(name: str, documentation: str, *, labelnames: Sequence[str] = ()) -> Gauge

Register (or fetch) a gauge (up/down value).

Parameters:

Name Type Description Default
name str

The metric name.

required
documentation str

The HELP text.

required
labelnames Sequence[str]

Optional label names.

()

Returns:

Name Type Description
Gauge Gauge

The prometheus_client gauge.

histogram

histogram(
    name: str,
    documentation: str,
    *,
    labelnames: Sequence[str] = (),
    buckets: Sequence[float] | None = None,
) -> Histogram

Register (or fetch) a histogram (value distribution).

Parameters:

Name Type Description Default
name str

The metric name.

required
documentation str

The HELP text.

required
labelnames Sequence[str]

Optional label names.

()
buckets Sequence[float] | None

Bucket upper bounds; defaults to prometheus_client's default buckets.

None

Returns:

Name Type Description
Histogram Histogram

The prometheus_client histogram.

DEFAULT_LATENCY_BUCKETS module-attribute

DEFAULT_LATENCY_BUCKETS: tuple[float, ...] = (
    0.005,
    0.01,
    0.025,
    0.05,
    0.1,
    0.25,
    0.5,
    1.0,
    2.5,
    5.0,
    10.0,
)
set_cookie(
    response: Response,
    name: str,
    value: str,
    *,
    max_age: int | None = None,
    path: str = "/",
    domain: str | None = None,
    http_only: bool = True,
    secure: bool = True,
    samesite: SameSite = "lax",
) -> None

Set a security-hardened cookie on response.

Parameters:

Name Type Description Default
response Response

The outgoing response.

required
name str

Cookie name.

required
value str

Cookie value (e.g. a JWT).

required
max_age int | None

Lifetime in seconds. None (or 0) emits a session cookie with no Max-Age. Mirror your token's TTL so the browser drops it when the token expires.

None
path str

Cookie path. Scope sensitive cookies (refresh tokens) to their endpoint to shrink the blast radius.

'/'
domain str | None

Cookie domain. None binds to the current host.

None
http_only bool

Block JS access (document.cookie). Default True.

True
secure bool

Require HTTPS. Default True; mandatory when samesite="none".

True
samesite SameSite

"lax" (default), "strict" or "none". Cross-site SPAs need "none" (plus secure=True).

'lax'
clear_cookie(
    response: Response,
    name: str,
    *,
    path: str = "/",
    domain: str | None = None,
    http_only: bool = True,
    secure: bool = True,
    samesite: SameSite = "lax",
) -> None

Delete a cookie previously set with :func:set_cookie.

The flags must match those used when the cookie was set, otherwise the browser ignores the deletion. Pass the same path / domain / samesite / secure / http_only you used originally.

Parameters:

Name Type Description Default
response Response

The outgoing response.

required
name str

Cookie name.

required
path str

Path the cookie was set on.

'/'
domain str | None

Domain the cookie was set on.

None
http_only bool

Must match the original flag.

True
secure bool

Must match the original flag.

True
samesite SameSite

Must match the original attribute.

'lax'

SameSite module-attribute

SameSite = Literal['lax', 'strict', 'none']

HardenedStaticFiles

HardenedStaticFiles(
    *args: object, security_headers: dict[str, str] | None = None, **kwargs: object
)

Bases: StaticFiles

StaticFiles that stamps anti-XSS headers on every response.

Defense in depth for serving user-uploaded content: if a malicious file ever lands on disk (an upload-validation bypass, a manual operator action), serving it does not become a stored-XSS primitive against any same-origin SPA.

Use exactly like :class:starlette.staticfiles.StaticFiles — app.mount("/uploads", HardenedStaticFiles(directory=...)). Pass security_headers= to override or extend the defaults (:data:DEFAULT_STATIC_SECURITY_HEADERS). Existing headers set by the parent are preserved (setdefault semantics).

Initialize.

Parameters:

Name Type Description Default
*args object

Positional arguments forwarded to StaticFiles.

()
security_headers dict[str, str] | None

Headers to stamp on every response. Defaults to :data:DEFAULT_STATIC_SECURITY_HEADERS.

None
**kwargs object

Keyword arguments forwarded to StaticFiles (directory, packages, html, check_dir …).

{}

get_response async

get_response(path: str, scope: Scope) -> Response

Delegate to StaticFiles and stamp the security headers.

Parameters:

Name Type Description Default
path str

The requested file path.

required
scope Scope

The ASGI scope.

required

Returns:

Name Type Description
Response Response

The file response with security headers applied.

DEFAULT_STATIC_SECURITY_HEADERS module-attribute

DEFAULT_STATIC_SECURITY_HEADERS: dict[str, str] = {
    "X-Content-Type-Options": "nosniff",
    "Content-Security-Policy": "default-src 'none'; sandbox",
    "Cross-Origin-Resource-Policy": "same-site",
}

Headers stamped on every response that serves a stored file.

  • X-Content-Type-Options: nosniff — browsers stop guessing the MIME from the bytes, so a polyglot file with a benign extension (HTML+JS uploaded as .jpg) is not rendered as HTML on retrieval.
  • Content-Security-Policy: default-src 'none'; sandbox — even if a browser renders the file, embedded scripts cannot execute and the sandbox blocks forms, top-level navigation and same-origin access.
  • Cross-Origin-Resource-Policy: same-site — bounds the file's readability to documents on the same site.

make_spa_router

make_spa_router(
    dist_dir: str | Path,
    *,
    index_file: str = "index.html",
    assets_dir: str = "assets",
    excluded_prefixes: tuple[str, ...] = DEFAULT_EXCLUDED_PREFIXES,
    asset_cache_control: str = DEFAULT_ASSET_CACHE_CONTROL,
    document_cache_control: str = DEFAULT_DOCUMENT_CACHE_CONTROL,
    security_headers: dict[str, str] | None = None,
    allow_blocking_headers: bool = False,
) -> APIRouter

Build a router that serves a compiled SPA with a client-side fallback.

Include it last, after every API router, because it claims a catch-all GET /{path:path} route. FastAPI matches in registration order, so anything mounted afterwards becomes unreachable::

from fastapi import FastAPI
from tempest_fastapi_sdk import make_spa_router

app = FastAPI()
app.include_router(users_router, prefix="/api/users")
app.include_router(make_spa_router("web/dist"))

Parameters:

Name Type Description Default
dist_dir str | Path

The build output directory — Vite's dist. Must contain index_file.

required
index_file str

The entry document served on fallback.

'index.html'
assets_dir str

Sub-directory of hashed assets, mounted with the immutable cache policy. Missing directories are tolerated, so a build that emits everything at the root still works.

'assets'
excluded_prefixes tuple[str, ...]

Paths the fallback refuses to answer, so API 404s stay JSON. Defaults to :data:DEFAULT_EXCLUDED_PREFIXES.

DEFAULT_EXCLUDED_PREFIXES
asset_cache_control str

Cache-Control for hashed assets.

DEFAULT_ASSET_CACHE_CONTROL
document_cache_control str

Cache-Control for index_file.

DEFAULT_DOCUMENT_CACHE_CONTROL
allow_blocking_headers bool

Skip the check that refuses a security_headers policy which would block the SPA's own bundle. security_headers stays a raw override — this parameter is what keeps it one — but the override has to be deliberate, because the failure it causes is a blank page whose only symptom is in the browser console.

False
security_headers dict[str, str] | None

Headers stamped on the document and on every asset. Defaults to :data:DEFAULT_SPA_SECURITY_HEADERS — the application policy. Passing :data:~tempest_fastapi_sdk.api.static.DEFAULT_STATIC_SECURITY_HEADERS here serves a blank page: it is the policy for untrusted files, and it blocks the SPA's own bundle.

None

Returns:

Name Type Description
APIRouter APIRouter

A router serving the assets and the SPA fallback.

Raises:

Type Description
FileNotFoundError

When dist_dir or its index_file is missing. Failing at wiring time is deliberate: the alternative is a service that boots fine and answers every page with a 404, which usually gets discovered in staging.

ValueError

When security_headers carries a policy that would block the SPA's own bundle — the shape DEFAULT_STATIC_SECURITY_HEADERS has — and allow_blocking_headers is False. Same reasoning as the missing-directory case: a blank page with the cause in the browser console is worse than a refusal at wiring time.

DEFAULT_ASSET_CACHE_CONTROL module-attribute

DEFAULT_ASSET_CACHE_CONTROL: str = 'public, max-age=31536000, immutable'

Cache policy for content-hashed build assets.

Vite names every emitted asset with a content hash, so a changed file is a changed URL. That makes an effectively permanent cache safe, and it is what keeps a returning visitor from re-downloading the bundle.

DEFAULT_DOCUMENT_CACHE_CONTROL module-attribute

DEFAULT_DOCUMENT_CACHE_CONTROL: str = 'no-store, must-revalidate'

Cache policy for index.html.

The entry document is the only file whose URL is stable across deploys, so caching it is what pins a browser to a stale bundle. It must be revalidated on every navigation.

DEFAULT_EXCLUDED_PREFIXES module-attribute

DEFAULT_EXCLUDED_PREFIXES: tuple[str, ...] = (
    "/api",
    "/docs",
    "/redoc",
    "/openapi.json",
    "/health",
    "/metrics",
    "/logs",
    "/admin",
    "/auth",
)

Path prefixes the SPA fallback must never answer.

Everything the SDK's own routers mount, plus /api. A request under these falls through to the real route — or to a JSON 404 — instead of being handed an HTML document.

DEFAULT_SPA_CONTENT_SECURITY_POLICY module-attribute

DEFAULT_SPA_CONTENT_SECURITY_POLICY: str = "; ".join(
    (
        "default-src 'self'",
        "script-src 'self'",
        "style-src 'self' 'unsafe-inline'",
        "img-src 'self' data:",
        "font-src 'self' data:",
        "connect-src 'self'",
        "form-action 'self'",
        "base-uri 'self'",
        "object-src 'none'",
        "frame-ancestors 'none'",
    )
)

Content Security Policy for an application served from its own origin.

Deliberately not :data:~tempest_fastapi_sdk.api.static.DEFAULT_STATIC_SECURITY_HEADERS. That one exists for a file nobody trusts — an upload, an attachment — and blocks execution by design: default-src 'none'; sandbox. Pointed at a compiled SPA it blocks the page's own bundle and stylesheet, and the sandbox blocks script execution outright, so the browser renders a blank document. Measured before the fix, on a two-file build:

document CSP: default-src 'none'; sandbox
Loading the script '/assets/app.js' violates ... "default-src 'none'"
Blocked script execution ... the document's frame is sandboxed

This policy is the application counterpart: everything from the same origin, nothing from anywhere else. object-src 'none' and frame-ancestors 'none' keep plugins and framing out; base-uri 'self' stops an injected <base> from re-pointing every relative URL.

style-src keeps 'unsafe-inline' because React — and the component libraries built on it — writes the style attribute inline, and a policy that breaks the UI is a policy that gets deleted. It is scoped to styles: script-src stays 'self', so an injected <script> or an inline handler is still refused. A caller who controls their component tree can tighten it to style-src 'self' plus style-src-attr 'unsafe-inline' and pass the result through security_headers=.

DEFAULT_SPA_SECURITY_HEADERS module-attribute

DEFAULT_SPA_SECURITY_HEADERS: dict[str, str] = {
    "Content-Security-Policy": DEFAULT_SPA_CONTENT_SECURITY_POLICY,
    "X-Content-Type-Options": "nosniff",
    "X-Frame-Options": "DENY",
    "Referrer-Policy": "strict-origin-when-cross-origin",
    "Cross-Origin-Resource-Policy": "same-origin",
}

Headers stamped on SPA responses when the caller passes none.

The default for :func:make_spa_router, which serves an application — not the static default, which serves files an application must not trust.

WebhookSender

WebhookSender(
    http_client: AsyncClient,
    *,
    signer: WebhookSignatureVerifier | None = None,
    max_attempts: int = 3,
    backoff_base: float = 0.5,
    timeout: float = 10.0,
    event_header: str = "X-Webhook-Event",
    id_header: str = "X-Webhook-Id",
    timestamp_header: str = "X-Webhook-Timestamp",
)

Sign and deliver outbound webhooks with bounded retries.

The counterpart to :class:WebhookSignatureVerifier: it POSTs a JSON event to a subscriber URL, signs the exact body with the same verifier instance (so the receiver validates it with that verifier), and retries transient failures (connection errors, 5xx, 429) with exponential backoff. Client errors (other 4xx) are not retried — they won't succeed on repeat.

The HTTP client is injected (an httpx.AsyncClient), matching the SDK's other outbound helpers — the caller owns its lifecycle, pooling and base config.

Example
verifier = WebhookSignatureVerifier(secret, prefix="sha256=")
sender = WebhookSender(http_client, signer=verifier)
result = await sender.send(
    "https://sub.example.com/hooks",
    event="order.paid",
    payload={"id": str(order.id), "total": 4200},
)
if not result.delivered:
    ...  # enqueue for later / alert

Initialize the sender.

Parameters:

Name Type Description Default
http_client AsyncClient

The injected async client used for every POST.

required
signer WebhookSignatureVerifier | None

When given, its expected(body) HMAC (with its prefix) is written to its header_name so the receiver can verify with the same instance. None sends unsigned.

None
max_attempts int

Total POST attempts before giving up (>= 1). Defaults to 3.

3
backoff_base float

Base seconds for exponential backoff (backoff_base * 2**(attempt-1)). Defaults to 0.5.

0.5
timeout float

Per-request timeout in seconds.

10.0
event_header str

Header carrying the event type.

'X-Webhook-Event'
id_header str

Header carrying the unique delivery id.

'X-Webhook-Id'
timestamp_header str

Header carrying the unix timestamp.

'X-Webhook-Timestamp'

send async

send(
    url: str, *, event: str, payload: object, headers: Mapping[str, str] | None = None
) -> WebhookDelivery

Deliver one signed webhook, retrying transient failures.

Only 5xx and 429 are retried. Another 4xx describes a request the endpoint will reject identically next time, so retrying it only delays the failure. A network-level error — no response at all — is always transient and always retried.

Parameters:

Name Type Description Default
url str

The subscriber URL.

required
event str

The event type (sent in the event header).

required
payload object

JSON-serializable body (default=str covers UUID/Decimal/datetime).

required
headers Mapping[str, str] | None

Extra headers merged in (they do not override the signature/metadata headers).

None

Returns:

Name Type Description
WebhookDelivery WebhookDelivery

The outcome — delivered plus the last

WebhookDelivery

status, attempt count and error.

send_many async

send_many(deliveries: list[tuple[str, Any]], *, event: str) -> list[WebhookDelivery]

Deliver the same event to many URLs concurrently.

Parameters:

Name Type Description Default
deliveries list[tuple[str, Any]]

(url, payload) pairs.

required
event str

The event type applied to every delivery.

required

Returns:

Type Description
list[WebhookDelivery]

list[WebhookDelivery]: One result per input, in order.

WebhookDelivery dataclass

WebhookDelivery(
    url: str,
    event: str,
    delivered: bool,
    status_code: int | None,
    attempts: int,
    delivery_id: str,
    error: str | None = None,
)

The outcome of one outbound webhook delivery attempt sequence.

Attributes:

Name Type Description
url str

The destination URL.

event str

The event type sent.

delivered bool

Whether a 2xx was received.

status_code int | None

The last HTTP status, or None when every attempt failed before a response (network error).

attempts int

How many POSTs were made.

error str | None

The last error message when not delivered.

delivery_id str

The unique id sent in the id header.

setup_tracing

setup_tracing(
    app: FastAPI,
    *,
    service_name: str,
    otlp_endpoint: str | None = None,
    sqlalchemy_engine: Engine | AsyncEngine | None = None,
    instrument_httpx: bool = True,
    sample_ratio: float = 1.0,
    resource_attributes: dict[str, str] | None = None,
    insecure: bool = True,
) -> TracerProvider

Install OpenTelemetry tracing and auto-instrument the app.

Call it at module level, right after the FastAPI instance is built (or inside the create_app factory) — never from the lifespan. Request spans come from wrapping the app's middleware stack, and Starlette builds that stack on the first ASGI event it receives, which is the lifespan startup itself. A call from inside the lifespan therefore finds the stack already built, and the OpenTelemetry FastAPI instrumentation never wraps it; this function detects that case and emits a :class:RuntimeWarning instead of failing silently. Since FastAPI 0.142, such an app is still traced, by FastAPI's own telemetry: a SERVER span under the instrumentation scope "fastapi" with fastapi.dependencies / fastapi.endpoint / fastapi.serialization children and the newer semantic-convention attributes (http.request.method, url.path) — not the spans this function attaches. When the instrumentation does wrap the app, FastAPI turns its own tracing off for it, so a request is never traced twice.

The database engine of :class:~tempest_fastapi_sdk.db.connection.AsyncDatabaseManager only exists after connect(), which normally runs in the lifespan. Leave sqlalchemy_engine out here and call :func:instrument_sqlalchemy_engine from the lifespan once the engine is connected.

Parameters:

Name Type Description Default
app FastAPI

The application to instrument for incoming requests.

required
service_name str

Logical service name attached to every span (service.name resource attribute) — this is how the service shows up in Jaeger / Tempo / Honeycomb.

required
otlp_endpoint str | None

OTLP/gRPC collector endpoint (e.g. "http://otel-collector:4317"). When None, a console span exporter is installed instead — handy for local debugging without a collector.

None
sqlalchemy_engine Engine | AsyncEngine | None

When given, instrument this engine so every query becomes a span. Only useful for an engine that already exists at module level; for the AsyncDatabaseManager engine use :func:instrument_sqlalchemy_engine after connect(). Silently skipped if opentelemetry-instrumentation-sqlalchemy is absent.

None
instrument_httpx bool

When True (default), instrument outbound httpx calls so they appear as child spans. Silently skipped if the httpx instrumentor is absent.

True
sample_ratio float

Head-based sampling ratio in [0, 1]. 1.0 traces every request; 0.1 traces ~10%.

1.0
resource_attributes dict[str, str] | None

Extra resource attributes merged onto every span (e.g. {"deployment.environment": "prod"}).

None
insecure bool

Whether the OTLP gRPC channel is plaintext. Defaults to True (typical for an in-cluster collector). Ignored when otlp_endpoint is None.

True

Returns:

Name Type Description
TracerProvider TracerProvider

The installed (or already-installed) global

TracerProvider

tracer provider, so callers can register custom span

TracerProvider

processors.

Raises:

Type Description
ImportError

If the [otel] extra is not installed.

ValueError

If sample_ratio is outside [0, 1].

Warns:

Type Description
RuntimeWarning

When app has already built its middleware stack (the call came from the lifespan or after the first request), so the instrumentation is not attached and requests are traced by FastAPI's own telemetry instead.

Notes

When a TracerProvider is already installed — setup_tracing ran twice, or the host wired its own — it is reused rather than replaced: the FastAPI instrumentation is attached to this app and sqlalchemy_engine, when given, is instrumented; the httpx instrumentation is left as the first call set it.

instrument_sqlalchemy_engine

instrument_sqlalchemy_engine(engine: Engine | AsyncEngine) -> None

Instrument a SQLAlchemy engine created after setup_tracing.

The engine of :class:~tempest_fastapi_sdk.db.connection.AsyncDatabaseManager only exists once connect() ran, usually inside the lifespan, while setup_tracing has to run before the lifespan. Call this from the lifespan right after connect(); queries then become child spans of the request span, bound to the global tracer provider that setup_tracing installed.

The SQLAlchemy instrumentor is a process-wide singleton, so this traces one engine per process: a second call (for another engine, or after setup_tracing(..., sqlalchemy_engine=...)) only logs Attempting to instrument while already instrumented, and the second engine's statements produce no span.

Parameters:

Name Type Description Default
engine Engine | AsyncEngine

The engine to instrument. An AsyncEngine is unwrapped to its sync_engine, which is what the instrumentor hooks into.

required

Raises:

Type Description
ImportError

If opentelemetry-instrumentation-sqlalchemy (shipped by the [otel] extra) is not installed. Unlike the best-effort path inside setup_tracing, an explicit call does not degrade silently.

make_bearer_token_dependency

make_bearer_token_dependency(
    tokens: JWTUtils | Callable[[Request], JWTUtils],
    *,
    soft: bool = False,
    bearer_scheme: HTTPBearer | None = None,
    cookie_name: str | None = None,
    query_param: str | None = None,
    accepted_typ: Collection[str] = (ACCESS_TOKEN_TYPE,),
    strict: bool = False,
    legacy_claims: Collection[str] = (),
    error_message: str = MISSING_TOKEN_MESSAGE,
) -> Callable[..., Coroutine[Any, Any, dict[str, Any] | None]]

Build a FastAPI dependency that decodes a JWT from header/cookie/query.

Returns the decoded claims dict so the caller can wire its own get_current_user on top, combining the decoded subject with the project's session / repository conventions.

Token lookup order, first hit wins:

  1. Authorization: Bearer <jwt> header.
  2. The cookie_name cookie, when set.
  3. The query_param query-string value, when set.

The header/cookie seam is what lets the same dependency serve both bearer clients and the cookie delivery mode of :func:tempest_fastapi_sdk.make_auth_router.

query_param exists for cookieless clients that cannot set an Authorization header — chiefly the browser EventSource used for SSE, whose constructor accepts neither headers nor a request body. Prefer a session cookie (withCredentials) whenever the client shares the API's origin; reach for the query string only when cross-origin or a raw EventSource leaves no other channel.

.. warning:: A token in the query string leaks into access logs, the browser history and any Referer header. Only enable query_param with short-lived access tokens (never a refresh token), always over TLS, and scrub the value from your log format.

Parameters:

Name Type Description Default
tokens JWTUtils | Callable[[Request], JWTUtils]

The JWT helper used to verify the token, or a factory called with each request that returns it — for a helper built after import, in create_app.

required
soft bool

When True, return None on missing or invalid tokens instead of raising. Useful for endpoints that work both authenticated and anonymous.

False
bearer_scheme HTTPBearer | None

Override the bearer scheme. Defaults to HTTPBearer(auto_error=False).

None
cookie_name str | None

When set, fall back to this cookie for the access token if the Authorization header is absent. None (default) skips the cookie lookup.

None
query_param str | None

When set, fall back to this query-string parameter (e.g. "access_token") if header and cookie are both absent. None (default) skips it. See the security warning above before enabling.

None
accepted_typ Collection[str]

Token types this dependency accepts, matched against the typ claim. Defaults to (ACCESS_TOKEN_TYPE,) — a refresh token or the MFA-pending token from step one of a two-step login is rejected, even though both are validly signed with the same secret. Widen it only for a route that deliberately takes another kind of token.

(ACCESS_TOKEN_TYPE,)
strict bool

How to treat a token that carries no recognizable type marker. False (default) accepts it — the compatibility window that keeps sessions minted before the typ claim existed from being logged out on upgrade. True refuses it. A service whose legacy tokens declared their type under a claim of their own (type, token_type) has neither typ nor an SDK fallback marker on any of them, so under the default every one of those refresh tokens authorizes any route for the length of its TTL. Such a service wants strict=True plus legacy_claims, and until v0.274.0 could only get there by not using this factory.

False
legacy_claims Collection[str]

Extra claim names to read the token type from when typ is absent, in order. Pair with strict=True: the claims classify the old tokens, and strict refuses whatever stays unclassified. See :func:~tempest_fastapi_sdk.token_type_allowed.

()
error_message str

Message attached to the raised :class:UnauthorizedException when soft is False.

MISSING_TOKEN_MESSAGE

Returns:

Type Description
Callable[..., Coroutine[Any, Any, dict[str, Any] | None]]

Callable[..., Coroutine[Any, Any, dict[str, Any] | None]]: An

Callable[..., Coroutine[Any, Any, dict[str, Any] | None]]

async FastAPI dependency yielding the decoded claims dict

Callable[..., Coroutine[Any, Any, dict[str, Any] | None]]

(or None when soft=True and the token is absent /

Callable[..., Coroutine[Any, Any, dict[str, Any] | None]]

invalid).

make_jwt_user_dependency

make_jwt_user_dependency(
    tokens: JWTUtils | Callable[[Request], JWTUtils],
    user_loader: Callable[..., Coroutine[Any, Any, Any]],
    *,
    soft: bool = False,
    bearer_scheme: HTTPBearer | None = None,
    cookie_name: str | None = None,
    query_param: str | None = None,
    accepted_typ: Collection[str] = (ACCESS_TOKEN_TYPE,),
    strict: bool = False,
    legacy_claims: Collection[str] = (),
    subject_claim: str = "sub",
    error_message: str = MISSING_TOKEN_MESSAGE,
    session_dependency: Callable[..., Any] | None = None,
) -> Callable[..., Coroutine[Any, Any, Any]]

Build a FastAPI dependency that returns the authenticated user.

The dependency:

  1. Reads the JWT from Authorization: Bearer (or, when cookie_name is set, falls back to that cookie).
  2. Decodes / verifies the JWT with tokens.
  3. Pulls the user identifier from the configured subject_claim.
  4. Awaits user_loader(<id>) and returns the user it yields.

user_loader is the single seam where the service maps payload[subject_claim] to an actual user. Returning None from it refuses the request: with soft=False that is an :class:UnauthorizedException, the same answer an absent subject gets. In soft mode it stays None, which is what the flag is for.

Session sharing. When session_dependency is given, the returned dependency declares it as a sub-dependency and calls the two-argument user_loader(subject, session) with the request-scoped session. Because FastAPI caches a sub-dependency by its callable within a single request, the authenticated user is loaded on the same session the request's repositories use — so the instance stays attached and can be mutated / refreshed without the InvalidRequestError: Instance is not persistent within this Session that a per-loader private session would cause. Pass the exact callable your repositories depend on (e.g. db.session_dependency); a different wrapper would resolve to a second, distinct session and defeat the sharing.

When session_dependency is None the loader is called with a single argument (user_loader(subject)) and owns its own session lifecycle — useful outside a request scope, but it yields a detached instance.

Parameters:

Name Type Description Default
tokens JWTUtils | Callable[[Request], JWTUtils]

The JWT helper used to verify the token, or a factory called with each request that returns it — for a helper built after import, in create_app.

required
user_loader Callable[..., Coroutine[Any, Any, Any]]

Async callable that receives the subject (typically the user id as a string) and returns the loaded user. When session_dependency is set it is called as user_loader(subject, session). Returning None refuses the request when soft is False (401) and yields None when it is True; that is the answer for a subject that resolves to no account. Raising :class:UnauthorizedException from inside the loader also works and lets you choose the message. Raising :class:NotFoundException reaches the client as 404 on a URL that exists, which a front end does not read as "session over" — return None instead.

required
soft bool

When True, return None instead of raising on a missing or invalid token, and when the loader declines the subject.

False
bearer_scheme HTTPBearer | None

Override the bearer scheme.

None
cookie_name str | None

When set, fall back to this cookie for the access token when the Authorization header is absent.

None
query_param str | None

When set, fall back to this query-string parameter for the access token (cookieless clients such as EventSource). See the security warning on :func:make_bearer_token_dependency before enabling.

None
accepted_typ Collection[str]

Token types accepted, matched against the typ claim. Defaults to access-only, so the refresh token and the MFA-pending token cannot stand in for an access token. See :func:make_bearer_token_dependency.

(ACCESS_TOKEN_TYPE,)
strict bool

How to treat a token that carries no recognizable type marker. False (default) accepts it — the compatibility window that keeps sessions minted before the typ claim existed from being logged out on upgrade. True refuses it. A service whose legacy tokens declared their type under a claim of their own (type, token_type) has neither typ nor an SDK fallback marker on any of them, so under the default every one of those refresh tokens authorizes any route for the length of its TTL. Such a service wants strict=True plus legacy_claims, and until v0.274.0 could only get there by not using this factory.

False
legacy_claims Collection[str]

Extra claim names to read the token type from when typ is absent, in order. Pair with strict=True: the claims classify the old tokens, and strict refuses whatever stays unclassified. See :func:~tempest_fastapi_sdk.token_type_allowed.

()
subject_claim str

Which JWT claim carries the user id. Defaults to "sub".

'sub'
error_message str

Message attached to the raised :class:UnauthorizedException when soft is False.

MISSING_TOKEN_MESSAGE
session_dependency Callable[..., Any] | None

The request-scoped session provider to share with repositories. When set, user_loader is called with (subject, session).

None

Returns:

Type Description
Callable[..., Coroutine[Any, Any, Any]]

Callable[..., Coroutine[Any, Any, Any]]: An async FastAPI

Callable[..., Coroutine[Any, Any, Any]]

dependency yielding the user (or None in soft mode).

make_permission_dependency

make_permission_dependency(
    tokens: JWTUtils | Callable[[Request], JWTUtils],
    required_permissions: Iterable[str],
    *,
    permissions_claim: str = "permissions",
    require_all: bool = True,
    bearer_scheme: HTTPBearer | None = None,
    unauthorized_message: str = MISSING_TOKEN_MESSAGE,
    forbidden_message: str = "Insufficient permissions for this operation",
) -> Callable[..., Coroutine[Any, Any, None]]

Build a FastAPI dependency that gates a route by permission claims.

Same shape as :func:make_role_dependency but defaults to require_all=True since permissions are usually fine-grained capabilities (orders:write, users:delete) where every listed permission must be granted.

Parameters:

Name Type Description Default
tokens JWTUtils | Callable[[Request], JWTUtils]

The JWT helper used to verify the token, or a factory called with each request that returns it — for a helper built after import, in create_app.

required
required_permissions Iterable[str]

Permissions the route requires.

required
permissions_claim str

JWT claim carrying the permissions. Defaults to "permissions".

'permissions'
require_all bool

When True (default), every listed permission must be present.

True
bearer_scheme HTTPBearer | None

Override the bearer scheme.

None
unauthorized_message str

Message attached to the :class:UnauthorizedException.

MISSING_TOKEN_MESSAGE
forbidden_message str

Message attached to the :class:ForbiddenException.

'Insufficient permissions for this operation'

Returns:

Type Description
Callable[..., Coroutine[Any, Any, None]]

Callable[..., Coroutine[Any, Any, None]]: An async FastAPI

Callable[..., Coroutine[Any, Any, None]]

dependency.

make_role_dependency

make_role_dependency(
    tokens: JWTUtils | Callable[[Request], JWTUtils],
    required_roles: Iterable[str],
    *,
    roles_claim: str = "roles",
    require_all: bool = False,
    bearer_scheme: HTTPBearer | None = None,
    unauthorized_message: str = MISSING_TOKEN_MESSAGE,
    forbidden_message: str = "Insufficient role for this operation",
) -> Callable[..., Coroutine[Any, Any, None]]

Build a FastAPI dependency that gates a route by JWT role claims.

The dependency decodes the bearer JWT, reads the configured roles claim (a string or list of strings) and compares it against required_roles. require_all=False (default) authorizes the request when any required role is present; require_all=True requires every listed role.

Parameters:

Name Type Description Default
tokens JWTUtils | Callable[[Request], JWTUtils]

The JWT helper used to verify the token, or a factory called with each request that returns it — for a helper built after import, in create_app.

required
required_roles Iterable[str]

Roles the route accepts.

required
roles_claim str

Which JWT claim carries the roles. Defaults to "roles".

'roles'
require_all bool

When True, every role in required_roles must be present.

False
bearer_scheme HTTPBearer | None

Override the bearer scheme.

None
unauthorized_message str

Message attached to the raised :class:UnauthorizedException when the token is missing or invalid.

MISSING_TOKEN_MESSAGE
forbidden_message str

Message attached to the raised :class:ForbiddenException when the token is valid but the role requirement is not satisfied.

'Insufficient role for this operation'

Returns:

Type Description
Callable[..., Coroutine[Any, Any, None]]

Callable[..., Coroutine[Any, Any, None]]: An async FastAPI

Callable[..., Coroutine[Any, Any, None]]

dependency raising :class:UnauthorizedException /

Callable[..., Coroutine[Any, Any, None]]

class:ForbiddenException as appropriate, None on

Callable[..., Coroutine[Any, Any, None]]

success.

make_token_dependency

make_token_dependency(
    secret: str,
    *,
    header_name: str = "X-Token",
    error_message: str = "Invalid or missing token",
    allow_unauthenticated: bool = False,
) -> Callable[..., Coroutine[Any, Any, None]]

Build a FastAPI dependency that validates a shared-secret header.

The returned coroutine compares the inbound header value with secret using :func:hmac.compare_digest (constant-time).

An empty (or whitespace-only) secret raises :class:ValueError here, when the dependency is built — at import, in a typical service. It used to disable the check silently, and a TOKEN_SECRET left empty in a deployed .env turned every gated route into a public one. A local run that wants the gate off says so with allow_unauthenticated=True; with a non-empty secret that flag changes nothing.

While the check is enforced, every response of a route behind it carries Cache-Control: no-store. A response cache in front of the app (the SDK's ResponseCacheMiddleware or a proxy) answers before the route's dependencies run, so a stored copy of a gated response would be served without the token ever being checked; no-store keeps the response out of every such cache, whatever header header_name names.

Parameters:

Name Type Description Default
secret str

The shared secret to compare against.

required
header_name str

The header to read. Defaults to "X-Token".

'X-Token'
error_message str

Message attached to the raised :class:UnauthorizedException.

'Invalid or missing token'
allow_unauthenticated bool

Accept an empty secret and let every request through. For a local run nothing else reaches.

False

Returns:

Type Description
Callable[..., Coroutine[Any, Any, None]]

Callable[..., Coroutine[Any, Any, None]]: An async FastAPI

Callable[..., Coroutine[Any, Any, None]]

dependency that raises :class:UnauthorizedException on

Callable[..., Coroutine[Any, Any, None]]

mismatch and returns None on success.

Raises:

Type Description
ValueError

When secret is empty and allow_unauthenticated is False.

require_x_token async

require_x_token(
    secret: str,
    token: str,
    *,
    error_message: str = "Invalid or missing token",
    allow_unauthenticated: bool = False,
) -> None

Imperative variant of :func:make_token_dependency.

Useful when validation happens outside the FastAPI dependency pipeline (e.g. from a websocket handler or background task). Same contract for an empty secret: refused unless allow_unauthenticated=True.

Parameters:

Name Type Description Default
secret str

The shared secret.

required
token str

The token to verify.

required
error_message str

Message attached on failure.

'Invalid or missing token'
allow_unauthenticated bool

Accept an empty secret and let the call through.

False

Raises:

Type Description
ValueError

When secret is empty and allow_unauthenticated is False.

UnauthorizedException

When the tokens do not match in constant time.

describe_validation_envelope

describe_validation_envelope(app: FastAPI) -> None

Rewrite the 422 schema to the envelope the handler answers with.

FastAPI documents the 422 it generates itself as HTTPValidationError with detail as an array, and every route with a body or a parameter references that one component. Registering :func:~tempest_fastapi_sdk.make_validation_exception_handler changes the runtime shape to the SDK envelope, so leaving the schema alone would ship the documented-versus-real divergence this SDK exists to avoid — in the one response a generated client is most likely to model.

Rewriting the single shared component is enough: each route's 422 is a $ref to it. The ValidationError item loses input, which the handler deliberately never emits.

Called by :func:~tempest_fastapi_sdk.register_exception_handlers when envelope_validation_errors=True. Wraps app.openapi so the patch survives the schema being regenerated, and is idempotent.

Parameters:

Name Type Description Default
app FastAPI

The application whose schema to rewrite.

required

RAISES_ATTRIBUTE module-attribute

RAISES_ATTRIBUTE: str = '__tempest_raises__'

Attribute :func:raises sets on the endpoint it decorates.

app_exception_handler async

app_exception_handler(request: Request, exc: AppException) -> JSONResponse

Default :class:AppException handler (logs at INFO).

Thin wrapper around :func:make_app_exception_handler kept for backwards compatibility with code that imports the handler callable directly.

Parameters:

Name Type Description Default
request Request

The incoming HTTP request.

required
exc AppException

The exception raised.

required

Returns:

Name Type Description
JSONResponse JSONResponse

The serialized response.

make_validation_exception_handler

make_validation_exception_handler(
    *,
    log_level: int = INFO,
    catalog: MessageCatalog | None = None,
    default_locale: str = DEFAULT_LOCALE,
    locale_resolver: LocaleResolver | None = None,
    logger: Logger | None = None,
    envelope_builder: ErrorEnvelopeBuilder | None = None,
) -> ValidationExceptionHandler

Build the handler for FastAPI's RequestValidationError.

The 422 is the error a client sees most often and was the only one outside the SDK's envelope: FastAPI intercepts RequestValidationError in its own default handler, so it answered with pydantic's raw list and no code, and never passed through the :class:MessageCatalog a service configured.

Two things this handler changes, both measured:

  • The envelope. The response is {"detail", "code": "VALIDATION_ERROR", "details": {"errors": [...]}}, so a client parses one shape for every failure instead of two.
  • The messages. Each entry's message comes from the catalog, keyed by the pydantic error type rather than by field, so a new field on a schema is translated the day it is added. A type the catalog does not carry keeps pydantic's own msg, which is already the English sentence — so English needs no table and cannot drift from upstream.

It also stops echoing the submitted value. FastAPI's default 422 includes input for every failing field: measured, a password field that fails min_length puts the password in the response body, and SecretStr does not prevent it, because validation runs before the secret wrapper is built. details carries loc and type and never input.

Parameters:

Name Type Description Default
log_level int

Level for the log line. Defaults to :data:logging.INFO, since a 422 is normal client flow.

INFO
catalog MessageCatalog | None

Catalog used to localize each entry. None keeps pydantic's own messages.

None
default_locale str

Locale used when Accept-Language is absent or matches nothing in the catalog.

DEFAULT_LOCALE
locale_resolver LocaleResolver | None

Optional callable taking the request and returning a locale tag (or None to fall back to Accept-Language negotiation). See :func:make_locale_resolver.

None
logger Logger | None

Where this handler logs. None uses the SDK's own logger.

None
envelope_builder ErrorEnvelopeBuilder | None

Builds the response body from an :class:~tempest_fastapi_sdk.ErrorEnvelopeContext whose details carries the errors list. A builder that raises is logged and the SDK envelope is answered instead. None keeps the SDK envelope.

None

Returns:

Name Type Description
ValidationExceptionHandler ValidationExceptionHandler

An async

ValidationExceptionHandler

(request, exc) -> JSONResponse callable ready to pass to

ValidationExceptionHandler

meth:FastAPI.add_exception_handler.

ServerErrorCallback module-attribute

ServerErrorCallback = Callable[[Request, Exception], Awaitable[None]]

Async callable invoked after a 5xx response has been built.

Runs as a Starlette BackgroundTask, so it never delays or alters the response the client receives.

VALIDATION_ERROR_CODE module-attribute

VALIDATION_ERROR_CODE: str = 'VALIDATION_ERROR'

The envelope code a request-validation failure answers with.

ValidationExceptionHandler module-attribute

ValidationExceptionHandler = Callable[
    [Request, RequestValidationError], Awaitable[JSONResponse]
]

Async callable resolving a request-validation failure to a response.

LocaleResolver module-attribute

LocaleResolver = Callable[[Request], str | None]

Callable resolving the locale tag for a request, or None to fall back.

When passed to :func:~tempest_fastapi_sdk.register_exception_handlers (or to the individual make_*_exception_handler factories), a non-empty tag it returns wins over the request's Accept-Language header whenever the configured :class:~tempest_fastapi_sdk.MessageCatalog supports it. Returning None (or a blank tag, or one the catalog does not carry) falls back to header negotiation and then to default_locale.

make_locale_resolver

make_locale_resolver(
    *,
    state_attr: str | None = "locale",
    user_attr: str | None = "user",
    user_locale_attr: str = "locale",
    query_param: str | None = "lang",
    catalog: MessageCatalog | None = None,
) -> LocaleResolver

Build a :data:LocaleResolver reading request signals in order.

Follows the precedence of :func:~tempest_fastapi_sdk.resolve_locale (query parameter, then the stored preference) without being locked to the two locales the auth templates ship, so a locale merged into a :class:~tempest_fastapi_sdk.MessageCatalog works unchanged. First match wins:

  1. query_param — the query string (?lang=en-US by default; None ignores the query string).
  2. request.state.<state_attr> — a locale attached by a middleware or dependency (request.state.locale by default; None skips).
  3. request.state.<user_attr>.<user_locale_attr> — the preference stored on the authenticated user (request.state.user.locale by default, the column :class:~tempest_fastapi_sdk.LocaleColumnMixin adds; user_attr=None skips).
  4. None — the handler then negotiates Accept-Language and falls back to its default_locale.

A value that is not a string, or is blank, is skipped. When catalog is given, a signal naming a locale the catalog does not support is skipped too, so an unsupported ?lang=fr-FR still reaches request.state.locale instead of short-circuiting the chain.

Parameters:

Name Type Description Default
state_attr str | None

Attribute of request.state holding a locale string. Defaults to "locale".

'locale'
user_attr str | None

Attribute of request.state holding the user object. Defaults to "user".

'user'
user_locale_attr str

Attribute of the user object holding the locale. Defaults to "locale".

'locale'
query_param str | None

Query parameter checked first. Defaults to "lang".

'lang'
catalog MessageCatalog | None

Catalog used to skip unsupported signals instead of returning them.

None

Returns:

Name Type Description
LocaleResolver LocaleResolver

A (request) -> str | None callable ready for

LocaleResolver

func:~tempest_fastapi_sdk.register_exception_handlers.

ErrorEnvelopeContext dataclass

ErrorEnvelopeContext(
    *,
    status_code: int,
    code: str,
    detail: str,
    details: dict[str, Any],
    field: str | None,
    request: Request,
    request_id: str | None,
    exception: Exception,
)

Everything a handler resolved about one error, before rendering.

Attributes:

Name Type Description
status_code int

The HTTP status the response carries.

code str

The machine-readable error code (NOT_FOUND, VALIDATION_ERROR, INTERNAL_SERVER_ERROR, HTTP_405...), the same value the SDK envelope puts in code.

detail str

The human-readable message, already localized when a catalog is configured.

details dict[str, Any]

The structured context the SDK envelope puts in details: AppException.details, the errors list of a 422, or the request_id of a 5xx.

field str | None

The input an :class:AppException blames, or None.

request Request

The request being answered.

request_id str | None

The request id from the contextvar or the X-Request-ID header, when there is one.

exception Exception

The exception being answered.

ErrorEnvelopeBuilder module-attribute

ErrorEnvelopeBuilder = Callable[[ErrorEnvelopeContext], Mapping[str, object]]

Callable turning an :class:ErrorEnvelopeContext into the response body.

Passed as envelope_builder= to :func:~tempest_fastapi_sdk.register_exception_handlers. The returned mapping goes through jsonable_encoder, so UUID and datetime values serialize. It must not raise: a builder that does is logged and the response falls back to the SDK envelope, with the same status.

CSRF_COOKIE_NAME: str = 'csrf_token'

Default cookie holding the CSRF token.

CSRF_HEADER_NAME module-attribute

CSRF_HEADER_NAME: str = 'X-CSRF-Token'

Default header the client echoes the cookie value into.

CachedResponse dataclass

CachedResponse(
    status_code: int,
    headers: list[tuple[str, str]],
    body: bytes,
    media_type: str | None,
    fingerprint: str = "",
)

Serialized response stored under an idempotency key.

Attributes:

Name Type Description
status_code int

HTTP status of the original response.

headers list[tuple[str, str]]

Response headers as a flat list of (name, value) pairs (preserving duplicates for Set-Cookie).

body bytes

Raw response body bytes.

media_type str | None

Original Content-Type.

fingerprint str

Digest of the request that produced the response (method, path, query and body). Empty for entries that are not bound to a request, such as the response cache's.

IdempotencyStore

Bases: Protocol

Protocol every idempotency cache implements.

get async

get(key: str) -> CachedResponse | None

Return the cached response for key or None when missing.

Parameters:

Name Type Description Default
key str

The idempotency key from the request header.

required

Returns:

Type Description
CachedResponse | None

CachedResponse | None: The stored response, or None on a miss.

set async

set(key: str, response: CachedResponse, *, ttl_seconds: int) -> None

Store response under key with a TTL.

Parameters:

Name Type Description Default
key str

The idempotency key from the request header.

required
response CachedResponse

The response to remember for replays.

required
ttl_seconds int

How long the entry stays replayable.

required

MemoryResponseCacheStore

MemoryResponseCacheStore()

In-process :class:ResponseCacheStore (one worker only).

Fine for a single process / tests; use :class:RedisResponseCacheStore to share a cache across workers.

Initialize the empty store.

get async

get(key: str) -> CachedResponse | None

Return the live cached response for key (expired entries drop).

Parameters:

Name Type Description Default
key str

Cache key derived from method, path and the vary headers.

required

Returns:

Type Description
CachedResponse | None

CachedResponse | None: The stored response, or None on a miss.

set async

set(key: str, response: CachedResponse, *, ttl_seconds: int) -> None

Store response under key with a monotonic-clock expiry.

Parameters:

Name Type Description Default
key str

Cache key derived from method, path and the vary headers.

required
response CachedResponse

The response to store.

required
ttl_seconds int

How long the entry stays fresh.

required

RedisResponseCacheStore

RedisResponseCacheStore(client: _RedisLike, *, prefix: str = 'respcache:')

Redis-backed :class:ResponseCacheStore, shared across workers.

Serializes each response as JSON (body base64-encoded), the same wire shape the idempotency store uses.

Configure the store.

Parameters:

Name Type Description Default
client _RedisLike

A raw async Redis client (get / set).

required
prefix str

Key prefix namespacing this cache.

'respcache:'

get async

get(key: str) -> CachedResponse | None

Return the cached response for key, or None on miss.

Parameters:

Name Type Description Default
key str

Cache key derived from method, path and the vary headers.

required

Returns:

Type Description
CachedResponse | None

CachedResponse | None: The stored response, or None on a miss.

set async

set(key: str, response: CachedResponse, *, ttl_seconds: int) -> None

Store response under key with ex=ttl_seconds.

Parameters:

Name Type Description Default
key str

Cache key derived from method, path and the vary headers.

required
response CachedResponse

The response to store.

required
ttl_seconds int

How long the entry stays fresh.

required

ResponseCacheMiddleware

ResponseCacheMiddleware(
    app: ASGIApp,
    *,
    store: ResponseCacheStore | None = None,
    ttl_seconds: int = 60,
    max_age: int | None = None,
    cache_control: str | None = None,
    methods: tuple[str, ...] = ("GET", "HEAD"),
    cacheable_status: tuple[int, ...] = (200,),
    vary: tuple[str, ...] = (),
    exempt_paths: tuple[str, ...] = (),
    exempt_prefixes: tuple[str, ...] = (),
    cacheable: Callable[[Request], bool] | None = None,
    cache_credentialed: bool = False,
    credential_headers: tuple[str, ...] = DEFAULT_CREDENTIAL_HEADERS,
)

Bases: BaseHTTPMiddleware

Add ETag / conditional-GET and optional server-side response caching.

Example:

>>> app.add_middleware(ResponseCacheMiddleware, ttl_seconds=30)
>>> app.add_middleware(
...     ResponseCacheMiddleware,
...     store=RedisResponseCacheStore(redis),
...     ttl_seconds=60,
...     vary=("Accept-Encoding",),
... )

Configure the middleware.

Parameters:

Name Type Description Default
app ASGIApp

The wrapped application.

required
store ResponseCacheStore | None

When set, full responses are cached server-side and served without re-running the handler. When None, only ETag / 304 handling is applied.

None
ttl_seconds int

Server-cache TTL and the default max-age.

60
max_age int | None

Cache-Control: max-age value; defaults to ttl_seconds.

None
cache_control str | None

Explicit Cache-Control value; when set it overrides the max_age-derived one. The default is private, max-age=<max_age> — private because the middleware cannot know whether a given route's body is personalized, and a wrong public there means a shared proxy serves one user's response to another. Set it to "public, max-age=…" deliberately, on a router that only serves shared content.

None
methods tuple[str, ...]

HTTP methods eligible for caching.

('GET', 'HEAD')
cacheable_status tuple[int, ...]

Status codes eligible for caching (default: only 200).

(200,)
vary tuple[str, ...]

Request headers folded into the cache key and emitted as Vary.

()
exempt_paths tuple[str, ...]

Exact paths that bypass the middleware.

()
exempt_prefixes tuple[str, ...]

Path prefixes that bypass the middleware. ("/api/sse",) covers /api/sse/stream. Matching is textual, so it also covers /api/sse-legacy.

()
cacheable Callable[[Request], bool] | None

Optional predicate; when it returns False the request bypasses caching.

None
cache_credentialed bool

Whether a request carrying any of credential_headers may use the shared store. False (default) makes such requests bypass it — their response belongs to one caller, and the key does not identify callers. True folds a digest of those headers into the key, so each set of credentials gets its own entry; only turn it on once you have checked that the cached routes do not embed a second identity (a tenant header, a path-independent session).

False
credential_headers tuple[str, ...]

Request headers whose presence marks a request as credentialed. The default covers Authorization, Cookie, X-Token (the header of make_token_dependency) and X-API-Key. Add the header your own auth reads when it is none of those: a request authenticated through an unlisted header looks anonymous, and its response would be stored under the shared key and served to the next caller before the auth dependency runs.

DEFAULT_CREDENTIAL_HEADERS

Raises:

Type Description
ValueError

When ttl_seconds is not positive, or when credential_headers is empty.

dispatch async

dispatch(
    request: Request, call_next: Callable[[Request], Awaitable[Response]]
) -> Response

Serve from cache / 304 when possible, else cache the response.

Parameters:

Name Type Description Default
request Request

The inbound request.

required
call_next Callable[[Request], Awaitable[Response]]

The next handler in the middleware chain.

required

Returns:

Name Type Description
Response Response

A 304 when the ETag matches, the cached body on a hit, otherwise the handler's own response.

ResponseCacheStore

Bases: Protocol

Where full cached responses live (get/set with TTL).

get async

get(key: str) -> CachedResponse | None

Return the cached response for key, or None.

Parameters:

Name Type Description Default
key str

The cache key.

required

Returns:

Type Description
CachedResponse | None

CachedResponse | None: The stored response, or None on miss.

set async

set(key: str, response: CachedResponse, *, ttl_seconds: int) -> None

Store response under key for ttl_seconds.

Parameters:

Name Type Description Default
key str

The cache key.

required
response CachedResponse

The response to cache.

required
ttl_seconds int

Time-to-live in seconds.

required

OAuthAudienceVerifier

Bases: Protocol

The extra call the token-in-hand endpoint makes on a provider.

Deliberately not part of :class:OAuthClient: the redirect flow exchanges a code this service asked for, so it already knows the token is its own and needs none of this. Only POST /auth/oauth/{provider}/token — where the token is handed to us by whoever is calling — has to ask who the token was minted for.

Keeping it separate also means a client written against an older SDK still satisfies :class:OAuthClient; it just cannot be used with the token-in-hand route, which refuses with :class:~tempest_fastapi_sdk.exceptions.oauth.OAuthAudienceUnverifiableException instead of trusting it.

verify_token_audience async

verify_token_audience(tokens: OAuthTokens) -> None

Assert the token was issued to this application.

Parameters:

Name Type Description Default
tokens OAuthTokens

The bundle the caller presented.

required

Raises:

Type Description
OAuthTokenAudienceMismatchException

When the provider says the token belongs to another client_id.

OAuthTokenRejectedException

When the provider rejects the token outright.

HealthCheck module-attribute

HealthCheck = Callable[[], Awaitable[bool]]

Type alias for async health-check callables.

Each callable returns True when the dependency is healthy and False (or raises) otherwise. Exceptions and timeouts are caught by the readiness endpoint and translated to False.

is_log_dir_unset

is_log_dir_unset(log_dir: str | Path) -> bool

Return whether log_dir is the empty string that disables files.

configure_logging(log_dir="") (and LOG_DIR="") means "no file logging". Handed to :class:~pathlib.Path, the same empty string becomes ., the current working directory — so a reader would list whatever *.log sits there, and a clear would truncate it. Only a str can be empty this way; a Path was built deliberately.

Parameters:

Name Type Description Default
log_dir str | Path

The configured directory.

required

Returns:

Name Type Description
bool bool

True for an empty or whitespace-only string.

LogSource module-attribute

LogSource = Literal['all', 'debug', 'info', 'warning', 'error', 'critical', '500']

Selectable log source for the /logs endpoint.

"all" merges every per-level file (excluding 500.log to avoid duplicating error.log rows); the rest map to a single file.

rotated_log_files

rotated_log_files(path: str | Path) -> list[Path]

List the rotated backups of one log file, newest first.

:func:~tempest_fastapi_sdk.configure_logging rotates either by size (info.log.1 is the newest backup, higher numbers are older) or by time (info.log.2026-10-20, info.log.2026-10-20_13 for hourly rotation; later dates are newer). Both shapes are listed, so a reader sees the same history whichever mode wrote it — and a directory that switched modes keeps showing the files the old mode left behind.

Order is by modification time, newest first, which is correct across both naming schemes; files with the same modification time fall back to the scheme's own order (lower number first, later date first).

Parameters:

Name Type Description Default
path str | Path

The live log file (logs/info.log). It does not need to exist.

required

Returns:

Type Description
list[Path]

list[Path]: The existing backups, newest first. Empty when the

list[Path]

directory or the backups do not exist.

make_tool_spec_router

make_tool_spec_router(
    spec: SpecProvider,
    *,
    path: str = "/tool-spec",
    tag: str = "meta",
    response_model: type[Any] | None = None,
    docs_locale: str | None = None,
) -> APIRouter

Build a router that exposes a tool-spec / capabilities manifest.

The endpoint sits at the root prefix by default so it joins /health as a meta endpoint outside of /api/<domain>.

Parameters:

Name Type Description Default
spec SpecProvider

The manifest. Pass either a dict (served verbatim), a sync callable returning a dict (called on every request — useful for content that depends on settings or runtime state), or an async callable.

required
path str

Endpoint path. Defaults to "/tool-spec".

'/tool-spec'
tag str

OpenAPI tag. Defaults to "meta".

'meta'
response_model type[Any] | None

Optional Pydantic model used as the response schema for OpenAPI. The provider must return a value compatible with the model.

None
docs_locale str | None

Language of the OpenAPI summary and description text — "en-US" or "pt-BR". None (default) reads API_DOCS_LOCALE through :class:~tempest_fastapi_sdk.settings.ServerSettings, whose default is "en-US".

None

Returns:

Name Type Description
APIRouter APIRouter

A FastAPI router with a single GET route.

run_server

run_server(
    app: str | FastAPI = "src.api.app:app",
    *,
    settings: ServerSettings | None = None,
    host: str | None = None,
    port: int | None = None,
    reload: bool | None = None,
    **uvicorn_kwargs: Any,
) -> None

Run uvicorn against app using the SDK's defaults.

This is the canonical helper imported from src/server.py. It keeps the entry point a single line and centralizes the host / port / reload defaults across every service.

Resolution order for each kwarg: explicit host / port / reload argument → matching field on settings → SDK default ("127.0.0.1" / 8000 / False).

Parameters:

Name Type Description Default
app str | FastAPI

Either an import string (preferred for reload support — "src.api.app:app") or the FastAPI instance itself.

'src.api.app:app'
settings ServerSettings | None

Optional settings object; SERVER_HOST / SERVER_PORT / SERVER_RELOAD are read from it when present and not overridden.

None
host str | None

Override bind interface.

None
port int | None

Override TCP port.

None
reload bool | None

Override uvicorn auto-reload.

None
**uvicorn_kwargs Any

Forwarded verbatim to :func:uvicorn.run (workers, log_config, ssl_*, etc.).

{}

Returns:

Name Type Description
None None

Blocks until uvicorn exits.

RSAWebhookSignatureVerifier

RSAWebhookSignatureVerifier(
    public_key_pem: str | bytes,
    *,
    algorithm: str = "sha256",
    header_name: str = "x-webhook-signature",
)

Validate RSA-signed webhook payloads (OpenPix/Woovi-style).

Some providers sign each webhook with their PRIVATE key and publish a well-known PUBLIC key; the receiver verifies the asymmetric signature over the raw body. This complements :class:WebhookSignatureVerifier (symmetric HMAC) for those gateways. Uses RSASSA-PKCS1-v1_5 over a configurable hash.

Requires cryptography (ships with the [webpush] extra, or pip install cryptography); the import is deferred to first use.

Attributes:

Name Type Description
public_key_pem bytes

The PEM-encoded provider public key.

algorithm str

Hash algorithm name ("sha256" default).

header_name str

Header carrying the base64 signature.

Initialize the verifier.

Parameters:

Name Type Description Default
public_key_pem str | bytes

PEM-encoded RSA public key. Strings are encoded as UTF-8.

required
algorithm str

Hash algorithm — "sha256" (default), "sha384" or "sha512".

'sha256'
header_name str

Header carrying the base64 signature.

'x-webhook-signature'

Raises:

Type Description
ValueError

If algorithm is not a supported SHA-2 hash.

verify

verify(body: bytes, signature: str) -> bool

Verify a base64 RSA signature over body in one shot.

Parameters:

Name Type Description Default
body bytes

The raw request body, exactly as received (never re-serialized — re-encoding changes the bytes and breaks the signature).

required
signature str

The base64-encoded signature header value.

required

Returns:

Name Type Description
bool bool

True when the signature verifies against the configured public key, False on any failure (bad signature, malformed base64, unparseable key).

Raises:

Type Description
ImportError

If cryptography is not installed.

dependency

dependency(
    *, error_message: str = "Invalid webhook signature"
) -> Callable[..., Coroutine[Any, Any, bytes]]

Build a FastAPI dependency that validates the inbound webhook.

Reads the raw body, verifies the RSA signature header, and returns the body bytes so the route handler can re-parse it without re-reading the stream.

Parameters:

Name Type Description Default
error_message str

Message attached to the raised :class:UnauthorizedException when verification fails.

'Invalid webhook signature'

Returns:

Type Description
Callable[..., Coroutine[Any, Any, bytes]]

Callable[..., Coroutine[Any, Any, bytes]]: An async FastAPI

Callable[..., Coroutine[Any, Any, bytes]]

dependency yielding the raw body on success and raising

Callable[..., Coroutine[Any, Any, bytes]]

class:UnauthorizedException on mismatch.

WebhookSignatureVerifier

WebhookSignatureVerifier(
    secret: str | bytes,
    *,
    algorithm: str = "sha256",
    header_name: str = "X-Signature",
    encoding: str = "hex",
    prefix: str = "",
)

Validate HMAC-signed webhook payloads (Stripe/GitHub-style).

Providers usually compute hmac(secret, body) with a fixed algorithm and ship the digest in a request header (hex or base64). This helper centralizes the verification using :func:hmac.compare_digest (constant time) and exposes a FastAPI dependency that reads the raw body without consuming it for the route handler.

Attributes:

Name Type Description
secret bytes

The shared secret as bytes.

algorithm str

The hashlib algorithm name.

header_name str

The request header carrying the signature.

encoding str

How the signature is encoded — "hex" or "base64".

prefix str

Optional fixed prefix (e.g. "sha256=").

Initialize the verifier.

Parameters:

Name Type Description Default
secret str | bytes

The shared secret. Strings are encoded as UTF-8.

required
algorithm str

hashlib algorithm name ("sha256", "sha512", ...).

'sha256'
header_name str

Header carrying the signature.

'X-Signature'
encoding str

"hex" (default) or "base64".

'hex'
prefix str

Optional fixed prefix on the header value (e.g. "sha256="). Stripped before comparison.

''

Raises:

Type Description
ValueError

When secret is empty or only whitespace. An HMAC under an empty key is a digest anyone can compute, so a verifier built from an unset setting would accept every forged delivery; refusing at construction surfaces the missing configuration at boot instead.

expected

expected(body: bytes) -> str

Return the expected signature for body.

Parameters:

Name Type Description Default
body bytes

The raw request body to sign.

required

Returns:

Name Type Description
str str

The signature encoded per :attr:encoding.

verify

verify(body: bytes, signature: str) -> bool

Check signature against body in constant time.

Parameters:

Name Type Description Default
body bytes

The raw request body.

required
signature str

The provider-supplied signature (including any configured :attr:prefix).

required

Returns:

Name Type Description
bool bool

True when the signature matches.

dependency

dependency(
    *,
    error_message: str = "Invalid webhook signature",
    timestamp_header: str | None = None,
    max_age_seconds: int = 300,
) -> Callable[..., Coroutine[Any, Any, bytes]]

Build a FastAPI dependency that validates the inbound webhook.

The returned coroutine reads the raw body, verifies the header signature, and returns the body bytes so the route handler can re-parse it without re-reading the stream.

Replay. The signature covers the body and nothing else, so a captured request stays valid forever — anyone who can observe one delivery can resend it indefinitely. Pass timestamp_header= to additionally require a fresh unix-timestamp header and reject anything older than max_age_seconds, which bounds the window a captured delivery can be replayed in. It is opt-in because not every provider sends such a header, and turning it on unilaterally would reject their legitimate traffic. The SDK's own :class:WebhookSender sends X-Webhook-Timestamp.

The timestamp is not covered by the signature

Only the body is signed, so an attacker replaying a capture can also rewrite the timestamp to a current one. The check therefore bounds accidental and opportunistic replay, not an active attacker who reads and rewrites the request. Closing that needs the provider to sign timestamp.body — the shape Stripe uses; when yours does, verify it with verifier.verify(f"{ts}.".encode() + body, signature).

Parameters:

Name Type Description Default
error_message str

Message attached to the raised :class:UnauthorizedException when verification fails.

'Invalid webhook signature'
timestamp_header str | None

Header carrying a unix timestamp (seconds). None (default) skips the freshness check.

None
max_age_seconds int

How old a timestamped delivery may be. Ignored unless timestamp_header is set.

300

Returns:

Type Description
Callable[..., Coroutine[Any, Any, bytes]]

Callable[..., Coroutine[Any, Any, bytes]]: An async

Callable[..., Coroutine[Any, Any, bytes]]

FastAPI dependency that yields the raw body on success

Callable[..., Coroutine[Any, Any, bytes]]

and raises :class:UnauthorizedException on mismatch.