xtr_security_csrf ¶
Cross-site request forgery tokens, minted and checked by id.
A manager mints a value per token id, masks what it hands out, and checks what comes back against what it stored; a storage keeps the values — in the session a request carries, or wherever the application points them. This module gathers the public surface so an application imports it from one place.
CsrfToken ¶
The id a token is known under, and the value that answers for it.
A token id names what the token guards — a form, an action, a listener — and the value is what a request carries to prove that the page which rendered it asked for it. The pair travels together: the id says which stored value the carried one is checked against.
Record the id and the value that answers for it.
Parameters:
CsrfTokenManager ¶
CsrfTokenManager(storage: TokenStorageInterface, generator: TokenGeneratorInterface | None = None, namespace: str | Callable[[], str] | None = None)
Bases: CsrfTokenManagerInterface
Mints a value per token id, stores it, and masks what it hands out.
What answers for an id is not the value that is stored: every value handed out is masked with a fresh key, so two renders of the same form carry different strings, and a page that compresses its response cannot be made to leak a token by echoing one back. The masked value is all a caller ever sees; the stored one is all the manager ever compares.
The id a value is stored under is the namespace followed by the token id, so tokens minted for one origin do not answer for another.
Record where values are kept, what mints them, and how ids are prefixed.
Parameters:
-
storage(TokenStorageInterface) –Where token values are kept, by namespaced id.
-
generator(TokenGeneratorInterface | None, default:None) –What mints a fresh value; a URI-safe generator when nothing is given.
-
namespace(str | Callable[[], str] | None, default:None) –The prefix every stored id carries, so tokens minted for one origin do not answer for another: a string used as it is, or a callable asked each time — the scheme a request arrived under can change between calls, so it is read per call, not once.
Noneprefixes nothing.
get_token
async
¶
Return the token for token_id, minting one where none is stored.
A value already stored is handed out again — masked anew, so the string differs, but it answers for the same stored value.
refresh_token
async
¶
Mint a fresh value for token_id, replacing whatever was stored.
remove_token
async
¶
Drop the value under token_id, returning what it held.
is_token_valid
async
¶
Tell whether token carries the value stored under its id.
The comparison is constant-time, and the value it is handed is never trusted to be well-formed: one that does not read as a value this manager minted is compared as it came, and does not check out.
CsrfTokenManagerInterface ¶
Bases: Protocol
Mints, renews, drops and checks tokens, by id.
Every member is awaited: a manager reaches a storage to answer any of them, and one storage must be swappable for another — a remote one is awaited — exactly as every matcher is awaited even when it only reads the head of a request.
get_token
async
¶
Return the token for token_id, minting one where none is stored.
A token already stored is returned with the value it holds — the same stored value, though not the same string, since what is handed out is masked per call — so asking twice answers two tokens that both check out.
refresh_token
async
¶
Mint a fresh value for token_id, stored or not.
For once-only tokens, in places with high security needs: whatever was stored under the id is replaced, independent of whether a value existed before.
remove_token
async
¶
Drop the token under token_id, if one is stored.
Returns:
-
str | None–The value the id held, or
Nonewhen it held nothing.
is_token_valid
async
¶
Tell whether token carries the value stored under its id.
Never raises on the value it is handed: one that does not read as a value this manager minted simply does not check out.
CsrfError ¶
Bases: Exception
Base class for every error raised by this library.
Catch this to handle anything minting or checking a cross-site request forgery token can go wrong with; catch a subclass to handle one cause. Every subclass carries the data a caller needs as typed attributes and composes its own message from them.
InvalidArgumentError ¶
Bases: CsrfError, ValueError
A declaration, configuration or call was malformed.
A generator asked for less entropy than a byte holds — mistakes caught
where they are made. Also a :class:ValueError, so code guarding its
configuration with except ValueError keeps working.
TokenNotFoundError ¶
Bases: CsrfError
No token is stored under the id a caller asked to read.
The manager never raises it — where nothing is stored it mints — it is
the error a storage raises when its get_token is called directly for
an id that holds nothing.
Record which id was asked about and found empty.
Parameters:
-
token_id(str) –The id whose stored value was asked for.
TokenGeneratorInterface ¶
UriSafeTokenGenerator ¶
Bases: TokenGeneratorInterface
Mints URI-safe values: base64 with +, / and = gone.
A value that carries none of the characters a URI encodes sits in a query, a form field or a header as it is, without a reader having to decode anything first — which is why the padding is stripped too.
Record how much entropy each minted value carries.
Parameters:
-
entropy(int, default:256) –The bits of randomness each value is drawn from.
Raises:
-
InvalidArgumentError–When
entropyis 7 bits or fewer — a value that short could be guessed.
ClearableTokenStorageInterface ¶
Bases: TokenStorageInterface, Protocol
A token storage that can also drop everything it holds.
The session strategy is the caller: when a re-authentication rotates the session, the tokens minted under the old one must not answer for the new — a value stolen before the rotation would otherwise still check out after it.
SessionTokenStorage ¶
Bases: ClearableTokenStorageInterface
Keeps token values in the session, under the id they answer for.
Each value lives under <namespace>/<token_id>: the namespace keeps
the tokens out of the attributes the rest of the application keeps in
the same session, and lets two applications sharing one session keep
their tokens apart.
The storage also keeps the list of its ids under the namespace key
itself. The session offers no way to walk the attributes it carries, so
the list is what clear() drops them from — every token this storage
minted, and nothing the rest of the session holds. A value written
under the namespace by something else than this storage is not in the
list, and survives a clear.
Record the session the tokens travel in, and their namespace.
Parameters:
-
session(SessionInterface) –The session whose attributes carry the tokens.
-
namespace(str, default:'_csrf') –The prefix every stored id carries.
get_token
async
¶
Return the value stored under token_id.
Raises:
-
TokenNotFoundError–When no value is stored under the id.
set_token
async
¶
Store token under token_id, and remember the id.
remove_token
async
¶
Drop the value under token_id, returning what it held.
clear
async
¶
Drop every token this storage minted, and nothing else.
The ids come from the list kept under the namespace key, so the clear is complete across the requests that minted them — a token stored two requests ago goes with one stored now. The session strategy calls this when a re-authentication rotates the session: the tokens minted under the old one must not answer for the new.
TokenStorageInterface ¶
Bases: Protocol
Keeps token values by id, wherever the application points them.
Every member is awaited: one storage must be swappable for another, and a remote one is awaited — the session is only the one this library ships a storage for.
get_token
async
¶
Return the value stored under token_id.
Raises:
-
TokenNotFoundError–When no value is stored under the id.
set_token
async
¶
Store token under token_id, replacing what was there.