ORIONIS API REFERENCE

THE ORIONIS API

Build with clarity.

Explore the building blocks of an async-first Python framework. Every module, class, and method — connected, searchable, and ready to build with.

class documentation

class CSRFTokenMiddleware(BaseMiddleware): (source)

Constructor: CSRFTokenMiddleware(config)

View In Hierarchy

Web-layer middleware that enforces Cross-Site Request Forgery protection.

Design decisions

  • Session-bound token — an existing token is reused while its session value is truthy. session.regenerate() requests an identifier rotation and preserves the token along with the other session data. SessionGuard.login() explicitly replaces the token; logout invalidates the session and clears it. This middleware creates a token when the configured session key is missing or has a falsy value.
  • Cryptographic token — secrets.token_urlsafe(n) produces URL-safe Base-64 output from the OS CSPRNG. 32 bytes → 256 bits of entropy, well above the OWASP minimum.
  • Timing-safe comparison — secrets.compare_digest() is used exclusively; plain == is never used.
  • Header-first extraction — X-CSRF-Token and X-XSRF-Token are checked before touching the body. Body parsing is skipped entirely when the token is already present in a header, avoiding unnecessary I/O on API-style clients.
  • XSRF-TOKEN cookie — opt-in double-submit cookie pattern for Angular, Axios, and other JavaScript frameworks. The cookie is intentionally not HttpOnly so client scripts can read it.
  • Immediate exit paths — the hot path bails out as early as possible for safe methods and disabled middleware, adding near-zero overhead for the common GET case. Route-level exclusions are handled by the router (don't add the middleware to those routes).
  • No global state — all request-scoped data flows through request.state; the middleware instance itself is stateless.
Async Static Method __extractFromBody Return the CSRF token from the parsed form body, or None.
Static Method __extractFromHeaders Return the CSRF token from the request headers, or None.
Method __attachXsrfCookie Set the XSRF-TOKEN cookie on the outgoing response.
Method __init__ Initialise the middleware from a raw configuration dictionary.
Method __resolveToken Return the CSRF token for this session, creating it if absent.
Async Method handle Execute the CSRF lifecycle for one HTTP request.
Class Variable __slots__ Declare the instance attribute slots reserved by this class.
Instance Variable _cfg Cfg supplied through cfg.
Instance Variable _enabled Store the settings used by the token lifecycle.
Instance Variable _session_key Session key under which the authenticated identity is stored.
Instance Variable _token_length Token length obtained from cfg.token_length.
Instance Variable _xsrf_cookie Xsrf cookie obtained from cfg.xsrf_cookie.
async def __extractFromBody(request: Request) -> str | None: (source)

Return the CSRF token from the parsed form body, or None.

Only invoked for application/x-www-form-urlencoded and multipart/form-data requests; JSON and other content-types are expected to supply the token via a header. Body parsing is deliberately deferred to this point: when the token is already in a header this method is never called.

Checked field names (in order): _csrf, csrf_token.

Parameters
request:orionis.http.RequestIncoming HTTP request.
Returns
str | NoneToken string if found, otherwise None.
def __extractFromHeaders(request: Request) -> str | None: (source)

Return the CSRF token from the request headers, or None.

Checks X-CSRF-Token first, then X-XSRF-Token. Header inspection is O(1) and involves no I/O, so it is always tried before the request body.

Parameters
request:orionis.http.RequestIncoming HTTP request.
Returns
str | NoneToken string if found, otherwise None.
def __attachXsrfCookie(self, request: Request, response: Response, token: str): (source)

Set the XSRF-TOKEN cookie on the outgoing response.

The cookie is intentionally not HttpOnly so that JavaScript frameworks (Angular, Axios) can read it and forward it as the X-XSRF-Token request header.

The Secure flag is promoted to True automatically when the current request arrives over HTTPS, regardless of the cookie_secure configuration value.

Parameters
request:orionis.http.RequestProvides the scheme to decide whether to promote the Secure flag.
response:orionis.http.ResponseResponse to which the Set-Cookie header is appended.
token:strCSRF token to embed in the cookie value.
Returns
NoneSet the XSRF-TOKEN cookie on the outgoing response.
def __init__(self, config: dict): (source)

Initialise the middleware from a raw configuration dictionary.

Parameters
config:dictKey-value pairs that correspond to HTTPCsrf fields. An empty dict uses all framework defaults.
Returns
NoneInitialise the middleware from a raw configuration dictionary.
def __resolveToken(self, request: Request) -> str: (source)

Return the CSRF token for this session, creating it if absent.

An existing truthy token is returned unchanged, including after session.regenerate(). A new token is stored only when the configured session key is missing or has a falsy value. Login token rotation and logout clearing are handled explicitly by SessionGuard.

Without an active session, return a fresh ephemeral token for this request without persisting it.

Parameters
request:orionis.http.RequestCurrent request; session is read from request.state.session.
Returns
strURL-safe Base-64 CSRF token.
async def handle(self, request: Request, call_next: Callable[[], Awaitable[Response]]) -> Response: (source)

Execute the CSRF lifecycle for one HTTP request.

For safe methods the token is attached to request.state so templates can render the hidden field, and the request proceeds without any token comparison.

For unsafe methods the submitted token is extracted, compared against the session token, and CSRFTokenMismatchException is raised on mismatch before the handler is ever called.

Parameters
request:orionis.http.RequestIncoming HTTP request with an active session available at request.state.session.
call_next:Callable[[], Awaitable[Response]]No-arg async callable that advances through the rest of the middleware pipeline and into the route handler.
Returns
orionis.http.ResponseHTTP response, optionally augmented with the XSRF-TOKEN cookie when xsrf_cookie is enabled.
Raises
orionis.http.layer.web.exceptions.CSRFTokenMismatchExceptionWhen an unsafe request does not supply a valid CSRF token.
__slots__: tuple[str, ...] = (source)

Declare the instance attribute slots reserved by this class.

_cfg: HTTPCsrf = (source)

Cfg supplied through cfg.

_enabled: bool = (source)

Store the settings used by the token lifecycle.

_session_key: str = (source)

Session key under which the authenticated identity is stored.

_token_length: int = (source)

Token length obtained from cfg.token_length.

_xsrf_cookie: bool = (source)

Xsrf cookie obtained from cfg.xsrf_cookie.