tempest_fastapi_sdk.api¶
A integração com o FastAPI: app factory, middlewares, routers prontos, dependências, OAuth, cookies, SPA e webhooks.
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_handlerfactory.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
|
include_traceback
|
bool
|
When |
False
|
log_level
|
int
|
Logging level used by the 5xx handlers.
Defaults to :data: |
ERROR
|
catalog
|
MessageCatalog | None
|
When set, the
:class: |
None
|
default_locale
|
str
|
Locale used when |
DEFAULT_LOCALE
|
locale_resolver
|
LocaleResolver | None
|
Optional callable taking
the request and returning a locale tag (or |
None
|
logger
|
Logger | None
|
Where every handler logs.
|
None
|
on_server_error
|
ServerErrorCallback | None
|
Called with
|
None
|
envelope_validation_errors
|
bool
|
Whether to register the
:class: |
False
|
envelope_client_errors
|
bool
|
Whether every 4xx answers the
envelope — the A |
False
|
redact_exception
|
ExceptionRedactor | None
|
Maps the caught
exception to the one the 5xx log records of all three handlers carries in
|
redact_database_errors
|
envelope_builder
|
ErrorEnvelopeBuilder | None
|
Builds the body of
every error response from an
:class: |
None
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
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 |
INFO
|
catalog
|
MessageCatalog | None
|
Message catalog used to
localize |
None
|
default_locale
|
str
|
Locale used when |
DEFAULT_LOCALE
|
locale_resolver
|
LocaleResolver | None
|
Optional callable taking
the request and returning a locale tag (or |
None
|
logger
|
Logger | None
|
Where this handler logs.
Typed as |
None
|
on_server_error
|
ServerErrorCallback | None
|
Called with
|
None
|
redact_exception
|
ExceptionRedactor | None
|
Maps the caught
exception to the one the 5xx log record carries in
|
redact_database_errors
|
envelope_builder
|
ErrorEnvelopeBuilder | None
|
Builds the response
body from an :class: |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
AppExceptionHandler |
AppExceptionHandler
|
An async |
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:
- Whenever
exc.status_code >= 500, the failure is logged atlog_level(ERROR by default) undertempest_fastapi_sdk.api.handlers. The record is flagged with :data:HTTP_500_MARKERsoconfigure_logging(log_dir=…)routes it to the dedicated500.logalongside the trace. - The response keeps the original
status_code/headersand adds the SDK envelope shape (detail/code/details), so frontends consuming the same envelope across :class:AppExceptionand rawHTTPExceptiondon'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 |
True
|
log_level
|
int
|
Logging level used for 5xx records. |
ERROR
|
catalog
|
MessageCatalog | None
|
Catalog used to localize a
generic 4xx |
None
|
default_locale
|
str
|
Locale used when |
DEFAULT_LOCALE
|
locale_resolver
|
LocaleResolver | None
|
Optional callable taking
the request and returning a locale tag (or |
None
|
envelope_client_errors
|
bool
|
Whether a 4xx answers the SDK
envelope ( |
False
|
logger
|
Logger | None
|
Where this handler logs.
Typed as |
None
|
on_server_error
|
ServerErrorCallback | None
|
Called with
|
None
|
redact_exception
|
ExceptionRedactor | None
|
Maps the caught
exception to the one the 5xx log record carries in
|
redact_database_errors
|
envelope_builder
|
ErrorEnvelopeBuilder | None
|
Builds the response
body from an :class: |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
HTTPExceptionHandler |
HTTPExceptionHandler
|
An async |
HTTPExceptionHandler
|
|
|
HTTPExceptionHandler
|
meth: |
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:
- Logs the failure at
log_level(ERROR by default) under thetempest_fastapi_sdk.api.handlerslogger. Whenlog_traceback=True(the default), the full traceback is attached viaexc_infoso the application'sLogUtils/configure_loggingsetup serializes it. The record is flagged with :data:tempest_fastapi_sdk.core.logging.HTTP_500_MARKERsoconfigure_logging(log_dir=...)can route it to a dedicated500.log. - Returns the canonical SDK JSON envelope with
code="INTERNAL_SERVER_ERROR"andstatus_code=500. - When
include_traceback=True(development only) appends the formatted traceback underdetails.tracebackso the failure is visible in the browser too. Leave it off in production — the body would leak module paths, secrets inreproutput and SQL fragments.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
log_traceback
|
bool
|
Whether to attach the full traceback to
the log record via |
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.
Typed as |
None
|
on_server_error
|
ServerErrorCallback | None
|
Called with
|
None
|
redact_exception
|
ExceptionRedactor | None
|
Maps the caught
exception to the one the 5xx log record carries in
|
redact_database_errors
|
envelope_builder
|
ErrorEnvelopeBuilder | None
|
Builds the response
body from an :class: |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
UnhandledExceptionHandler |
UnhandledExceptionHandler
|
An async |
UnhandledExceptionHandler
|
|
|
UnhandledExceptionHandler
|
meth: |
redact_database_errors
¶
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
|
|
RedactedError
¶
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
¶
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 |
()
|
catalog
|
MessageCatalog | None
|
Catalog used to fill each
example's |
None
|
locale
|
str
|
Locale resolved against |
DEFAULT_LOCALE
|
descriptions
|
Mapping[int, str] | None
|
Per-status description
overrides. Unlisted statuses keep the generated
|
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]]
|
|
dict[int | str, dict[str, Any]]
|
exceptions are given, so an unconditional |
dict[int | str, dict[str, Any]]
|
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If an argument is not an :class: |
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: |
None
|
locale
|
str
|
Forwarded to :func: |
DEFAULT_LOCALE
|
Returns:
| Type | Description |
|---|---|
Callable[[EndpointT], EndpointT]
|
Callable[[EndpointT], EndpointT]: A decorator that attaches a |
Callable[[EndpointT], EndpointT]
|
class: |
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
¶
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 |
{}
|
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 |
locale |
str
|
Locale resolved against |
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: |
required |
Returns:
| Type | Description |
|---|---|
RaisesSpec | None
|
RaisesSpec | None: The attached spec, or |
RaisesSpec | None
|
handler carries none. |
prune_orphan_enum_schemas
¶
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
¶
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 |
Callable[..., Coroutine[Any, Any, None]]
|
class: |
Callable[..., Coroutine[Any, Any, None]]
|
class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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]
|
|
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 |
None
|
strict
|
bool
|
Forwarded to :func: |
False
|
legacy_claims
|
Collection[str]
|
Forwarded to
:func: |
()
|
unauthorized_message
|
str
|
Message of the
:class: |
MISSING_TOKEN_MESSAGE
|
forbidden_message
|
str
|
Message of the
:class: |
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
¶
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: |
None
|
summary
¶
Return the operation summary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The operation key ( |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: The summary, or |
description
¶
Return the operation description, formatted when asked.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The operation key. |
required |
**params
|
str
|
Placeholder values ( |
{}
|
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: The description, or |
str | None
|
the endpoint docstring. |
text
¶
Return a parameter or response description.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The text key ( |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The description. |
Raises:
| Type | Description |
|---|---|
KeyError
|
When the catalog has no such text. |
RouteDoc
dataclass
¶
The OpenAPI text of one operation, in one language.
Attributes:
| Name | Type | Description |
|---|---|---|
summary |
str | None
|
The operation's |
description |
str | None
|
The operation's |
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 |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
DocsLocale |
DocsLocale
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When the argument names a language the catalog does not carry. |
ValidationError
|
When |
RequestIDMiddleware
¶
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'
|
dispatch
async
¶
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
¶
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
|
|
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. |
''
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
ErrorEnvelopeMiddleware
¶
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: |
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: |
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_HEADER
|
principal_resolver
|
Callable[[Request], str] | None
|
Returns
the caller identity folded into the cache key. |
None
|
cache_server_errors
|
bool
|
Whether a |
False
|
credential_headers
|
tuple[str, ...]
|
Request headers digested
into the caller identity when |
DEFAULT_CREDENTIAL_HEADERS
|
allow_anonymous
|
bool
|
Whether requests without an identity
(no credential header, or a resolver returning |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
dispatch
async
¶
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
¶
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 |
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
¶
: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
|
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 |
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
¶
Header name canonical to the industry: Stripe, AWS and GitHub all use it.
BodySizeLimitMiddleware
¶
Pure ASGI middleware enforcing max_bytes per request.
Two checks happen:
- Header check —
Content-Lengthgreater than the cap short-circuits immediately with a413response. This catches the common case where the client knows the size. - Streaming check — for chunked / unknown-length uploads
the middleware tracks bytes seen in the
http.requestmessages 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.
|
required |
exclude_paths
|
tuple[str, ...]
|
Path prefixes that
bypass the limit. Match is |
()
|
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 |
INFO
|
exempt_paths
|
tuple[str, ...]
|
Exact paths that produce no line at all. |
()
|
exempt_prefixes
|
tuple[str, ...]
|
Path prefixes that bypass
the middleware. Until 0.286.0 |
()
|
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
|
trusted_ip_header
|
str | None
|
Single edge-set header naming
the client IP (e.g. |
None
|
request_id_header
|
str
|
Response header the correlation id is
read from when the context variable is empty. Must match
:class: |
'X-Request-ID'
|
redact_capability_urls
|
bool
|
Hide the credentials the SDK
itself puts in URLs — the token segment of
|
True
|
include_layer_timings
|
bool
|
When |
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: |
required |
patterns
|
tuple[Pattern[str], ...]
|
Signatures matched
against the request path. Defaults to
:data: |
DEFAULT_HONEYPOT_PATTERNS
|
query_patterns
|
tuple[Pattern[str], ...]
|
Signatures matched
against the raw query string alone. Defaults to
:data: |
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. |
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. Until 0.286.0 |
()
|
status_code
|
int
|
Status returned to a banned or offending caller. |
403
|
matches
¶
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 |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
DEFAULT_HONEYPOT_PATTERNS
module-attribute
¶
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
¶
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
|
|
ban
async
¶
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
¶
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
¶
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
|
|
ban
async
¶
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: |
required |
RedisBanStore
¶
: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
|
required |
prefix
|
str
|
Key prefix so ban entries do not collide with other cached data. |
'honeypot:ban:'
|
is_banned
async
¶
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
|
|
ban
async
¶
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: |
retry_after |
int
|
|
Initialize the helper.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
drain_timeout
|
float
|
Max seconds to wait for in-flight
requests in :meth: |
30.0
|
retry_after
|
int
|
|
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. |
()
|
in_flight
property
¶
Return the number of requests currently being served.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The in-flight request count. |
is_draining
property
¶
Return whether draining has begun.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
dispatch
async
¶
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 |
Response
|
draining. |
begin_drain
¶
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 until in-flight requests finish or the timeout elapses.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
attr: |
install_signal_handlers
¶
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, 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:
- The CSRF cookie (
csrf_tokenby default). - The CSRF header (
X-CSRF-Tokenby 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. |
()
|
dispatch
async
¶
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
|
CSRF_COOKIE_NAME
|
secure
|
bool
|
Emit the |
True
|
samesite
|
Literal['lax', 'strict', 'none']
|
|
'lax'
|
max_age
|
int | None
|
Cookie lifetime in seconds. |
None
|
Returns:
| Type | Description |
|---|---|
Callable[[Request, Response], str]
|
Callable[[Request, Response], str]: FastAPI dependency. |
generate_csrf_token
¶
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
|
None
|
trusted_ip_header
|
str | None
|
When set (and |
None
|
store
|
RateLimitStore | None
|
Counter backend for the
single-window mode. Defaults to an in-process
:class: |
None
|
policy
|
RateLimitPolicy | None
|
Resolves a list of limits
per request — token buckets, stacked windows, per-plan
quotas. See
:class: |
None
|
quota_store
|
QuotaStore | None
|
Counter backend for the
policy mode. Defaults to an in-process
:class: |
None
|
exempt_paths
|
tuple[str, ...]
|
Exact paths to skip entirely
(e.g. |
()
|
exempt_prefixes
|
tuple[str, ...]
|
Path prefixes that bypass
the middleware. |
()
|
retry_after_header
|
bool
|
Whether to add a
|
True
|
limit_headers
|
bool
|
Whether to advertise the limit with
|
True
|
error_message
|
str
|
|
'Too many requests'
|
error_code
|
str
|
|
code
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
dispatch
async
¶
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
¶
Outcome of a single rate-limit check.
Attributes:
| Name | Type | Description |
|---|---|---|
allowed |
bool
|
|
remaining |
int
|
Requests still allowed in the current window
( |
retry_after |
int
|
Seconds the caller should wait before
retrying ( |
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:
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
¶
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.
|
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 |
Raises:
| Type | Description |
|---|---|
Exception
|
Propagates the backend error when |
key_by_ip
¶
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. |
None
|
Returns:
| Type | Description |
|---|---|
Callable[[Request], str]
|
Callable[[Request], str]: A key function yielding |
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 |
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
|
required |
claim
|
str
|
Claim whose value is the bucket key (e.g.
|
required |
scope
|
str | None
|
Prefix for the key. Defaults to |
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. |
'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
¶
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: |
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). |
None
|
trusted_ip_header
|
str | None
|
Single edge-set header holding the
real client IP (e.g. |
None
|
scope
|
str | None
|
Prefix of every bucket. |
None
|
limit_headers
|
bool
|
Whether to emit |
True
|
retry_after_header
|
bool
|
Whether to emit |
True
|
error_message
|
str
|
|
'Too many requests'
|
error_code
|
str
|
|
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 |
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.
|
required |
scope
|
str | None
|
Prefix of the key. Defaults to |
None
|
normalize
|
bool
|
Strip surrounding whitespace and lowercase the
value, so |
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 |
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. |
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
¶
Whether this rule uses the token-bucket algorithm.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
capacity
property
¶
Token-bucket capacity, or the window limit for a window rule.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
|
refill_per_second
property
¶
Tokens restored per second by the bucket.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
|
effective_scope
property
¶
Sub-key used to isolate this rule's counters.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
|
str
|
from the rule's numbers (e.g. |
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
|
|
limit |
int
|
|
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. |
scope |
str
|
:attr: |
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
¶
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
|
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 |
RedisQuotaStore
¶
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.
|
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 |
|
QuotaResult
|
set. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Exception
|
Propagates the backend error when |
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. |
required |
resolve
|
Callable[[Request], str | None]
|
Extracts the plan
name from the request. |
required |
default_plan
|
str
|
Plan used for anonymous traffic and for
names missing from |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
plan_for
¶
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 |
str
|
resolver yields |
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_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
¶
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 |
required |
claim
|
str
|
Claim holding the plan name. Defaults to |
'plan'
|
Returns:
| Type | Description |
|---|---|
Callable[[Request], str | None]
|
Callable[[Request], str | None]: The resolver. |
plan_by_header
¶
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: |
required |
Returns:
| Type | Description |
|---|---|
Callable[[Request], str]
|
Callable[[Request], str]: A key function yielding |
Callable[[Request], str]
|
|
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
¶
Google's authorize endpoint.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The configured endpoint URL. |
token_url
property
¶
Google's token endpoint.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The configured endpoint URL. |
userinfo_url
property
¶
OIDC-flavored userinfo endpoint.
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: The endpoint URL, or |
tokeninfo_url
property
¶
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
¶
GitHub's authorize endpoint.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The configured endpoint URL. |
token_url
property
¶
GitHub's token endpoint.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The configured endpoint URL. |
userinfo_url
property
¶
GitHub's user-info endpoint.
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: The endpoint URL, or |
emails_url
property
¶
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: |
required |
Returns:
| Name | Type | Description |
|---|---|---|
OAuthUser |
OAuthUser
|
Normalized identity. |
Raises:
| Type | Description |
|---|---|
OAuthError
|
When |
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
|
tokeninfo_url
|
str | None
|
A tokeninfo endpoint called as
|
None
|
introspection_url
|
str | None
|
The IdP's RFC 7662
introspection endpoint (Keycloak:
|
None
|
provider_name
|
str
|
Key embedded in
:attr: |
'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: |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When both |
authorize_url
property
¶
The provider's authorization endpoint, from discovery or config.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The configured endpoint URL. |
token_url
property
¶
The provider's token endpoint, from discovery or config.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The configured endpoint URL. |
userinfo_url
property
¶
The provider's userinfo endpoint, when it advertises one.
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: The endpoint URL, or |
tokeninfo_url
property
¶
The IdP's token-introspection endpoint, when one was wired.
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: The endpoint URL, or |
str | None
|
|
str | None
|
provider, since its audience cannot be checked. |
introspection_url
property
¶
The IdP's RFC 7662 introspection endpoint, when one was wired.
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: The endpoint URL, or |
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,
|
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 ( |
subject |
str
|
Stable per-provider user id. Combine with
|
email |
str | None
|
The email the provider returned, if any.
Some IdPs gate this behind extra scopes. Not necessarily
verified — check |
email_verified |
bool | None
|
Whether the provider states it has
verified |
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 |
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 |
scope |
str | None
|
Space-separated scopes granted. |
raw |
dict[str, Any]
|
Full token-endpoint response. |
OAuthError
¶
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 |
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: |
leeway |
float
|
Clock skew tolerated on |
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 |
required |
jwks_url
|
str
|
The realm's JWK Set endpoint — the
|
required |
algorithms
|
Sequence[str]
|
Signing algorithms accepted.
Closed on purpose; |
('RS256',)
|
required_claims
|
Sequence[str]
|
Claims a token must carry.
|
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 |
60
|
http_client
|
HTTPClient | None
|
Shared client for the
key-set fetch. |
None
|
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
ValueError
|
When |
verify
async
¶
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 |
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 |
OAuthTokenAudienceMismatchException
|
When the token was issued to another client. |
OAuthAudienceUnverifiableException
|
When
|
OAuthProviderUnavailableException
|
When the key set cannot be read. |
ALWAYS_REQUIRED_CLAIMS
module-attribute
¶
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
¶
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
¶
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 |
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: |
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
|
origins
|
list[str] | None
|
Override for
:attr: |
None
|
origin_regex
|
str | None
|
Override for
:attr: |
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 bytimeout, and returns200only when all pass. Returns503when at least one fails, raises or times out. One hung dependency fails only its own check, and the response still arrives after abouttimeout.
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
|
None
|
checks
|
dict[str, HealthCheck] | None
|
Extra readiness
checks keyed by name (e.g. |
None
|
prefix
|
str
|
The URL prefix for the router. Defaults to
|
'/health'
|
tag
|
str
|
OpenAPI tag applied to both endpoints. |
'health'
|
version
|
str | None
|
When provided, attached to the
readiness payload as |
None
|
expose_checks
|
bool
|
Whether to surface the per-dependency
breakdown in the readiness payload. Defaults to |
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. |
3.0
|
docs_locale
|
str | None
|
Language of the OpenAPI |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
APIRouter |
APIRouter
|
A router ready to |
APIRouter
|
FastAPI app. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
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 theheader_nameheader 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 readyDepends(...)/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 |
'logs'
|
token_secret
|
str
|
Shared secret expected in the
|
''
|
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
|
False
|
dependencies
|
Sequence[Callable[..., Any] | Depends] | None
|
Extra dependencies run on both routes, after the |
None
|
prefix
|
str
|
URL prefix for the router. Defaults to
|
'/logs'
|
tag
|
str
|
OpenAPI tag applied to the endpoints. |
'logs'
|
header_name
|
str
|
Auth header name. Defaults to |
'X-Token'
|
default_page_size
|
int
|
Page size when the caller omits it. |
20
|
max_page_size
|
int
|
Upper bound enforced on |
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
|
docs_locale
|
str | None
|
Language of the OpenAPI |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
APIRouter |
APIRouter
|
A router ready to |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
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 |
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 |
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:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
log_dir
|
str | Path
|
Directory holding the log files — the
|
required |
source
|
LogSource
|
Which file(s) to read. |
'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
|
Returns:
| Name | Type | Description |
|---|---|---|
LogReadResult |
LogReadResult
|
The matching records, newest first, and whether the |
LogReadResult
|
per-file bound cut any file. An empty |
|
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:
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'
|
delete_backups
|
bool
|
Also delete the rotated backups of each
file. Defaults to |
False
|
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: The names of the files that were emptied, in |
list[str]
|
func: |
list[str]
|
|
list[str]
|
to it. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
OSError
|
When a path cannot be opened for writing, or a backup cannot be deleted. |
LogReadResult
dataclass
¶
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 |
truncated |
bool
|
Whether at least one selected file held more
records than |
DEFAULT_MAX_RECORDS_PER_FILE
module-attribute
¶
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 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 afinallyso 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 |
required |
latency_buckets
|
tuple[float, ...]
|
Histogram bucket upper bounds in seconds. |
DEFAULT_LATENCY_BUCKETS
|
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
dispatch
async
¶
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: |
required |
path
|
str
|
Endpoint path. Defaults to |
'/metrics'
|
dependencies
|
list[Callable[..., Any] | Depends] | None
|
FastAPI dependencies attached to the route. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
APIRouter |
APIRouter
|
Mount with |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
TypeError
|
When |
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
¶
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
|
|
|
CollectorRegistry
|
metrics between runs. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
BusinessMetrics
¶
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
Attributes:
| Name | Type | Description |
|---|---|---|
namespace |
str
|
Optional prefix applied to every metric name
( |
Bind the factory to a registry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
registry
|
CollectorRegistry
|
The shared registry (from
:func: |
required |
namespace
|
str
|
Optional name prefix for every metric. |
''
|
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
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 |
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 |
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 |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Histogram |
Histogram
|
The |
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
¶
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
|
path
|
str
|
Cookie path. Scope sensitive cookies (refresh tokens) to their endpoint to shrink the blast radius. |
'/'
|
domain
|
str | None
|
Cookie domain. |
None
|
http_only
|
bool
|
Block JS access ( |
True
|
secure
|
bool
|
Require HTTPS. Default |
True
|
samesite
|
SameSite
|
|
'lax'
|
clear_cookie
¶
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'
|
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 |
()
|
security_headers
|
dict[str, str] | None
|
Headers to stamp
on every response. Defaults to
:data: |
None
|
**kwargs
|
object
|
Keyword arguments forwarded to |
{}
|
get_response
async
¶
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 |
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
|
asset_cache_control
|
str
|
|
DEFAULT_ASSET_CACHE_CONTROL
|
document_cache_control
|
str
|
|
DEFAULT_DOCUMENT_CACHE_CONTROL
|
allow_blocking_headers
|
bool
|
Skip the check that refuses a
|
False
|
security_headers
|
dict[str, str] | None
|
Headers stamped on the
document and on every asset. Defaults to
:data: |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
APIRouter |
APIRouter
|
A router serving the assets and the SPA fallback. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
When |
ValueError
|
When |
DEFAULT_ASSET_CACHE_CONTROL
module-attribute
¶
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
¶
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
|
None
|
max_attempts
|
int
|
Total POST attempts before giving up
( |
3
|
backoff_base
|
float
|
Base seconds for exponential backoff
( |
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 ( |
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 — |
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]]
|
|
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 |
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 ( |
required |
otlp_endpoint
|
str | None
|
OTLP/gRPC collector endpoint
(e.g. |
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 |
None
|
instrument_httpx
|
bool
|
When |
True
|
sample_ratio
|
float
|
Head-based sampling ratio in |
1.0
|
resource_attributes
|
dict[str, str] | None
|
Extra resource
attributes merged onto every span (e.g.
|
None
|
insecure
|
bool
|
Whether the OTLP gRPC channel is plaintext.
Defaults to |
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 |
ValueError
|
If |
Warns:
| Type | Description |
|---|---|
RuntimeWarning
|
When |
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 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
|
required |
Raises:
| Type | Description |
|---|---|
ImportError
|
If |
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:
Authorization: Bearer <jwt>header.- The
cookie_namecookie, when set. - The
query_paramquery-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 |
required |
soft
|
bool
|
When |
False
|
bearer_scheme
|
HTTPBearer | None
|
Override the bearer scheme.
Defaults to |
None
|
cookie_name
|
str | None
|
When set, fall back to this cookie for
the access token if the |
None
|
query_param
|
str | None
|
When set, fall back to this
query-string parameter (e.g. |
None
|
accepted_typ
|
Collection[str]
|
Token types this dependency
accepts, matched against the |
(ACCESS_TOKEN_TYPE,)
|
strict
|
bool
|
How to treat a token that carries no
recognizable type marker. |
False
|
legacy_claims
|
Collection[str]
|
Extra claim names to read the
token type from when |
()
|
error_message
|
str
|
Message attached to the raised
:class: |
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 |
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:
- Reads the JWT from
Authorization: Bearer(or, whencookie_nameis set, falls back to that cookie). - Decodes / verifies the JWT with
tokens. - Pulls the user identifier from the configured
subject_claim. - 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 |
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
|
required |
soft
|
bool
|
When |
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 |
None
|
query_param
|
str | None
|
When set, fall back to this
query-string parameter for the access token (cookieless
clients such as |
None
|
accepted_typ
|
Collection[str]
|
Token types accepted, matched
against the |
(ACCESS_TOKEN_TYPE,)
|
strict
|
bool
|
How to treat a token that carries no
recognizable type marker. |
False
|
legacy_claims
|
Collection[str]
|
Extra claim names to read the
token type from when |
()
|
subject_claim
|
str
|
Which JWT claim carries the user id.
Defaults to |
'sub'
|
error_message
|
str
|
Message attached to the raised
:class: |
MISSING_TOKEN_MESSAGE
|
session_dependency
|
Callable[..., Any] | None
|
The
request-scoped session provider to share with repositories.
When set, |
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 |
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 |
required |
required_permissions
|
Iterable[str]
|
Permissions the route requires. |
required |
permissions_claim
|
str
|
JWT claim carrying the permissions.
Defaults to |
'permissions'
|
require_all
|
bool
|
When |
True
|
bearer_scheme
|
HTTPBearer | None
|
Override the bearer scheme. |
None
|
unauthorized_message
|
str
|
Message attached to the
:class: |
MISSING_TOKEN_MESSAGE
|
forbidden_message
|
str
|
Message attached to the
:class: |
'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 |
required |
required_roles
|
Iterable[str]
|
Roles the route accepts. |
required |
roles_claim
|
str
|
Which JWT claim carries the roles.
Defaults to |
'roles'
|
require_all
|
bool
|
When |
False
|
bearer_scheme
|
HTTPBearer | None
|
Override the bearer scheme. |
None
|
unauthorized_message
|
str
|
Message attached to the raised
:class: |
MISSING_TOKEN_MESSAGE
|
forbidden_message
|
str
|
Message attached to the raised
:class: |
'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: |
Callable[..., Coroutine[Any, Any, None]]
|
class: |
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'
|
error_message
|
str
|
Message attached to the raised
:class: |
'Invalid or missing token'
|
allow_unauthenticated
|
bool
|
Accept an empty |
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: |
Callable[..., Coroutine[Any, Any, None]]
|
mismatch and returns |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
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 |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
UnauthorizedException
|
When the tokens do not match in constant time. |
describe_validation_envelope
¶
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
¶
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: |
INFO
|
catalog
|
MessageCatalog | None
|
Catalog used to localize each
entry. |
None
|
default_locale
|
str
|
Locale used when |
DEFAULT_LOCALE
|
locale_resolver
|
LocaleResolver | None
|
Optional callable taking
the request and returning a locale tag (or |
None
|
logger
|
Logger | None
|
Where this handler logs.
|
None
|
envelope_builder
|
ErrorEnvelopeBuilder | None
|
Builds the response
body from an :class: |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
ValidationExceptionHandler |
ValidationExceptionHandler
|
An async |
ValidationExceptionHandler
|
|
|
ValidationExceptionHandler
|
meth: |
ServerErrorCallback
module-attribute
¶
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
¶
The envelope code a request-validation failure answers with.
ValidationExceptionHandler
module-attribute
¶
Async callable resolving a request-validation failure to a response.
LocaleResolver
module-attribute
¶
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:
query_param— the query string (?lang=en-USby default;Noneignores the query string).request.state.<state_attr>— a locale attached by a middleware or dependency (request.state.localeby default;Noneskips).request.state.<user_attr>.<user_locale_attr>— the preference stored on the authenticated user (request.state.user.localeby default, the column :class:~tempest_fastapi_sdk.LocaleColumnMixinadds;user_attr=Noneskips).None— the handler then negotiatesAccept-Languageand falls back to itsdefault_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 |
'locale'
|
user_attr
|
str | None
|
Attribute of |
'user'
|
user_locale_attr
|
str
|
Attribute of the user object holding the
locale. Defaults to |
'locale'
|
query_param
|
str | None
|
Query parameter checked first. Defaults
to |
'lang'
|
catalog
|
MessageCatalog | None
|
Catalog used to skip unsupported signals instead of returning them. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
LocaleResolver |
LocaleResolver
|
A |
LocaleResolver
|
func: |
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 ( |
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 |
field |
str | None
|
The input an :class: |
request |
Request
|
The request being answered. |
request_id |
str | None
|
The request id from the contextvar or the
|
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
module-attribute
¶
Default cookie holding the CSRF token.
CSRF_HEADER_NAME
module-attribute
¶
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 |
body |
bytes
|
Raw response body bytes. |
media_type |
str | None
|
Original |
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 |
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
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
CachedResponse | None
|
CachedResponse | None: The stored response, or |
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 |
required |
response
|
CachedResponse
|
The response to store. |
required |
ttl_seconds
|
int
|
How long the entry stays fresh. |
required |
RedisResponseCacheStore
¶
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 ( |
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 |
required |
Returns:
| Type | Description |
|---|---|
CachedResponse | None
|
CachedResponse | None: The stored response, or |
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 |
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
|
ttl_seconds
|
int
|
Server-cache TTL and the default |
60
|
max_age
|
int | None
|
|
None
|
cache_control
|
str | None
|
Explicit |
None
|
methods
|
tuple[str, ...]
|
HTTP methods eligible for caching. |
('GET', 'HEAD')
|
cacheable_status
|
tuple[int, ...]
|
Status codes eligible for
caching (default: only |
(200,)
|
vary
|
tuple[str, ...]
|
Request headers folded into the cache key
and emitted as |
()
|
exempt_paths
|
tuple[str, ...]
|
Exact paths that bypass the middleware. |
()
|
exempt_prefixes
|
tuple[str, ...]
|
Path prefixes that bypass
the middleware. |
()
|
cacheable
|
Callable[[Request], bool] | None
|
Optional predicate;
when it returns |
None
|
cache_credentialed
|
bool
|
Whether a request carrying any of
|
False
|
credential_headers
|
tuple[str, ...]
|
Request headers whose
presence marks a request as credentialed. The default covers
|
DEFAULT_CREDENTIAL_HEADERS
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
dispatch
async
¶
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 |
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 |
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 |
OAuthTokenRejectedException
|
When the provider rejects the token outright. |
HealthCheck
module-attribute
¶
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
¶
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
|
|
LogSource
module-attribute
¶
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
¶
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 ( |
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'
|
tag
|
str
|
OpenAPI tag. Defaults to |
'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 |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
APIRouter |
APIRouter
|
A FastAPI router with a single |
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'
|
settings
|
ServerSettings | None
|
Optional settings object;
|
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: |
{}
|
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 ( |
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'
|
header_name
|
str
|
Header carrying the base64 signature. |
'x-webhook-signature'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
verify
¶
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
|
|
Raises:
| Type | Description |
|---|---|
ImportError
|
If |
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: |
'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: |
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 — |
prefix |
str
|
Optional fixed prefix (e.g. |
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'
|
header_name
|
str
|
Header carrying the signature. |
'X-Signature'
|
encoding
|
str
|
|
'hex'
|
prefix
|
str
|
Optional fixed prefix on the header value
(e.g. |
''
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
expected
¶
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: |
verify
¶
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: |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
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: |
'Invalid webhook signature'
|
timestamp_header
|
str | None
|
Header carrying a unix timestamp
(seconds). |
None
|
max_age_seconds
|
int
|
How old a timestamped delivery may be.
Ignored unless |
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: |