Skip to content

Auth CSRF

Synchronizer-token CSRF protection.

rn_forge.fastapi.auth.csrf

Synchronizer-token CSRF protection for the session-authenticated routes.

The token is a random value kept server-side under the session ID, and handed to the browser in the readable XSRF-TOKEN cookie. :class:CsrfProtection compares it in constant time with the X-XSRF-TOKEN header on an unsafe request, which are the names Angular's HttpClient uses. Before sign-in the record is keyed by an anonymous ID behind the __Host-session cookie, so the login request is protected too. SessionMiddleware decides which requests are checked: those that carry the session cookie, and the password-login path.

The request's Origin (Referer over HTTPS when there is no Origin) must be its own origin or one of trusted_origins, and Sec-Fetch-Site: cross-site is rejected. The request's own scheme and host come from X-Forwarded-Proto and X-Forwarded-Host only when the peer is one of trusted_proxies. A request with a Bearer Authorization header skips the check.

ANONYMOUS_PREFIX = 'anon.' module-attribute

Starts the ID of an anonymous session.

ANONYMOUS_TTL = timedelta(minutes=10) module-attribute

How long an anonymous session holds its token.

The readable cookie that carries the token.

CSRF_HEADER = 'X-XSRF-TOKEN' module-attribute

The request header that must repeat the token.

CsrfProtection(*, store, problem_type_base, trusted_origins=(), trusted_proxies=())

The token store and the checks that guard unsafe requests.

Parameters:

Name Type Description Default
store CsrfStore

Holds the tokens.

required
problem_type_base str

Prefix of the type URI of the csrf-failed problem; empty for about:blank.

required
trusted_origins Collection[str]

Origins, besides the request's own, that may send an unsafe request, such as https://app.example.

()
trusted_proxies Collection[str]

Peer addresses or CIDR networks whose forwarded scheme and host headers are believed.

()

check(*, method, headers, scheme, peer, expected)

Check one request.

Parameters:

Name Type Description Default
method str

The HTTP method.

required
headers Mapping[str, str]

The request headers, by lowercase name.

required
scheme str

The scheme the server received the request on.

required
peer str | None

The address of the connection's peer.

required
expected str | None

The token stored for the request's session, or None when it has none.

required

Raises:

Type Description
CsrfFailed

The request is unsafe and the origin, fetch-metadata or token check fails.

is_anonymous(key) staticmethod

Whether key has the shape of an anonymous session ID.

mint(key, *, ttl)

Store a new random token under key, replacing any token, and return it.

new_anonymous_id() staticmethod

A new anonymous session ID.

Set the token cookie on response.

CsrfStore

Bases: Protocol

Holds the CSRF token of each session, keyed by session ID.

Every method is synchronous and thread-safe.

delete(key)

Remove the token stored under key, if any.

get(key)

Return the token stored under key, or None when there is none.

save(key, token, *, ttl)

Store token under key, replacing any token, for ttl.

InMemoryCsrfStore(clock=_utc_now)

:class:CsrfStore held in process memory, for tests and development.

Parameters:

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

Returns the current time, aware.

_utc_now

delete(key)

Remove the token under key.

get(key)

Return the unexpired token under key.

save(key, token, *, ttl)

Store token under key for ttl.