xtr_security_http ¶
The HTTP edge of xtr security: firewalls, authenticators and access tokens.
The :class:Firewall — a subscriber over the kernel lifecycle's events — the
:class:IsGranted and :class:CurrentUser route surface, the authenticator
and passport machinery a firewall runs, the bearer access-token extractors and
the :class:AccessTokenAuthenticator, and the listeners and events around a
login. Built on the security core; needs FastAPI and xtr-http-kernel.
MAX_USERNAME_LENGTH
module-attribute
¶
The longest identifier a badge accepts, guarding against a runaway input.
SOURCE_PAYLOAD
module-attribute
¶
Read the presented value from the request payload: the JSON body, else the form.
SOURCE_QUERY
module-attribute
¶
Read the presented value from the query string.
AccessMap ¶
Bases: AccessMapInterface
Holds a firewall's access-control rules and finds the first a request matches.
A rule is a request matcher and the one attribute a claimed request must
satisfy, added with :meth:add. Rules are tried in the order they were
added; the first whose matcher claims the request decides it, so a broad
^/api rule must be added after the narrow ^/api/admin it would
otherwise shadow. A request matching no rule has no attribute to satisfy —
the firewall lets it through, its access left to whatever the route itself
requires.
:meth:get_patterns answers the rule's attribute as the one member of a
tuple, beside the channel the rule demands the request arrive over. A
rule added without a channel demands none — the channel half of its
answer is None — while one added with channel="https" is answered
with a redirect until the request arrives over it.
Start with no rules; add each with :meth:add.
add ¶
Append a rule: attribute is required of a request request_matcher claims.
One attribute per rule is deliberate — a rule that needs two conditions is two rules, or a single closure attribute.
channel names the scheme the rule demands the request arrive
over — "https" or "http" — or None to demand none; the
channel listener answers a request arriving over the wrong one with a
redirect to the same request over the scheme the rule demands.
get_patterns
async
¶
Return the first matching rule's attribute, and the channel it demands.
The attribute rides out as the one member of a tuple, the shape the
deciding step hands the access decision manager; the channel is the
one the matching rule demands, or None when it demands none.
AccessMapInterface ¶
Bases: Protocol
Answers what a request must satisfy, from a firewall's access rules.
The access listener asks this after authentication: the first rule whose
matcher claims the request names the attributes the token must satisfy,
and a request no rule claims has none. The channel half of the answer —
which scheme the rule demands the request arrive over — is the channel
listener's to enforce; no rule carries one yet, so every answer pairs its
attributes with None until one does.
get_patterns
async
¶
Return the first matching rule's attributes, and the channel it demands.
Parameters:
-
request(ServerRequestInterface) –The request the rules are matched against, as a message.
Returns:
-
tuple[str, ...]–The attributes the first rule whose matcher claims
request -
str | None–requires — an empty tuple when no rule claims it — and the channel
-
tuple[tuple[str, ...], str | None]–that rule demands the request arrive over, or
Nonewhen it -
tuple[tuple[str, ...], str | None]–demands none.
AccessTokenExtractorInterface ¶
Bases: Protocol
Reads the token string from a request.
An extractor knows where a token lives — an Authorization header, a
query parameter, a form field — and returns it as a string, or None
when the request carries none.
extract_access_token
async
¶
Return the token in request, or None when there is none.
AccessTokenHandlerInterface ¶
Bases: Protocol
Validates an access token and reports who it was issued for.
A handler is the whole of what makes a bearer token trustworthy: it
verifies the token — a JWT's signature and claims, an introspection
call — and returns a
:class:~xtr_security_http.authenticator.passport.badge.user_badge.UserBadge
naming the user, its attributes carrying the token's scope,
client_id, jti and remaining claims. This is the seam an OAuth2
resource server plugs its own token validation into.
get_user_badge_from
async
¶
Return the user badge access_token proves.
Raises:
-
AuthenticationError–When the token cannot be trusted — most often an :class:
InvalidAccessTokenErrorfor a malformed, expired or wrongly signed token.
ChainAccessTokenExtractor ¶
Bases: AccessTokenExtractorInterface
Returns the first token any of its extractors finds.
Tries each extractor in turn and returns the first non-None token, so a
firewall can accept a token from a header or a query parameter without
caring which the client used.
Record the extractors to try, in order.
Raises:
-
InvalidArgumentError–When no extractor is given, which would find no token ever.
extract_access_token
async
¶
Return the first token any extractor finds, or None when none do.
FormEncodedBodyExtractor ¶
Bases: AccessTokenExtractorInterface
Reads a token from a form field of an x-www-form-urlencoded body.
RFC 6750 allows a bearer token in a form body; this reads the
access_token field of one, when the request carries that content type.
The body is read as the message the request arrived as — the read
materialises it and its parsed side — and the token is read out of the
parsed form, so no form-parsing dependency is needed.
Attributes:
-
field_name–The form field the token is read from.
Build the extractor for the field_name form field.
extract_access_token
async
¶
Return the token in the form body, or None when it is absent.
Only a POST whose content type names the urlencoded form encoding
is read — the one request a submitted form travels as, its media type
weighed whole, so one that only starts like it is no form. The body is
read before the parsed form is asked for, the order a served request
needs: the reading materialises both, and the parsed side answers
behind it. A body that turns out larger than the 64 KiB cap yields no
token — the cap weighs the bytes that actually arrived, never what a
header promised — and so does a form whose field carries anything
other than one text value; an endpoint behind the firewall then
challenges rather than failing on the oversize or malformed body.
HeaderAccessTokenExtractor ¶
Bases: AccessTokenExtractorInterface
Reads a token from a request header, Authorization: Bearer <token> by default.
The standard reading is the one the framework's own bearer dependency
performs — the scheme word and the credentials parted by the first space,
the scheme matched without regard to case — so a missing or malformed
header reads as None and the firewall's entry point — not the
framework — answers the challenge. A different header name or token type
folds the extraction onto the raw header value instead, for a scheme that
is not the standard bearer one.
Attributes:
-
header_name–The header the token is read from.
-
token_type–The scheme word before the token (
"Bearer"by default).
Build the extractor for header_name carrying a token_type token.
extract_access_token
async
¶
Return the token in the header, or None when it is absent or malformed.
QueryAccessTokenExtractor ¶
Bases: AccessTokenExtractorInterface
Reads a token from a query parameter, access_token by default.
A request without the parameter reads as None. Passing a bearer token
in the URL is discouraged by RFC 6750, but some clients can send it no
other way; the extractor exists for them.
Attributes:
-
parameter_name–The query parameter the token is read from.
Build the extractor for the parameter_name query parameter.
extract_access_token
async
¶
Return the token in the query parameter, or None when it is absent.
A name the query answers with anything other than one text value — the contract lets a repeated or nested name answer structure — reads as no token: a bearer token is one string, and anything else in its place is a malformed request rather than a credential.
SenderConstraintInterface ¶
Bases: Protocol
Tells whether a request presenting an access token proves possession of what it is bound to.
A bearer token is accepted from whoever holds it. A sender-constrained
one names a key or a certificate in its cnf claim (RFC 7800,
Section 3.1), and is accepted only from a request that proves possession
of it: DPoP does it with a signature over the request (RFC 9449), mutual
TLS with the certificate of the handshake (RFC 8705, Section 3). The
token handler says what the token is; this says whether the request
carrying it is the one it was issued to.
check
async
¶
Weigh the request against what access_token says it is bound to.
Parameters:
-
request(ServerRequestInterface) –The request presenting the token.
-
access_token(str) –The token the request presented.
-
claims(Mapping[str, object]) –The claims the token handler read from the access token — the
cnfof RFC 7800, Section 3.1 among them.
Raises:
-
AuthenticationError–When the request does not prove possession of what the token is bound to.
get_challenge ¶
Answer the scheme this constraint's tokens are presented under, and its parameters.
A resource server accepting sender-constrained tokens challenges with the scheme they are presented under, so a client is told how to come back rather than being sent to build a bearer request that would be refused again. The parameters override the ones the authenticator builds itself.
Parameters:
-
error(AuthenticationError | None) –The failure being answered, or
Nonewhen the request carried no access token at all.
Returns:
AuthenticationFailureHandlerInterface ¶
Bases: Protocol
Turns a failed authentication into the response that answers it.
An authenticator delegates its failure reaction here: a handler answers
the request itself — a challenge, a redirect back to a form — and the
response it returns is what the firewall sends. A handler that wants the
entry point's challenge instead is not a failure handler: the authenticator
answers with None when it has none.
on_authentication_failure
async
¶
on_authentication_failure(request: ServerRequestInterface, error: AuthenticationError) -> ResponseInterface
Answer request for the failure error.
AuthenticationSuccessHandlerInterface ¶
Bases: Protocol
Turns a successful authentication into a response, or lets the request go on.
An authenticator delegates its success reaction here: a handler may answer
the request itself — a redirect after a form login — or return None to
let the request reach its endpoint with the token now set.
on_authentication_success
async
¶
on_authentication_success(request: ServerRequestInterface, token: TokenInterface) -> ResponseInterface | None
Answer request for the authenticated token, or return None.
AuthenticationUtils ¶
Reads the last login attempt's error and username off one request.
A login page builds one over the request it is rendering, and reads three things: the error to explain, the username to re-fill, and — when the request is asking a caller who is already authenticated to prove themselves again — which attribute that proof is being asked for.
Read the login form's answers off request.
get_last_authentication_error
async
¶
Return the error the last login attempt failed with, when one was kept.
The request's own state is read first — a failure the flow is still
answering is parked there — and the session second, which is where a
login that redirected back to its form leaves the error for the page
that renders it, rebuilt from the envelope the session keeps; a
session value that is no such envelope answers None. Reading it
off the session takes it away again unless clear_session is
False: an error page shows an error once, not on every reload.
Parameters:
-
clear_session(bool, default:True) –Whether the error read off the session is removed with it, so a reload of the page shows no stale error.
get_last_username
async
¶
Return the username the last login attempt carried, for the form to re-fill.
The request's own state is read first, the session second, and a request that kept no username answers with the empty string — the form renders with an empty field, not with a missing one.
get_re_authentication_attribute
async
¶
Return the attribute a re-authentication is being asked for, when one is.
Reading it does not end the re-authentication — a successful login does, by removing the attribute — so the page still knows what it is asking for when the user mistypes their password. The request's own attribute is read first, then the session, where the entry point that started the re-authentication keeps it across the redirect.
AuthenticatorManager ¶
AuthenticatorManager(authenticators: Sequence[AuthenticatorInterface], token_storage: TokenStorageInterface, event_dispatcher: EventDispatcherInterface, firewall_name: str, logger: LoggerInterface | None = None, expose_security_errors: ExposeSecurityLevel = ExposeSecurityLevel.NONE, required_badges: Sequence[type[BadgeInterface]] = ())
Bases: AuthenticatorManagerInterface, UserAuthenticatorInterface
Runs the authenticators of one firewall and dispatches the events around each step.
The order is fixed and is the whole contract of this class:
- a supports pass asks every authenticator, parking the supporters and the skipped on the request's security state; the first supporter that still applies reads the request into a passport;
- a :class:
~xtr_security_http.event.check_passport_event.CheckPassportEventlets listeners resolve the badges — set the user loader, verify a password; - every badge must report itself resolved, and every required badge must
be present, or a
:class:
~xtr_security_core.exception.BadCredentialsErroris raised; - the user is loaded and a token is created, then an
:class:
~xtr_security_http.event.authentication_token_created_event.AuthenticationTokenCreatedEventlets a listener replace it; - an
:class:
~xtr_security_core.event.authentication_success_event.AuthenticationSuccessEventruns the post-authentication account check; - the token is stored, the authenticator's success handler runs, an
interactive authenticator announces the login through an
:class:
~xtr_security_http.event.interactive_login_event.InteractiveLoginEvent, and a :class:~xtr_security_http.event.login_success_event.LoginSuccessEventlets a listener migrate a password or replace the response.
A failure anywhere never raises: the error is masked to the configured
level, the authenticator's failure handler runs, and a
:class:~xtr_security_http.event.login_failure_event.LoginFailureEvent
lets a listener answer the request. A response from any of them is
returned for the firewall to send; the lack of one means the request goes
on anonymous — the access decision is what turns that into a challenge.
Record the authenticators, the storage, the dispatcher and the policy.
supports ¶
Tell whether an authenticator handles request: True, None or False.
Every authenticator is asked — the pass records the complete picture,
parking the supporters and the skipped on state for the pass that
authenticates, so none is asked twice within one pass. True means
an authenticator definitely applies; None that only lazy ones do,
none of them sure a credential is present; False that none
applies.
Raises:
-
InvalidArgumentError–When one of the authenticators is no :class:
~xtr_security_http.authenticator.authenticator_interface.AuthenticatorInterface— a wiring mistake, not a request failure.
authenticate_request
async
¶
authenticate_request(request: ServerRequestInterface, state: SecurityState) -> ResponseInterface | None
Authenticate request through the supporters the supports pass recorded.
The pass hands its findings over through state — read and removed
here, once — so a second call over the same request finds nothing
parked and leaves it anonymous. Nothing parked at all means no
supports pass ran: the request stays anonymous too.
A lazy authenticator — one whose :meth:supports returned None —
that raises a plain
:class:~xtr_security_core.exception.BadCredentialsError is read as "no
credential presented": it did not apply, so the next authenticator is
tried. Any other failure is a real one, handled without raising: the
request goes on anonymous, and the access decision is what turns that
into a challenge.
execute_authenticators
async
¶
execute_authenticators(authenticators: Sequence[AuthenticatorInterface], request: ServerRequestInterface, state: SecurityState) -> ResponseInterface | None
Run the handed-off authenticators in order, re-checking each first.
The re-check is per authenticator — never the full supports pass
again — because what the request carries may have changed between
the pass and now. A re-check that turned False skips its
authenticator with a note. Only a response ends the run — once one
authenticator answered, no later one is called; an outcome of
None, from a success or a handled failure that answered nothing,
lets the run go on to the next authenticator, and a lazy abstain
(no credential presented) does the same.
execute_authenticator
async
¶
execute_authenticator(authenticator: AuthenticatorInterface, request: ServerRequestInterface, state: SecurityState, *, lazy: bool) -> ResponseInterface | object | None
Carry one authenticator through the sequence, or abstain when it does not apply.
authenticate_user
async
¶
authenticate_user(user: UserInterface, authenticator: AuthenticatorInterface, request: ServerRequestInterface, badges: Sequence[BadgeInterface] = (), attributes: Mapping[str, object] | None = None) -> ResponseInterface | None
Log user in through authenticator, skipping every check.
The caller vouches for the user, so there is nothing to verify: no
passport check, no badge validation, no post-authentication account
check. A self-validating passport is built around the user — a loader
that hands them back — carrying the extra badges and
attributes as given, the authenticator turns it into a token, and
the login finishes exactly as a request-driven one does: the token is
announced, stored, the success handler runs and the login-success
event carries what the storage held before.
handle_authentication_success
async
¶
handle_authentication_success(token: TokenInterface, passport: Passport, request: ServerRequestInterface, authenticator: AuthenticatorInterface, previous_token: TokenInterface | None) -> ResponseInterface | None
Store the token, run the success handler, then announce the login.
An authenticator that reports itself interactive — one a user actively
logs in through, as opposed to a token re-establishing one — announces
the login between the success handler and the login-success event,
under the name
:attr:~xtr_security_http.security_events.SecurityEvents.INTERACTIVE_LOGIN.
handle_authentication_failure
async
¶
handle_authentication_failure(error: AuthenticationError, request: ServerRequestInterface, authenticator: AuthenticatorInterface, passport: Passport | None, state: SecurityState) -> ResponseInterface | None
Answer a failed authentication without ever raising.
The error is masked to the configured level, the authenticator's
failure handler runs first — its answer is what the event carries —
and a listener may replace that answer through the event. A response
from either is returned for the firewall to send; the lack of one
means the request goes on anonymous, and the access decision is what
turns that into a challenge — reading the masked error back off
state, where this step parked it, so the entry point's challenge
can still name what went wrong.
AuthenticatorManagerInterface ¶
Bases: Protocol
Runs a firewall's authenticators over a request, settling on a token or a failure.
Asks each authenticator whether it supports the request, parking what the pass learned — the supporters, the skipped — on the request's security state; the pass that authenticates reads the supporters back off that same carrier, so each authenticator is asked once per pass. It then authenticates through the first supporter that applies, checks the passport, creates and stores the token, and dispatches the events around each step. It answers with a response only when a success or failure handler produced one; otherwise the request goes on with its token set on the storage.
supports ¶
Tell whether any authenticator handles request, recording the pass.
The authenticators that support the request and the ones that do not
are handed to the pass that authenticates through state, the
request's security state, so they are not asked twice.
None means no authenticator is sure yet — a lazy one that would try
only if a credential were present.
authenticate_request
async
¶
authenticate_request(request: ServerRequestInterface, state: SecurityState) -> ResponseInterface | None
Authenticate request through the supporters the pass recorded.
Reads — and removes — what the supports pass parked on state; with
nothing parked, or nothing supporting the request, the request stays
anonymous.
Raises:
-
AuthenticationError–When authentication fails and no failure handler answered it — the firewall turns it into a challenge.
CustomAuthenticationFailureHandler ¶
CustomAuthenticationFailureHandler(handler: AuthenticationFailureHandlerInterface, options: Mapping[str, object])
Bases: AuthenticationFailureHandlerInterface
Delegates a failure answer to the application's own handler, options first.
The wiring knows the firewall's options — where its login page is, which parameter carries a failure path — while the application knows what the answer should look like. This is the seam between them: the options are handed to the handler when they can be (a handler that takes them), and the answer is the handler's own either way.
The wrapper configures a copy of the handler of its own, once, so two
firewalls sharing one handler never answer with each other's options.
The copy is shallow: a handler's set_options must rebind what it
sets, not change state the copies share.
Record the application's handler and the options to hand it.
Parameters:
-
handler(AuthenticationFailureHandlerInterface) –The application's own failure handler, asked last.
-
options(Mapping[str, object]) –The options the wiring collected for the firewall, for a handler that takes them.
on_authentication_failure
async
¶
on_authentication_failure(request: ServerRequestInterface, error: AuthenticationError) -> ResponseInterface
Let the configured copy of the application's handler answer.
CustomAuthenticationSuccessHandler ¶
CustomAuthenticationSuccessHandler(handler: AuthenticationSuccessHandlerInterface, options: Mapping[str, object], firewall_name: str)
Bases: AuthenticationSuccessHandlerInterface
Delegates a success answer to the application's own handler, options first.
The wiring knows the firewall's options and its name — where to return the caller to, which firewall authenticated them — while the application knows what the answer should look like. This is the seam between them: both are handed to the handler when they can be (a handler that takes them), and the answer is the handler's own either way.
The wrapper configures a copy of the handler of its own, once, so two
firewalls sharing one handler never answer with each other's options.
The copy is shallow: a handler's set_options and
set_firewall_name must rebind what they set, not change state the
copies share.
Record the application's handler, the options and the firewall's name.
Parameters:
-
handler(AuthenticationSuccessHandlerInterface) –The application's own success handler, asked last.
-
options(Mapping[str, object]) –The options the wiring collected for the firewall, for a handler that takes them.
-
firewall_name(str) –The firewall that authenticated, for a handler that keys its answers by one.
on_authentication_success
async
¶
on_authentication_success(request: ServerRequestInterface, token: TokenInterface) -> ResponseInterface | None
Let the configured copy of the handler answer.
DefaultAuthenticationFailureHandler ¶
DefaultAuthenticationFailureHandler(http_utils: HttpUtils, options: Mapping[str, object] | None = None, logger: LoggerInterface | None = None, firewall_name: str | None = None)
Bases: AuthenticationFailureHandlerInterface
Answers a failed login with a redirect, keeping the error for the form.
The redirect target is a ladder: a target on the request's own origin the request carried under the configured parameter — a query parameter a page with a login form of its own sets — then the configured failure path, then the login page. The error is kept on the request's session for the page that renders the form again — as the JSON envelope of its public half, never its internal message — and the page the caller came from is kept as the return trip's target when the options ask for it.
The failure_forward option is refused: this stack has no sub-request
to hand the login page to, so the redirect is the only path an answer
takes. A configuration that asks for the forward is a wiring mistake to
report, not a request to answer.
Record the URI machinery, the options, the logger and the firewall's name.
Parameters:
-
http_utils(HttpUtils) –Matches paths and builds the redirect, so the handler names neither a response nor a URI class.
-
options(Mapping[str, object] | None, default:None) –The options the wiring collected, merged over the defaults.
-
logger(LoggerInterface | None, default:None) –Logs the redirect that answers, when one is given.
-
firewall_name(str | None, default:None) –The firewall that failed to authenticate, keying the return trip's target so two firewalls never overwrite each other's.
DefaultAuthenticationSuccessHandler ¶
DefaultAuthenticationSuccessHandler(http_utils: HttpUtils, options: Mapping[str, object] | None = None, logger: LoggerInterface | None = None)
Bases: AuthenticationSuccessHandlerInterface
Answers a successful login with a redirect, by the target ladder.
The target is a ladder: the configured default, when the options say it always wins; a target on the request's own origin the request carried under the configured parameter; the path the interrupted request saved on the session — read and removed, a return trip happens once; the page of the request's own origin the caller came from, when the options ask for it; then the configured default.
Record the URI machinery, the options and the logger.
Parameters:
-
http_utils(HttpUtils) –Matches paths and builds the redirect, so the handler names neither a response nor a URI class.
-
options(Mapping[str, object] | None, default:None) –The options the wiring collected, merged over the defaults.
-
logger(LoggerInterface | None, default:None) –Logs a parameter the ladder ignored, when one is given.
set_options ¶
Merge options over the defaults, and answer from the merge.
get_firewall_name ¶
Return the firewall whose login this handler answers, when one is set.
set_firewall_name ¶
Record firewall_name, keying the session's saved target path.
on_authentication_success
async
¶
on_authentication_success(request: ServerRequestInterface, token: TokenInterface) -> ResponseInterface | None
Answer with a redirect to the target the ladder picks.
ExposeSecurityLevel ¶
Bases: Enum
How much of the real reason an authentication failure may reveal.
Telling a client precisely why authentication failed helps an attacker: that a user exists, or that an account is merely disabled rather than unknown, is a way to probe. This level decides how much leaks out; anything hidden is reported to the client as plain bad credentials.
NONE— reveal nothing: unknown users and account-status failures alike become bad credentials. The safe default.ACCOUNT_STATUS— reveal that an account is disabled, locked or expired, but still hide whether a user exists.ALL— reveal every failure as it happened. For development.
UserAuthenticatorInterface ¶
Bases: Protocol
Authenticates a known user outside the request-driven flow.
Where the manager's request-driven pass reads a credential off a request, this starts from the user itself — a login form that already loaded the user, a command that switches to one — and lets one authenticator finish the login: create the token, store it, run the success handler and announce the login. The passport check, badge validation and the post-authentication account check are skipped: the caller vouches for the user, so there is nothing to verify.
authenticate_user
async
¶
authenticate_user(user: UserInterface, authenticator: AuthenticatorInterface, request: ServerRequestInterface, badges: Sequence[BadgeInterface] = (), attributes: Mapping[str, object] | None = None) -> ResponseInterface | None
Log user in through authenticator over request.
Parameters:
-
user(UserInterface) –The user to authenticate, already loaded and vouched for.
-
authenticator(AuthenticatorInterface) –The one authenticator to finish the login with.
-
request(ServerRequestInterface) –The request the login answers, as a message.
-
badges(Sequence[BadgeInterface], default:()) –Extra badges the passport carries, beyond the user's.
-
attributes(Mapping[str, object] | None, default:None) –Extra attributes the passport carries, handed to the token and its listeners.
Returns:
-
ResponseInterface | None–The response the success handler or a login-success listener
-
ResponseInterface | None–produced, or
Nonewhen the request goes on.
AbstractAuthenticator ¶
Bases: AuthenticatorInterface
The parts of an authenticator every kind shares.
Turns a resolved passport into a
:class:~xtr_security_http.authenticator.token.post_authentication_token.PostAuthenticationToken
carrying the user and its roles, and answers both on_authentication_*
hooks with None — letting the request go on. A concrete authenticator
overrides :meth:supports and :meth:authenticate, and either hook when
it wants to answer the request itself.
create_token
async
¶
Build a post-authentication token for the passport's user and roles.
The user is read through the passport, which caches what the passport check already loaded, so this call does no I/O.
on_authentication_success
async
¶
on_authentication_success(request: ServerRequestInterface, token: TokenInterface, firewall_name: str) -> ResponseInterface | None
Answer nothing: the request goes on to its endpoint.
on_authentication_failure
async
¶
on_authentication_failure(request: ServerRequestInterface, error: AuthenticationError) -> ResponseInterface | None
Answer nothing: the failure is turned into a challenge elsewhere.
AbstractLoginFormAuthenticator ¶
Bases: AbstractAuthenticator, AuthenticationEntryPointInterface, InteractiveAuthenticatorInterface
The parts every form-login authenticator shares.
A subclass names its login page's URL — :meth:get_login_url, the one
abstract part — and reads the submitted form into a passport. The
request the form is submitted by is decided here: a POST whose path is
exactly the login page's, compared strictly, so the URL the subclass
names must be a path; a subclass that builds an absolute one overrides
:meth:supports too.
A failed login keeps its error for the page that renders the form again and returns the caller to the login page; a protected page reached without logging in is redirected there by the entry point this class also is. And the login is the user's own act — announced as one, through the interactive-login event.
Record the URI machinery that builds this login's redirects.
Parameters:
-
http_utils(HttpUtils) –Builds the redirect responses, so the class names no response class.
get_login_url ¶
Return the URL of the login page — abstract here, concrete in a subclass.
The default :meth:supports compares this value, as it is returned,
with the request's path, so it must be a path (/login); a
subclass that builds an absolute URL overrides :meth:supports too.
supports ¶
Handle the request only when it is the form's submission.
A POST whose path is exactly the login page's — the comparison is
strict, so :meth:get_login_url must return a path — is the form's
submission; anything else is not, and says why when the tooling is
listening.
on_authentication_failure
async
¶
on_authentication_failure(request: ServerRequestInterface, error: AuthenticationError) -> ResponseInterface | None
Keep the error for the form that renders again, and return to the login page.
The error is kept on the request's session — the one place the
redirect's target and the page that renders it share — under the
key a login page reads through
:class:~xtr_security_http.authentication.authentication_utils.AuthenticationUtils,
as the JSON envelope of its public half: a session holds JSON, and
the internal message has no place outside the process.
start
async
¶
start(request: ServerRequestInterface, error: AuthenticationError | None = None) -> ResponseInterface
Redirect the caller to the login page.
The error that led here needs no explaining on the form: the caller never submitted one, so there is nothing to explain yet.
is_interactive ¶
Announce the login as the user's own act: a form is submitted by hand.
AbstractPreAuthenticatedAuthenticator ¶
AbstractPreAuthenticatedAuthenticator(user_provider: UserProviderInterface, token_storage: TokenStorageInterface, firewall_name: str, logger: LoggerInterface | None = None)
Bases: AbstractAuthenticator, InteractiveAuthenticatorInterface
The parts every pre-authenticated authenticator shares.
A subclass reads the username its way — :meth:extract_username, the one
abstract part — and everything else is decided here. A request whose
reading yields no username is skipped, and so is one whose user already
holds a pre-authenticated token for this firewall: the token from the
session says everything a new one would. The passport states what makes
this kind of authentication different — the user was authenticated
before the passport was built, so it wears a
:class:~xtr_security_http.authenticator.passport.badge.pre_authenticated_user_badge.PreAuthenticatedUserBadge
and carries no credentials to check — and the token it settles on is a
:class:~xtr_security_core.authentication.token.pre_authenticated_token.PreAuthenticatedToken.
A failure clears the firewall's pre-authenticated token: whatever the token vouched for, the request that could not re-establish it invalidates it. And the login reports itself interactive — the user's own request established it, and the interactive-login announcement is how the rest of the flow learns that.
Record the provider, the storage, the firewall and the logger.
Parameters:
-
user_provider(UserProviderInterface) –Loads the user the request already names.
-
token_storage(TokenStorageInterface) –Read for a token that already vouches for the same user, and cleared when a failure invalidates one.
-
firewall_name(str) –The firewall this authenticator runs for; a token of another firewall is never its to clear.
-
logger(LoggerInterface | None, default:None) –Names what the authenticator skipped and cleared, when one is given.
extract_username ¶
Return the username the request already carries as proven.
The one abstract part: each pre-authenticated authenticator reads the
request its own way. None says the request carries no such user —
the authenticator is skipped — and a
:class:~xtr_security_core.exception.BadCredentialsError says the
request claimed to carry one and turned out not to: also a skip, but
one that clears any token the failure invalidates.
supports ¶
Handle the request when it names a user this firewall has not settled yet.
The reading is tried first: no user, or one the reading refuses, skips the authenticator — and a refusal clears the token it invalidates. A user who already holds a pre-authenticated token for this firewall skips it too: the token from the session vouches for everything a new one would. Anything else is this authenticator's request, and says why not when the tooling is listening.
authenticate
async
¶
Read the username again, and build the passport around the provider.
The reading runs here too, rather than being handed over from
:meth:supports: a request message cannot be changed in place, and
the pass that authenticates is handed the request as it arrived, not
the one the supports pass read. The reading is the request's own
environment, so reading it again answers what it answered before.
Raises:
-
BadCredentialsError–When the request no longer names a user — a caller that ran
authenticateon a request the reading cannot even begin on.
create_token
async
¶
Build a pre-authenticated token for the passport's user and roles.
The user is read through the passport, which caches what the passport check already loaded, so this call does no I/O.
on_authentication_failure
async
¶
on_authentication_failure(request: ServerRequestInterface, error: AuthenticationError) -> ResponseInterface | None
Clear the token the failure invalidates, and answer nothing.
The request goes on anonymous — the access decision is what turns that into a challenge.
is_interactive ¶
Report the login as the user's own act: their request established it.
AccessTokenAuthenticator ¶
AccessTokenAuthenticator(handler: AccessTokenHandlerInterface, extractor: AccessTokenExtractorInterface, responses: ResponseFactoryInterface, user_provider: UserProviderInterface | None = None, success_handler: AuthenticationSuccessHandlerInterface | None = None, failure_handler: AuthenticationFailureHandlerInterface | None = None, realm: str | None = None, resource_metadata_uri: str | None = None, sender_constraint: SenderConstraintInterface | None = None)
Bases: AbstractAuthenticator, FallbackAuthenticationEntryPointInterface
Authenticates a request by a bearer access token, and challenges when it is absent or bad.
An extractor reads the token out of the request; a handler validates it and
returns a user badge. The passport is self-validating — the token already
proved the user — so no credentials are checked. The granted scopes,
read from the badge's scope or scp attribute, become the token's
oauth2_scope attribute, the one
:class:~xtr_security_http.authorization.oauth2_scope_voter.OAuth2ScopeVoter
reads. A sender constraint, when one is configured, checks the request
against what the token says it is bound to before anything is loaded on
the user's behalf, and its scheme and parameters are the challenge's.
A failed authentication is always answered here: a 401 whose
WWW-Authenticate names invalid_token and says why. As the
firewall's stand-in entry point it also answers an unauthenticated
request with the RFC 6750 challenge that carries no error code — an
error code describes a token the client did send; it only stands in, so
a firewall holding an entry point that starts an authentication keeps
that one.
Attributes:
-
realm–The protection realm named in the challenge, when set.
Record the handler, extractor, response factory, optional peers and challenge settings.
Parameters:
-
handler(AccessTokenHandlerInterface) –Validates a token into a user badge.
-
extractor(AccessTokenExtractorInterface) –Reads the token out of a request.
-
responses(ResponseFactoryInterface) –Builds the challenge responses the entry point answers with, so the authenticator names no response class.
-
user_provider(UserProviderInterface | None, default:None) –Loads the user an identifier names, when the badge the handler returned carries no loader of its own — or one marked as a stand-in.
-
success_handler(AuthenticationSuccessHandlerInterface | None, default:None) –Reacts to a successful authentication, or
None. -
failure_handler(AuthenticationFailureHandlerInterface | None, default:None) –Reacts to a failed authentication, or
None. -
realm(str | None, default:None) –The protection realm named in the challenge, or
None. -
resource_metadata_uri(str | None, default:None) –The RFC 9728 protected-resource metadata URL the challenge advertises; a path is resolved against the request.
-
sender_constraint(SenderConstraintInterface | None, default:None) –What the request has to prove possession of, beyond holding the access token, for it to be accepted;
Noneaccepts a token from whoever presents it, which is what a bearer token is (RFC 6750, Section 1).
extractor
property
¶
Return the extractor that reads the token out of a request.
supports ¶
Answer lazily: None, whether or not the request carries a token.
Upstream answers False when its extractor finds no token,
collecting the reason; the local extractor's read is async and this
hook is sync, so the miss is answered one step later instead —
authenticate raises the no-token error and the manager's lazy
abstain skips this authenticator, leaving the request anonymous
exactly as a False would.
authenticate
async
¶
Read and validate the token, and build a self-validating passport.
The sender constraint, when one is configured, weighs the request against what the token says it is bound to before anything is loaded on the user's behalf.
Raises:
-
AuthenticationError–When no token is present, the handler rejects the one that is, or the request does not prove possession of what the token is bound to.
create_token
async
¶
Build the token and copy the passport's scope onto it as oauth2_scope.
on_authentication_success
async
¶
on_authentication_success(request: ServerRequestInterface, token: TokenInterface, firewall_name: str) -> ResponseInterface | None
Delegate to the success handler, or let the request go on.
on_authentication_failure
async
¶
on_authentication_failure(request: ServerRequestInterface, error: AuthenticationError) -> ResponseInterface
Answer the failure: the handler's response, or the invalid_token challenge.
A configured failure handler answers for this authenticator. Without
one the failure is answered here and now — a 401 naming
invalid_token and saying why — so a refused token is told it was
refused, rather than waiting for the access decision to challenge an
anonymous request.
start
async
¶
start(request: ServerRequestInterface, error: AuthenticationError | None = None) -> ResponseInterface
Answer an unauthenticated request with the RFC 6750 challenge.
The challenge of a request that carried no token at all holds no
error code — an error code describes a token the client did send —
so this is the bare challenge through which an RFC 9728 client
discovers where to get a token from. A token that was rejected is
the failure hook's to answer, with invalid_token.
AuthenticatorInterface ¶
Bases: Protocol
One way of authenticating a request, from a bearer token to a form post.
A firewall runs its authenticators in order. Each is asked whether it
:meth:supports the request; the first that does authenticates it,
producing a passport the manager checks and turns into a token. The two
on_authentication_* hooks let an authenticator answer the request
itself — a redirect on success, a challenge on failure — rather than
letting the request go on to its endpoint.
supports ¶
Tell whether this authenticator handles request.
True authenticates it and stops the others; False skips it;
None authenticates it but lets a later authenticator try too if
this one produces no token — a lazy authenticator with no credential
present in the request.
authenticate
async
¶
Read request into a passport, before any badge is resolved.
Raises:
-
AuthenticationError–When the request cannot even be read into a passport — a malformed token, a missing field.
create_token
async
¶
Turn a resolved passport into the token authentication settles on.
on_authentication_success
async
¶
on_authentication_success(request: ServerRequestInterface, token: TokenInterface, firewall_name: str) -> ResponseInterface | None
React to a successful authentication, optionally answering the request.
on_authentication_failure
async
¶
on_authentication_failure(request: ServerRequestInterface, error: AuthenticationError) -> ResponseInterface | None
React to a failed authentication, optionally answering the request.
FallbackUserLoader ¶
FallbackUserLoader(inner: Callable[..., UserInterface | Awaitable[UserInterface] | None] | None = None)
Wraps a user loader the wiring must not override, and marks it as such.
An authenticator that knows how to load its own user — a token's claims
naming one, a link signing one — hands its badge a loader wrapped here,
and the wiring leaves it alone. Called, the wrapper answers as the loader
it wraps — a coroutine when the loader is an async one, which the badge
awaits; wrapped around None, it answers with no user, the badge's own
way of saying the wiring should not load one at all.
Wrap inner, the loader the badge owns.
FormLoginAuthenticator ¶
FormLoginAuthenticator(http_utils: HttpUtils, user_provider: UserProviderInterface, success_handler: AuthenticationSuccessHandlerInterface, failure_handler: AuthenticationFailureHandlerInterface, options: Mapping[str, object] | None = None)
Bases: AbstractLoginFormAuthenticator, ReAuthenticationEntryPointInterface
Authenticates a form's submission: a username and a password.
The form is submitted to the configured check path — a POST there, a form content type when the options demand one — and its fields are read by the configured names. The username is kept on the session for the form that renders again, the passport carries a password credential with badges for the method, the remember-me conditions and — when the options enable it — the cross-site request forgery token the form presented, and the token the login earns is a username-password one.
The answers are delegated: a success to the success handler, a failure to the failure handler. A re-authentication — a caller already authenticated, asked to prove themselves again — ends with the login form, the caller's identifier kept on the session for it.
Record the form's shape and the handlers that answer its login.
Parameters:
-
http_utils(HttpUtils) –Matches the check path and builds the redirects.
-
user_provider(UserProviderInterface) –Loads the user the form's username names.
-
success_handler(AuthenticationSuccessHandlerInterface) –Answers a successful login.
-
failure_handler(AuthenticationFailureHandlerInterface) –Answers a failed one.
-
options(Mapping[str, object] | None, default:None) –The form's field names and paths, merged over the defaults;
login_path— the page the form lives on — is required, the one option with no default to fall back on.
Raises:
-
InvalidArgumentError–When
optionscarries nologin_path— the wiring must name the page the form lives on.
get_login_url ¶
Return the URI of the page the form lives on.
supports ¶
Handle the request only when it is this form's submission.
The method is weighed when the options demand a POST, the path must be the configured check path, and the content type a form's when the options demand one; anything else says why when the tooling is listening.
authenticate
async
¶
Read the form's submission into a passport.
The username is trimmed and kept on the session for the form that renders again; the password is read but never kept anywhere but the credential that verifies it. A field that is missing, empty or not a string at all fails the login as a bad credential — the form is answered, not the request rejected.
create_token
async
¶
Build a username-password token for the user the form's submission proved.
on_authentication_success
async
¶
on_authentication_success(request: ServerRequestInterface, token: TokenInterface, firewall_name: str) -> ResponseInterface | None
End any re-authentication this login answered, then let the handler answer.
Whether or not a login page read the attribute, the re-authentication is over: the caller proved themselves, so the attribute that named what they were being asked for is removed.
on_authentication_failure
async
¶
on_authentication_failure(request: ServerRequestInterface, error: AuthenticationError) -> ResponseInterface
Let the failure handler answer.
start_re_authentication
async
¶
start_re_authentication(request: ServerRequestInterface, token: TokenInterface) -> ResponseInterface
Send the caller to the login form to type their password again.
Their identifier and the attribute they were denied for are kept on
the session for the login page, so the form re-fills the identifier
and the page knows what it is asking for. They land back on the
resource they were denied as long as the success handler uses the
target path saved before this — which always_use_default_target_path
and a _target_path of the form both outrank.
HttpBasicAuthenticator ¶
HttpBasicAuthenticator(realm_name: str, user_provider: UserProviderInterface, responses: ResponseFactoryInterface, logger: LoggerInterface | None = None)
Bases: AbstractAuthenticator, AuthenticationEntryPointInterface
Authenticates the basic credentials a request's Authorization header carries.
The header's Basic scheme carries the username and the password
base64-encoded — the colon inside them splits the two, and a password
may itself carry colons. The passport carries a password credential
with a badge for the method, and the token the login earns is a
username-password one.
Record the realm, the provider, the response factory and the logger.
Parameters:
-
realm_name(str) –The protection realm named in the challenge, so the caller's agent can label the prompt it shows.
-
user_provider(UserProviderInterface) –Loads the user the credentials' username names.
-
responses(ResponseFactoryInterface) –Builds the challenge responses, so the class names no response class.
-
logger(LoggerInterface | None, default:None) –Logs a failed attempt, when one is given.
start
async
¶
start(request: ServerRequestInterface, error: AuthenticationError | None = None) -> ResponseInterface
Answer with the 401 that asks for basic credentials.
The challenge names the realm, and carries the no-store directives
every challenge this package writes does, so a shared cache never
keeps a 401 and replays it to another caller.
supports ¶
Handle the request only when it carries basic credentials.
A request without them is not failed — it simply has nothing for this authenticator to read, and says so when the tooling is listening.
authenticate
async
¶
Read the header's credentials into a passport.
create_token
async
¶
Build a username-password token for the user the credentials proved.
on_authentication_failure
async
¶
on_authentication_failure(request: ServerRequestInterface, error: AuthenticationError) -> ResponseInterface | None
Log the failed attempt, then answer with the challenge again.
InteractiveAuthenticatorInterface ¶
Bases: Protocol
An authenticator a user actively logs in through.
A user performs the login themselves — a form submitted, a login link
followed — as opposed to a session or a bearer token re-establishing the
same user passively. The manager asks :meth:is_interactive once a login
through this authenticator succeeded; one that reports itself interactive
announces the login through an
:class:~xtr_security_http.event.interactive_login_event.InteractiveLoginEvent,
under
:attr:~xtr_security_http.security_events.SecurityEvents.INTERACTIVE_LOGIN,
so a listener hears the user's own act wherever the credential came from.
is_interactive ¶
Tell whether a login through this authenticator is the user's own act.
True has the manager announce the login through the
interactive-login event; False, or not implementing this
interface, leaves the login unannounced.
JsonLoginAuthenticator ¶
JsonLoginAuthenticator(http_utils: HttpUtils, user_provider: UserProviderInterface, responses: ResponseFactoryInterface, success_handler: AuthenticationSuccessHandlerInterface | None = None, failure_handler: AuthenticationFailureHandlerInterface | None = None, options: Mapping[str, object] | None = None)
Bases: AbstractAuthenticator, InteractiveAuthenticatorInterface
Authenticates a JSON document: a username and a password, statelessly.
The document is the request's parsed body — a JSON object, its two
fields read by the configured paths — and the login answers as a
machine reads it: no redirect to a form, a 401 carrying the error's
message when no failure handler is given. The passport carries a
password credential with badges for the method and the remember-me
conditions — a copy of the document's own fields, the password erased
from it — and the token the login earns is a username-password one.
Record the document's shape and the handlers that answer its login.
Parameters:
-
http_utils(HttpUtils) –Matches the check path, when one is configured.
-
user_provider(UserProviderInterface) –Loads the user the document's username names.
-
responses(ResponseFactoryInterface) –Builds the
401a failure without a handler answers with, so the class names no response class. -
success_handler(AuthenticationSuccessHandlerInterface | None, default:None) –Answers a successful login, or
Noneto let the request reach its endpoint with the token now set. -
failure_handler(AuthenticationFailureHandlerInterface | None, default:None) –Answers a failed one, or
Noneto answer with a401carrying the error's message. -
options(Mapping[str, object] | None, default:None) –Where the username and the password live in the document, merged over the defaults.
supports ¶
Handle the request only when its body is a JSON document.
The content type names the JSON body; the path must be the configured check path, when one is configured. Anything else says why when the tooling is listening.
authenticate
async
¶
Read the document into a passport.
A served request is born with its body unread, and its parsed body
answers only what a read has yielded, so a JSON body — by the rule
:meth:supports weighs the content type by — is read before the
document is asked for. The two fields are read by their configured
paths — a dotted path walks into a nested document — and the
remember-me parameters are a copy of the document, the password
erased from it: the conditions a listener reads are the document's
own fields, never the password, and the document the request carries
— the very one the route behind the firewall reads — is left as it
arrived. A field that is missing, empty or not a string at all fails
the login as a bad credential.
create_token
async
¶
Build a username-password token for the user the document proved.
on_authentication_success
async
¶
on_authentication_success(request: ServerRequestInterface, token: TokenInterface, firewall_name: str) -> ResponseInterface | None
Let the handler answer, or the request reach its endpoint.
on_authentication_failure
async
¶
on_authentication_failure(request: ServerRequestInterface, error: AuthenticationError) -> ResponseInterface | None
Let the handler answer, or answer with a 401 carrying the error's message.
is_interactive ¶
Announce the login as the user's own act: a document is submitted by hand.
LoginLinkAuthenticator ¶
LoginLinkAuthenticator(login_link_handler: LoginLinkHandlerInterface, http_utils: HttpUtils, success_handler: AuthenticationSuccessHandlerInterface, failure_handler: AuthenticationFailureHandlerInterface, options: Mapping[str, object] | None = None)
Bases: AbstractAuthenticator, InteractiveAuthenticatorInterface
Authenticates the request that follows a login link.
The link is followed at the configured check path — by a POST there,
when the options demand one — and its user parameter names who the
link was signed for. The link itself is the whole proof: the badge's
loader spends it through the handler, so the passport validates
itself around the user the spent link loads, wearing the remember-me
badge a login this convenient is asked to outlive its session by.
The answers are delegated: a success to the success handler, a
failure to the failure handler.
Record the handler, the utils, the answer handlers and the options.
Parameters:
-
login_link_handler(LoginLinkHandlerInterface) –Spends the link the request presents and loads the user it signs in.
-
http_utils(HttpUtils) –Matches the check path.
-
success_handler(AuthenticationSuccessHandlerInterface) –Answers a successful login.
-
failure_handler(AuthenticationFailureHandlerInterface) –Answers a failed one.
-
options(Mapping[str, object] | None, default:None) –The link's shape, merged over the defaults;
check_path— where a followed link arrives — is required, the one option with no default to fall back on.
Raises:
-
InvalidArgumentError–When
optionscarries nocheck_path, or names where a link arrives by a route name.
supports ¶
Handle the request that arrives at the check path.
The method is weighed when the options demand a POST, and the path must be the configured check path; anything else says why when the tooling is listening.
authenticate
async
¶
Read the link's user parameter, and build the passport around spending it.
The user is loaded by spending the link — the handler's check is the proof — so the badge's loader consumes it and hands back the user it signed in, wrapped as the badge's own loader so the wiring leaves it alone. The passport validates itself: there is no credential beyond the link, which the handler already checked.
Raises:
-
InvalidLoginLinkAuthenticationError–When the request carries no
userparameter — a caller that ranauthenticateon a request the link's reading cannot even begin on.
on_authentication_success
async
¶
on_authentication_success(request: ServerRequestInterface, token: TokenInterface, firewall_name: str) -> ResponseInterface | None
Let the success handler answer.
on_authentication_failure
async
¶
on_authentication_failure(request: ServerRequestInterface, error: AuthenticationError) -> ResponseInterface
Let the failure handler answer.
is_interactive ¶
Report the login as the user's own act: they followed the link.
RememberMeAuthenticator ¶
RememberMeAuthenticator(remember_me_handler: RememberMeHandlerInterface, token_storage: TokenStorageInterface, cookie_name: str, logger: LoggerInterface | None = None)
Bases: AbstractAuthenticator, InteractiveAuthenticatorInterface
Re-establishes the user a remember-me cookie remembers.
Runs when the request carries the cookie and nothing else already has — a session that expired, a login the cookie outlived. The cookie is read into its details and spent through the handler: the handler's check is the whole proof, so the passport validates itself around the user the spent cookie loads, and the token the login settles on is a remembered one — authenticated, but a trust resolver tells it apart from a fully proven login.
Presenting a cookie is no explicit act of the user's, yet the login it re-establishes has been announced as an interactive one for as long as the flow has existed, and the listeners that react to a user coming back — one updating a last-login date — rely on the announcement; so this authenticator reports itself interactive, as it always has.
Record the handler, the storage, the cookie's name and the logger.
Parameters:
-
remember_me_handler(RememberMeHandlerInterface) –Spends the cookie the request presented and loads the user it remembers.
-
token_storage(TokenStorageInterface) –Holds the request's token, read to keep this authenticator from overwriting one a session already stored.
-
cookie_name(str) –The name the cookie travels under.
-
logger(LoggerInterface | None, default:None) –Where the flow's decisions are logged, or
None.
supports ¶
Answer whether the request presents a cookie worth spending.
A request whose storage already holds a token is authenticated —
the cookie must not overwrite it. One whose state staged the
cookie's clearing — a logout in flight — must not spend what the
same request is dropping. A request with no cookie, or an empty
one, has nothing to spend. Anything else presents a cookie this
authenticator handles lazily: None, so a later authenticator
may still run when this one yields no token.
authenticate
async
¶
Read the cookie into details, and build the passport around spending it.
The user is loaded by spending the cookie — the handler's check is the proof — so the badge's loader consumes it and hands back the user it remembered. The passport validates itself: there is no credential beyond the cookie, which the handler already checked.
Raises:
-
BadMethodCallError–When the request carries no cookie — a caller that ran
authenticatewithoutsupportshaving found one. -
AuthenticationError–When the cookie does not read into the details a handler wrote, or the handler refuses to spend it.
create_token
async
¶
Build a remembered token for the user the spent cookie loaded.
on_authentication_failure
async
¶
on_authentication_failure(request: ServerRequestInterface, error: AuthenticationError) -> ResponseInterface | None
Log the failure by what it says about the cookie, and answer nothing.
A theft is not logged here — the handler already raised it loudly, and the error's own reporting is the record that matters. The request goes on anonymous: the access decision is what turns that into the entry point's challenge.
is_interactive ¶
Report the login as the user's own act, as the flow always has.
RemoteUserAuthenticator ¶
RemoteUserAuthenticator(user_provider: UserProviderInterface, token_storage: TokenStorageInterface, firewall_name: str, user_key: str = 'REMOTE_USER', logger: LoggerInterface | None = None)
Bases: AbstractPreAuthenticatedAuthenticator
Authenticates the user the server in front of the application names.
A server that authenticated the request before the application saw it — a reverse proxy against the company directory, a gateway by source address — writes the account it identified as into the environment the request arrives with, under one key. This authenticator reads that key: the value it finds is the username, taken as proven because the server in front already vouched for it.
Record the provider, the storage, the firewall and the environment key.
Parameters:
-
user_provider(UserProviderInterface) –Loads the user the environment names.
-
token_storage(TokenStorageInterface) –Read for a token that already vouches for the same user, and cleared when a failure invalidates one.
-
firewall_name(str) –The firewall this authenticator runs for.
-
user_key(str, default:'REMOTE_USER') –The environment key the server in front wrote the authenticated account under.
-
logger(LoggerInterface | None, default:None) –Names what the authenticator skipped and cleared, when one is given.
extract_username ¶
Read the account the server in front authenticated, from the environment.
A request whose environment does not carry the key is refused: the server in front never vouched for anyone. A key whose value is empty reads as no user — the request goes unauthenticated rather than failing on it.
Raises:
-
BadCredentialsError–When the environment carries no
user_key.
TraceableAuthenticator ¶
Bases: AuthenticatorInterface, InteractiveAuthenticatorInterface
Wraps an authenticator and records each answer it gives.
The wiring swaps an authenticator for one of these when the tooling needs to explain a firewall's decision: which authenticator supported the request, what passport it built, how long that took, whether it authenticated and what it failed with. The wrapper changes nothing about the flow — every call is passed through as it came — it only listens.
The wrapped authenticator is stored as given, never unwrapped here: the
event getters and the manager's logs open the wrapper where they want the
real authenticator's name, so :meth:get_authenticator is the only door.
The duration is read off the injected clock as the wall-clock delta, in float seconds. The clock rule mandates the injectable clock, so tests can freeze it; a monotonic reading would survive NTP steps, but the duration of a debug trace tolerates the wall clock, and the rule keeps one time source for the package.
Wrap authenticator with every record empty, timing it on clock.
Parameters:
-
authenticator(AuthenticatorInterface) –The authenticator to wrap and record.
-
clock(ClockInterface | None, default:None) –The clock reading the authentication's start and end; the system clock when
None.
supports ¶
Record the wrapped answer, collecting any reasons for a negative one.
A fresh :class:UnsupportedReasons rides the request — under
:attr:~xtr_security_http.security_request_attributes.SecurityRequestAttributes.UNSUPPORTED_REASONS
— for exactly this call, so the wrapped authenticator can explain
itself while it answers; the attribute is gone again by the time the
caller sees the answer.
authenticate
async
¶
Record the passport the wrapped authenticator built, and how long.
create_token
async
¶
Pass through, so the wrapped authenticator builds the token.
on_authentication_success
async
¶
on_authentication_success(request: ServerRequestInterface, token: TokenInterface, firewall_name: str) -> ResponseInterface | None
Record that the wrapped authenticator authenticated, then pass through.
on_authentication_failure
async
¶
on_authentication_failure(request: ServerRequestInterface, error: AuthenticationError) -> ResponseInterface | None
Record the failure the wrapped authenticator answered, then pass through.
get_authenticator ¶
Return the wrapped authenticator, the one the wiring really runs.
is_interactive ¶
Answer for the wrapped authenticator, so tracing changes no announcement.
A wrapped form login is a form login still: the manager asks here, and the interactive-login announcement fires exactly as it would without the wrapper — which is the wrapper's whole contract, that every call is passed through as it came.
get_info ¶
Return everything recorded about the wrapped authenticator so far.
TraceableAuthenticatorManagerListener ¶
TraceableAuthenticatorManagerListener(listener: AuthenticatorManagerListener, recorder: Callable[[TraceableAuthenticator], None] | None = None)
Bases: AbstractListener
Wraps a manager listener and records each authenticator the pass chose.
The wiring swaps a firewall's manager listener for one of these when the
tooling needs to explain an authentication: which authenticators the
supports pass chose and skipped, and what each of them answered. The
wrapper changes nothing about the flow — every call is passed through as
it came — it only listens: the supporters the pass parked on the
request's state are re-parked as
:class:~xtr_security_http.authenticator.debug.traceable_authenticator.TraceableAuthenticator
wrappers, so the pass that authenticates records what each authenticator
does while it runs it.
The wrapped listener is stored as given, never unwrapped here:
:meth:get_authenticator_manager_listener is the only door.
A recorder is handed each recording wrapper as the supports pass
records it, so tooling that keeps its own record of the request — the
profiler's — reads what the authenticator answered once it has run.
Wrap listener with nothing recorded yet.
Parameters:
-
listener(AuthenticatorManagerListener) –The manager listener the chain runs.
-
recorder(Callable[[TraceableAuthenticator], None] | None, default:None) –Called with each recording wrapper, in the order asked, or
Noneto keep them here alone.
supports
async
¶
Record the authenticators the wrapped supports pass chose and skipped.
The supporters are re-parked as traceable wrappers, so the pass that authenticates runs the recording ones; the skipped are only recorded, the pass that authenticates never reads them.
authenticate
async
¶
Pass through, so the wrapped listener authenticates.
get_authenticator_manager_listener ¶
Return the wrapped listener, the one the wiring really runs.
get_authenticators_info ¶
Return what each recorded authenticator answered, in the order asked.
UnsupportedReasons ¶
Collects the reasons an authenticator declined to support a request.
A traceable wrapper parks one of these on the request — under
:attr:~xtr_security_http.security_request_attributes.SecurityRequestAttributes.UNSUPPORTED_REASONS
— for the duration of the wrapped authenticator's supports call, so
the authenticator can explain a negative answer while it gives it:
.. code-block:: python
reasons = request.get_attribute(SecurityRequestAttributes.UNSUPPORTED_REASONS)
if isinstance(reasons, UnsupportedReasons):
reasons.add("the request carries no bearer token")
The attribute is absent otherwise, so explaining costs nothing when nobody is listening.
Start with no reasons collected.
X509Authenticator ¶
X509Authenticator(user_provider: UserProviderInterface, token_storage: TokenStorageInterface, firewall_name: str, user_key: str = 'SSL_CLIENT_S_DN_Email', credentials_key: str = 'SSL_CLIENT_S_DN', logger: LoggerInterface | None = None, credential_user_identifier: str = 'emailAddress')
Bases: AbstractPreAuthenticatedAuthenticator
Authenticates the user the server verified a certificate for.
A request the server accepted on a client certificate arrives with what the server verified of it in the environment: the email the certificate names, ready to use, and the whole distinguished name the certificate was issued under. This authenticator reads the email first, and the configured identifier out of the distinguished name when the email is not there — the username is whichever the certificate carries.
Record the provider, the storage, the firewall and the certificate keys.
Parameters:
-
user_provider(UserProviderInterface) –Loads the user the certificate names.
-
token_storage(TokenStorageInterface) –Read for a token that already vouches for the same user, and cleared when a failure invalidates one.
-
firewall_name(str) –The firewall this authenticator runs for.
-
user_key(str, default:'SSL_CLIENT_S_DN_Email') –The environment key the server wrote the verified certificate's email under.
-
credentials_key(str, default:'SSL_CLIENT_S_DN') –The environment key the server wrote the whole distinguished name under.
-
logger(LoggerInterface | None, default:None) –Names what the authenticator skipped and cleared, when one is given.
-
credential_user_identifier(str, default:'emailAddress') –The distinguished-name identifier the username is read out of when the email key is absent;
emailAddressalso answers its dotted OID spelling.
extract_username ¶
Read the user the request's certificate identifies, from the environment.
The email key is read first, as it is; the distinguished name is searched for the configured identifier when the email is not there, and the value it carries becomes the username, whitespace trimmed. A request whose environment carries neither — or a name that carries no such identifier — is refused.
Raises:
-
BadCredentialsError–When the environment carries neither certificate key, or the name carries no such identifier.
Passport ¶
Passport(user_badge: UserBadge, credentials: CredentialsInterface, badges: Iterable[BadgeInterface] = (), attributes: Mapping[str, object] | None = None)
What an authenticator produced from a request, before a token exists.
A passport always carries a
:class:~xtr_security_http.authenticator.passport.badge.user_badge.UserBadge
naming the user and a credential to verify for them, plus any number of
other badges — a note to upgrade a password, a token to check. Listeners
resolve the badges during the passport check; :meth:get_user loads the
user through the user badge. Attributes are a scratch space listeners and
the authenticator share while building the token.
Badges are keyed by class: a passport carries at most one of each kind.
Record the user badge, the credentials and any other badges.
add_badge ¶
Attach badge under badge_class, and return self.
Badges are keyed by class: a passport carries at most one of each kind,
and a later badge replaces the earlier one under the same key. The key
defaults to type(badge) — the exact runtime class — and may be
given explicitly, so a custom badge can stand in for a built-in one.
has_badge ¶
Tell whether a badge of badge_class is attached.
get_badge ¶
Return the badge attached under badge_class, or None when none is.
The lookup is by key: a badge attached under an explicit class — a custom badge standing in for a built-in — is found under that class.
get_badges ¶
Return every badge attached, keyed by class.
get_user_badge ¶
Return the user badge every passport carries.
Raises:
-
AuthenticationServiceError–When no user badge is attached, which only a hand-built passport could lack.
get_user
async
¶
Load the user through the user badge once, and return it cached.
Raises:
-
AuthenticationServiceError–When no user badge is attached.
get_attribute ¶
Return the attribute name, or default when it is not set.
set_attribute ¶
Attach value under name on the passport.
get_attributes ¶
Return every attribute attached to the passport.
SelfValidatingPassport ¶
SelfValidatingPassport(user_badge: UserBadge, badges: Iterable[BadgeInterface] = (), attributes: Mapping[str, object] | None = None)
Bases: Passport
A passport for a user proven before it was built.
A bearer token was verified by its handler, so there are no credentials to
check — only the user it names. The passport check still runs: the account
checks apply, and a badge the authenticator did not resolve still fails
it. A
:class:~xtr_security_http.authenticator.passport.badge.pre_authenticated_user_badge.PreAuthenticatedUserBadge
is attached only by an authenticator that pre-authenticated the user
itself — never here, or the account checks would be silently skipped for
every self-validating authentication.
Record the user badge and any other badges, keyed by their class.
The parent constructor requires a credential to verify; this passport exists because there is none, so the badge bookkeeping is done here rather than through it.
AuthenticationMethodBadge ¶
Bases: BadgeInterface
Names the methods an authenticator verified for this attempt.
An authenticator that proves how the caller authenticated — a password, a one-time passcode — records each proof here, and the listener that collects authentication proofs reads them off the token. The names are deduplicated in the order they were given; at least one is required, since a badge claiming no method says nothing.
Record the verified methods, deduplicated, keeping their order.
Parameters:
-
methods(str, default:()) –The names of the authentication methods verified.
Raises:
-
InvalidArgumentError–When no method is given.
BadgeInterface ¶
Bases: Protocol
One fact about an authentication, resolved before a token is made.
A passport is a bag of badges: the user's identifier, the password to verify, a note that a password should be upgraded. Each badge starts unresolved and is marked resolved by whoever handles it — a listener on the passport-check event, or the badge itself when it needs nothing. Every badge must report itself resolved by the time the check is done, or authentication fails.
is_resolved ¶
Tell whether this badge has been handled and needs nothing more.
CsrfTokenBadge ¶
Bases: BadgeInterface
Carries the CSRF token a request presented, for the listener that checks it.
An authenticator whose form carries a CSRF token adds this badge with the token's identifier — a different one per authenticator — and the value the request presented. The listener that protects against cross-site request forgery compares the two and marks the badge resolved; until then the passport check fails, so a request that skipped the check cannot authenticate.
Record the token's identifier and the value the request presented.
Parameters:
PasswordUpgradeBadge ¶
PasswordUpgradeBadge(plaintext_password: str, password_upgrader: PasswordUpgraderInterface | None = None)
Bases: BadgeInterface
Carries the plaintext and the place to write its upgraded hash to.
Added to a passport when a password verified against an outdated hash, so the migrating listener can re-hash the plaintext with the current algorithm and hand it to an upgrader to store. It resolves on its own — an upgrade is opportunistic, never a condition of authentication.
Attributes:
-
plaintext_password–The verified plaintext, to be re-hashed.
-
password_upgrader–Where the fresh hash is written, when one is known.
Record the plaintext and, when known, where to store its new hash.
PreAuthenticatedUserBadge ¶
Bases: BadgeInterface
States that the user was already authenticated elsewhere.
A bearer token was verified by its handler before ever reaching a passport; there are no credentials on the passport to check. This badge stands for that fact — it is resolved from the moment it exists, so the credentials listener knows there is nothing to verify.
is_resolved ¶
Report resolved always: a pre-authenticated user needs no check.
RememberMeBadge ¶
Bases: BadgeInterface
Marks an authentication as one a remember-me cookie may outlive.
The badge's presence alone creates no cookie: the listener that checks the
remember-me conditions enables it — when the application asks for it
always, or the request carries the remember-me parameter — and the
listener that responds then sets the cookie. An authenticator that already
knows better can :meth:enable or :meth:disable it itself.
Attributes:
-
parameters–What the listener reads to decide — the parameter name, whether the application always wants the cookie.
Record the parameters the remember-me conditions are checked with.
UserBadge ¶
UserBadge(identifier: str, user_loader: Callable[..., UserInterface | Awaitable[UserInterface] | None] | None = None, attributes: Mapping[str, object] | None = None, identifier_normalizer: Callable[[str], str] | None = None)
Bases: BadgeInterface
Names the user an authentication is for, and loads them on demand.
The identifier is what authentication proved — a username, a token's
sub. A loader turns it into a user: passed in by the authenticator, or
set by a user-provider listener during the passport check. Attributes
carried alongside — a token's claims — are handed to the loader, so an
attributes-based provider can build the user from more than the identifier.
The badge needs no resolving of its own — a provider listener setting a
loader is bookkeeping, not a condition; :meth:get_user runs the loader
once and caches the user. An identifier longer than
:data:MAX_USERNAME_LENGTH is refused at construction.
Record the identifier, an optional loader and the attributes.
Parameters:
-
identifier(str) –What authentication proved the caller to be.
-
user_loader(Callable[..., UserInterface | Awaitable[UserInterface] | None] | None, default:None) –Turns the identifier (and attributes) into a user; a provider listener sets one during the check when omitted.
-
attributes(Mapping[str, object] | None, default:None) –Extra data — a token's claims — handed to the loader.
-
identifier_normalizer(Callable[[str], str] | None, default:None) –Applied to the identifier before it is stored, for a provider that folds case or trims it.
Raises:
-
BadCredentialsError–When the identifier is empty.
-
BadCredentialsError–When the identifier is longer than :data:
MAX_USERNAME_LENGTH.
get_loaded_user ¶
Return the user :meth:get_user already loaded, without doing I/O.
Raises:
-
AuthenticationServiceError–When the user has not been loaded yet, which a token being created before the passport check would be.
get_attributes ¶
Return the attributes handed to the loader.
get_user_loader ¶
Return the loader set for this badge, or None.
set_user_loader ¶
set_user_loader(user_loader: Callable[..., UserInterface | Awaitable[UserInterface] | None]) -> None
Set the loader a provider listener resolved for this badge.
get_user
async
¶
Load the user this badge names, once, and return it.
The loader is called with the identifier, and with the attributes when it accepts a second argument. Its result is awaited when it is an awaitable.
Raises:
-
AuthenticationServiceError–When no loader was set, or the loader returned something that is not a user.
-
UserNotFoundError–When the loader reports no such user.
is_resolved ¶
Report resolved always: the badge is never a condition of the check.
CredentialsInterface ¶
Bases: BadgeInterface, Protocol
A credential to verify, carried on a passport as a badge.
A password to check, a signature to validate. It is a
:class:~xtr_security_http.authenticator.passport.badge.badge_interface.BadgeInterface
like any other, unresolved until the listener that knows how verifies it —
at which point it reports resolved and drops whatever secret it held, so a
credential is consumed exactly once.
CustomCredentials ¶
Bases: CredentialsInterface
A credential whose verification an authenticator supplies as a check.
The escape hatch for a scheme the built-in credentials do not cover: the
check is a callable given the credentials and the resolved user, returning
whether they are valid — awaited when it returns an awaitable. The
credentials listener runs it through :meth:execute_custom_checker, which
fails authentication unless the callable returns strictly True.
Attributes:
-
checker–The callable that verifies
credentialsfor a user. -
credentials–The value handed to the checker.
Record the check and the credentials it verifies.
execute_custom_checker
async
¶
Run the check for user, and resolve the credentials only on success.
The checker is called with the credentials and the user; a result that
is an awaitable is awaited. A result other than strictly True —
the checker may also raise its own, more specific error — fails
authentication; the credentials are resolved only when the check
passed, so a failed attempt never reports itself verified.
Raises:
-
BadCredentialsError–When the checker returns anything but
True.
PasswordCredentials ¶
Bases: CredentialsInterface
A plaintext password waiting to be verified.
Carried on a passport for the credentials listener to check against the
user's stored hash. Verifying it calls :meth:mark_resolved, which drops
the plaintext: it is held only until the one check that reads it, never
longer. Reading the plaintext after it is resolved is refused.
Record the plaintext password to verify.
get_password ¶
Return the plaintext to verify, before it is consumed.
Raises:
-
InvalidArgumentError–When the credentials are already resolved and the plaintext has been dropped.
PostAuthenticationToken ¶
Bases: AbstractToken
A user, the firewall that authenticated them, and the roles decided.
The ordinary outcome of a successful authentication. It lives in the core, not only at the HTTP edge, because a worker or a command authenticates the same way — it sets one of these on the token storage without a request ever being involved.
A session keeps it with its firewall beside the roles and the attributes — the tokens an OIDC login stamps on it included, as the plain JSON of the session store.
Attributes:
-
firewall_name–The firewall (or unit of work) that authenticated.
Record the user, the firewall that authenticated them, and their roles.
Raises:
-
InvalidArgumentError–When
firewall_nameis empty.
get_firewall_name ¶
Return the firewall (or unit of work) that authenticated the user.
to_session ¶
Return the roles, the attributes and the firewall, for a session to keep.
from_session
classmethod
¶
from_session(state: Mapping[str, object], user: UserInterface | None, decode_token: Callable[[object], TokenInterface | None]) -> Self
Rebuild the token a session kept, its firewall included.
Raises:
-
InvalidArgumentError–When a field of
stateis missing or of the wrong type, or the firewall is empty.
AccessDeniedHandlerInterface ¶
Bases: Protocol
Shapes the response to a caller who is known but not allowed.
A firewall hands a denial here when the caller is fully authenticated —
the answer is a refusal, not a challenge. A handler may return a response
of its own, or None to leave the firewall to answer with a plain
403.
handle
async
¶
Return the response that refuses request, or None for a plain refusal.
InsufficientScopeAccessDeniedHandler ¶
InsufficientScopeAccessDeniedHandler(responses: ResponseFactoryInterface, realm: str | None = None, inner: AccessDeniedHandlerInterface | None = None, resource_metadata_uri: str | None = None, sender_constraint: SenderConstraintInterface | None = None)
Bases: AccessDeniedHandlerInterface
Answers a denied scope check with 403 and a bearer scope challenge.
When a bearer token is valid but lacks a scope a resource requires, RFC
6750 says the answer is 403 with a WWW-Authenticate header naming
error="insufficient_scope" and the scope the resource needs — and
nothing in the body: the header carries all there is to say, so no scope
detail leaks anywhere else. A denial no OAuth2 scope took part in is not
this handler's to answer: it goes to the handler the application
configured inside this one, or to the regular handling when it
configured none, so a firewall mixing scopes with roles keeps answering
the latter the way the application asked for.
Attributes:
-
realm–The protection realm named in the challenge, when set.
Record the response factory and every part the challenge is built from.
Parameters:
-
responses(ResponseFactoryInterface) –Builds the challenge responses this handler answers with, so it names no response class.
-
realm(str | None, default:None) –The protection realm named in the challenge, or
None. -
inner(AccessDeniedHandlerInterface | None, default:None) –Answers the denials no OAuth2 scope took part in, or
Noneto leave them to the regular handling. -
resource_metadata_uri(str | None, default:None) –Where the protected-resource metadata is published (RFC 9728, Section 5.1) — a client denied for a missing scope is the one that most needs to find the authorization server again — or
Noneto name none. -
sender_constraint(SenderConstraintInterface | None, default:None) –What the firewall binds its access tokens to, which names the scheme of this challenge as it names the one of a
401, orNoneforBearer.
handle
async
¶
Answer a scope shortfall with 403 and its challenge; leave the rest to inner.
The scopes every denied attribute asked for are merged — a denial may
name several scope requests — and a denial that asked for none is not
a scope shortfall at all: it goes to inner, which answering
None hands back to the regular access-denied handling.
OAuth2ScopeVoter ¶
Bases: CacheableVoterInterface
Grants OAUTH2_SCOPE(...) when the token carries every scope asked for.
A bearer token keeps the scopes it was issued with in the oauth2_scope
attribute — a sequence, or a single space-separated string. This voter reads
an OAUTH2_SCOPE(a b) attribute and grants only when every scope in it is
among the token's. A token that carries no scopes at all is denied: a scope
request it cannot satisfy is a denial, not a question left to the others —
abstaining would let it through under an allow_if_all_abstain manager.
get_required_scopes
staticmethod
¶
Read the scopes an attribute requires, all of which are required.
The one reader of the scope-request shape: the vote below, the
exception listener and the insufficient-scope handler all ask it here,
so they agree on what a scope request is. An attribute that is not
shaped like one — or names no scopes, which would grant every scoped
token vacuously — reads as None, so a caller leaves another
voter's attribute alone and abstains on a malformed one rather than
silently honouring it.
vote
async
¶
vote(token: TokenInterface, subject: object, attributes: Sequence[object], vote: Vote | None = None) -> Access
Grant when the token holds every asked-for scope; deny when it falls short.
supports_attribute ¶
Tell whether attribute asks for OAuth2 scopes, by its prefix alone.
The prefix is all a firewall needs to know — that this attribute is one this voter reads, not another voter's — so a malformed scope request still routes here and is abstained on by the vote, rather than being routed nowhere and silently honoured.
supports_type ¶
Vote on any subject: scopes are read from the token alone.
CurrentToken ¶
Bases: Depends
Injects the token the request authenticated into an endpoint parameter.
Used as Annotated[TokenInterface, CurrentToken()] — for an endpoint
that decides something itself off the roles or the attributes
authentication settled on. The marker is pure metadata; the reading of the
request's security state happens in the injectable
:class:~xtr_security_http.resolver.security_token_resolver.SecurityTokenResolver
the thin dependency delegates to.
By default the parameter must have a token: an anonymous request raises
:class:~xtr_security_core.exception.AuthenticationCredentialsNotFoundError,
which becomes a 401. Passing optional=True — for a parameter typed
TokenInterface | None — returns None for an anonymous request
instead. The dependency never appears in the generated schema.
Attributes:
-
optional(bool) –Whether an anonymous request yields
Noneinstead of raising.
Inject the current token, optionally nullable.
CurrentUser ¶
CurrentUser(user_class: type | tuple[type, ...] | None = None, *, optional: bool = False, disabled: bool = False)
Bases: Depends
Injects the current user into an endpoint parameter.
Used as Annotated[User, CurrentUser()]. The marker is pure metadata —
what the argument wants — and the reading of the request's security state
happens in the injectable
:class:~xtr_security_http.resolver.user_value_resolver.UserValueResolver
the thin dependency delegates to.
By default the parameter must have a user: an anonymous request raises
:class:~xtr_security_core.exception.AuthenticationCredentialsNotFoundError,
which becomes a 401. Passing optional=True — for a parameter typed
User | None — returns None for an anonymous request instead. When
user_class is given (one class, or several as a tuple for a union), a
user of another class raises
:class:~xtr_security_core.exception.UnsupportedUserError. Passing
disabled=True switches the resolution off for this one parameter —
the dependency yields None without reading the request — for an
application that enables the resolver globally but excludes a route.
(The web framework does not hand a dependency the annotation of the
parameter it fills, so nullability and the expected class are stated on
the marker rather than read from User | None.)
The dependency never appears in the generated schema.
Attributes:
-
optional(bool) –Whether an anonymous request yields
Noneinstead of raising. -
user_class(type | tuple[type, ...] | None) –The class (or tuple of classes) a user must be, or
Noneto accept any. -
disabled(bool) –Whether this marker's resolution is switched off.
Inject the current user, optionally typed, nullable, and disablable.
FirewallListenerOrder ¶
FirewallListenerOrder(*, before: type | str | Sequence[type | str] = (), after: type | str | Sequence[type | str] = ())
Declares the firewall listeners a listener runs before or after.
Used on a listener class::
@FirewallListenerOrder(after=ContextListener, before=AccessListener)
class TwoFactorListener(AbstractListener): ...
A listener's get_priority() is kept: these constraints only
reorder the listeners that share it, and one that would need a
listener to cross a priority fails the build instead of silently
moving it. This way a listener cannot displace the chain's own
ordering by mistake — it can only settle how it stands against the
ones it runs beside.
A target is a listener class, its "module:Class" name, or the
qualifier it runs under in the firewall's chain. One naming a
listener that is not in the chain is ignored — the package adding
it may simply not be installed.
Declare the neighbours, a single target or a sequence of them per direction.
IsCsrfTokenValid ¶
IsCsrfTokenValid(token_id: str, *, token_key: str = '_token', methods: str | Sequence[str] = (), token_source: int = SOURCE_PAYLOAD)
Bases: Depends
Requires the request to present the value minted for a token id.
Used as a dependency or a decorator, like
:class:~xtr_security_http.decorator.is_granted.IsGranted. The marker is
pure metadata — which token id a route proves, where the request carries
the value, which methods it applies to — and the checking happens in the
injectable
:class:~xtr_security_http.resolver.csrf_token_checker.CsrfTokenChecker
the thin dependency delegates to, which hands the presented value to the
token manager.
A request that presents no value, or one the manager does not vouch for,
is refused with a 403. The sources are a bitmask: the default reads
the payload (the JSON body, else the parsed form); SOURCE_QUERY and
SOURCE_HEADER widen it, and several combine — the first source named
that carries a value wins. A marker that names no method applies to every
one; a marker that names GET also answers HEAD.
Attributes:
-
token_id(str) –The id the token is known under — what it guards.
-
token_key(str) –The key the request carries the value under.
-
methods(tuple[str, ...]) –The (upper-cased) methods the check applies to; empty is all.
-
token_source(int) –The bitmask of the sources the value is read from.
Require the value minted for token_id, read as token_source says.
IsGranted ¶
IsGranted(attribute: str | Callable[..., bool | Awaitable[bool]], subject: str | Callable[..., object] | None = None, *, message: str | None = None, status_code: int | None = None, exception_code: int | None = None, methods: str | Sequence[str] = (), consume_security_scopes: bool = False)
Bases: Depends
Requires an attribute over a subject before the endpoint runs.
Written as a dependency or a decorator:
@router.delete("/books/{isbn}")
@IsGranted("ROLE_ADMIN") # below the route decorator
async def delete_book(isbn: str) -> None: ...
@router.put("/books/{isbn}", dependencies=[IsGranted("BOOK_EDIT", subject=load_book)])
async def edit(book: Annotated[Book, Depends(load_book)]) -> Book: ...
The marker is pure metadata — what must be granted, over what, and how a
denial answers — and the deciding happens in the injectable
:class:~xtr_security_http.resolver.is_granted_checker.IsGrantedChecker
the thin dependency delegates to, which runs the attribute through the
access-decision machinery.
The attribute is a string a voter matches, or a callable
(IsGrantedContext, subject) -> bool the closure voter runs. The subject
is None, the name of a path parameter, or a callable used as a FastAPI
dependency — resolved once per request and shared with the endpoint. A
denial raises an
:class:~xtr_security_core.exception.AccessDeniedError, which the firewall's
exception listener turns into 401 or 403; a status_code answers
with that status directly instead. It requires a firewall to have run;
without one the check is made against the anonymous token.
methods limits the check to those (upper-cased; GET extends to
HEAD); a marker that names none applies to every method. The security
scopes a route declared natively are ignored unless
consume_security_scopes=True: opted in, the request's accumulated
scopes are decided through the voter stack too, each one an attribute that
must be granted; without it they stay declaration and documentation, and
adding this marker to a chain never silently turns them into enforcement.
Attributes:
-
attribute(object) –The attribute required.
-
subject(object) –How the subject is obtained, or
None. -
message(str | None) –The denial message.
-
status_code(int | None) –The status a denial answers with directly, or
None. -
exception_code(int | None) –A code recorded on the marker for the caller that catches the denial.
-
methods(tuple[str, ...]) –The (upper-cased) methods the check applies to; empty is all.
-
consume_security_scopes(bool) –Whether the request's accumulated security scopes are decided too.
Require attribute over subject before the endpoint runs.
IsGrantedContext ¶
IsGrantedContext(token: TokenInterface, user: UserInterface | None, authorization_checker: AuthorizationCheckerInterface)
Bases: AuthorizationCheckerInterface
The token, its user, and an authorization checker to ask further questions.
A closure attribute (see
:class:~xtr_security_core.authorization.voter.closure_voter.ClosureVoter)
receives one of these and the subject. It has the token and its user to
reason about directly, :meth:is_granted to ask a nested question for the
same token — "may this token edit this book?" — and shortcuts for the
authentication-strength questions.
Attributes:
-
token(TokenInterface) –The token the decision is being made for.
-
user(UserInterface | None) –The token's user, or
Nonewhen nobody is authenticated.
Record the token, its user, and the checker nested questions go to.
is_granted
async
¶
is_granted(attribute: object, subject: object = None, access_decision: AccessDecision | None = None) -> bool
Answer a nested access question for the same token.
is_authenticated_fully
async
¶
Tell whether the token is fully authenticated.
is_authenticated_recently
async
¶
Tell whether the user authenticated recently.
is_authenticated_very_recently
async
¶
Tell whether the user authenticated very recently.
is_impersonator
async
¶
Tell whether the user is impersonating another user.
AuthenticationEntryPointInterface ¶
Bases: Protocol
Answers an unauthenticated request with what it takes to authenticate.
When a request reaches a protected resource without proving who is calling,
the firewall's entry point turns that into a response: a 401 carrying
the challenge a bearer scheme expects, a redirect to a login form. The
error that led here, when there is one, shapes the challenge.
start
async
¶
start(request: ServerRequestInterface, error: AuthenticationError | None = None) -> ResponseInterface
Return the response that asks request to authenticate.
Parameters:
-
request(ServerRequestInterface) –The request that reached a protected resource.
-
error(AuthenticationError | None, default:None) –The authentication error that led here, when one did, so the challenge can name why — a bad token, insufficient scope.
FallbackAuthenticationEntryPointInterface ¶
Bases: AuthenticationEntryPointInterface
An entry point that only stands in for a firewall declaring no other one.
An authenticator wears this marker when it can answer an unauthenticated request with a meaningful challenge, but has no authentication to start — a bearer challenge names the scheme, it does not begin a login — and must therefore never win over an entry point that does, a login form say. A firewall that holds one of each keeps picking the other, so an authenticator gaining a fallback entry point never makes an existing firewall ambiguous.
Having no authentication to start, it also gets no target path saved for it: answering an unauthenticated request through it never starts a session, so there is nothing for the caller to come back to.
The base contract is restated here because a marker a runtime check reads
— the exception listener asking which entry point it holds — cannot be a
Protocol the check would answer True for regardless. An entry point
that stands in inherits this and answers start its own way.
start
async
¶
start(request: ServerRequestInterface, error: AuthenticationError | None = None) -> ResponseInterface
Return the response that asks request to authenticate.
Parameters:
-
request(ServerRequestInterface) –The request that reached a protected resource.
-
error(AuthenticationError | None, default:None) –The authentication error that led here, when one did, so the challenge can name why — a bad token, insufficient scope.
ReAuthenticationEntryPointInterface ¶
Bases: Protocol
Starts a fresh authentication for a user who is already authenticated.
This is deliberately not an
:class:~xtr_security_http.entry_point.authentication_entry_point_interface.AuthenticationEntryPointInterface:
that one answers "who are you?", and an existing session already satisfies
it, so reusing it would send the caller to a login page that lets them
straight back through. Here the caller is known, and the only thing being
asked for is a fresh proof that they still hold their credentials — which
is why the token is passed rather than an error.
An entry point may implement this beside its own contract, in which case the firewall uses it for both without any extra configuration.
Pairs with the recency attributes
:attr:~xtr_security_core.authorization.voter.authenticated_voter.AuthenticatedVoter.IS_AUTHENTICATED_RECENTLY
and
:attr:~xtr_security_core.authorization.voter.authenticated_voter.AuthenticatedVoter.IS_AUTHENTICATED_VERY_RECENTLY,
and with the
:attr:~xtr_security_http.security_request_attributes.SecurityRequestAttributes.RE_AUTHENTICATION_ATTRIBUTE
key the listener parks the asked attribute under.
start_re_authentication
async
¶
start_re_authentication(request: ServerRequestInterface, token: TokenInterface) -> ResponseInterface
Return the response that asks the holder of token to prove themselves again.
Parameters:
-
request(ServerRequestInterface) –The request a recency check refused.
-
token(TokenInterface) –The token the caller already holds, so the fresh proof is asked of a known caller, not an anonymous one.
AuthenticationTokenCreatedEvent ¶
Bases: Event
Announces that a token was created for a passport, before it is put to use.
Dispatched right after an authenticator turned a resolved passport into a
token. A listener may read the passport's badges and attributes and
:meth:set_authenticated_token a token of its own — a richer one carrying
extra claims, say — which then becomes the token authentication settles on.
Not a frozen dataclass: replacing the token is the whole point, so the token it carries is mutable state.
Attributes:
-
passport–The passport the token was created from.
Record the created token and the passport it was made from.
CheckPassportEvent
dataclass
¶
CheckPassportEvent(authenticator: AuthenticatorInterface, passport: Passport, request: ServerRequestInterface | None = None)
Bases: Event
Announces that a passport is ready for its badges to be resolved and checked.
Dispatched once an authenticator has produced a passport, before a token is
made from it. Listeners resolve the badges the authenticator left for them
— a user provider sets a
:class:~xtr_security_http.authenticator.passport.badge.user_badge.UserBadge's
loader, a credentials listener verifies a password — each marking the badge
it handled resolved. Every badge must be resolved by the time the listeners
are done, or authentication fails.
The event is mutable in spirit: a listener reaches into the passport it carries and changes the badges' state. The dataclass itself is frozen — the authenticator and passport it names do not change — but stopping it skips the listeners that have not run, exactly as any event.
Attributes:
-
authenticator(AuthenticatorInterface) –The authenticator that produced the passport.
-
passport(Passport) –The passport whose badges are to be resolved and checked.
-
request(ServerRequestInterface | None) –The request the passport arrived with, when the dispatcher carried it — the checks that read where an attempt came from (throttling) need it;
Nonefor a hand-built event.
CheckRefreshedUserEvent ¶
CheckRefreshedUserEvent(token: TokenInterface, original_user: UserInterface, refreshed_user: UserInterface, user_changed: bool = False)
Bases: Event
Announces that a session token's user was just reloaded from its provider.
Dispatched while the context listener refreshes the token it read from the session, once a provider has reloaded the user, so a listener can weigh in on whether the reload changed the user enough to deauthenticate: an account an administrator disabled during the session, a permission withdrawn since the login. The verdict the listener itself computed — password, roles, identifier — is seeded in, so a listener starts from the built-in answer and may confirm, add its own reason, or clear one it does not want to act on.
Listeners run on every request of a stateful firewall: keep them cheap and free of side effects.
Not a frozen dataclass: a listener changes the verdict.
Attributes:
-
token–The token the session stored, whose user was reloaded.
-
original_user–The user as the session stored it.
-
refreshed_user–The user the provider just reloaded.
Record the reload, seeded with the built-in comparison's verdict.
Parameters:
-
token(TokenInterface) –The token the session stored, whose user was reloaded.
-
original_user(UserInterface) –The user as the session stored it.
-
refreshed_user(UserInterface) –The user the provider just reloaded.
-
user_changed(bool, default:False) –The verdict the listener itself computed — the built-in comparison of password, roles and identifier.
get_token ¶
Return the token the session stored, whose user was reloaded.
get_original_user ¶
Return the user as it was stored in the session.
get_refreshed_user ¶
Return the user as the provider just reloaded it.
is_user_changed ¶
Return the verdict as it stands: whether the token is deauthenticated.
set_user_changed ¶
Deauthenticate the token, or keep it despite what decided otherwise.
A listener adding its own reason hands the error carrying it, for the deauthentication event to pass on; one clearing the verdict clears the reason with it, because a reason with no verdict left is a reason nothing will read.
Parameters:
-
changed(bool) –The new verdict.
-
exception(AuthenticationError | None, default:None) –The reason to deauthenticate, when
changedis true; kept from a previous listener when left out.
get_exception ¶
Return the reason a listener gave to deauthenticate, if one did.
InteractiveLoginEvent
dataclass
¶
Bases: Event
Announces a user's own, interactive login.
A user actively authenticated — a form submitted, a login link followed —
as opposed to a session or a bearer token re-establishing the same user
passively. Dispatched under
:attr:~xtr_security_http.security_events.SecurityEvents.INTERACTIVE_LOGIN
— the one event here that carries a name of its own, because an
application listens for it across the whole flow rather than at one
authenticator — after an interactive authenticator's success handler ran
and before the login-success event. A listener reads the request the user
acted through and the token their login settled on, to stamp a session or
write an audit line; the token is the one the storage now holds, and
cannot be replaced from here.
Attributes:
-
request(ServerRequestInterface) –The request the user logged in through.
-
token(TokenInterface) –The token the login settled on.
LoginFailureEvent ¶
LoginFailureEvent(exception: AuthenticationError, authenticator: AuthenticatorInterface, request: ServerRequestInterface, response: ResponseInterface | None, firewall_name: str, passport: Passport | None = None)
Bases: Event
Announces that authentication failed, and lets a listener answer it.
Dispatched when an authenticator raised — after the error was masked, if
the firewall hides sensitive failures, and after the authenticator's
failure handler ran. A listener reads the error, the passport that got as
far as it did and the response the handler produced, and may
:meth:set_response to answer the failure itself.
Not a frozen dataclass: setting the response mutates it.
Attributes:
-
firewall_name–The firewall the authentication ran under.
Record the failure's whole context, the handler's answer included.
Parameters:
-
exception(AuthenticationError) –The error authentication failed with, masked already when the firewall hides sensitive failures.
-
authenticator(AuthenticatorInterface) –The authenticator that failed to authenticate.
-
request(ServerRequestInterface) –The request that failed to authenticate, as a message.
-
firewall_name(str) –The firewall the authentication ran under.
-
passport(Passport | None, default:None) –The passport, if one was produced before the failure.
-
response(ResponseInterface | None) –The response the failure handler produced, if any — a listener may replace it.
get_authenticator ¶
Return the authenticator that failed, unwrapped from any traceable.
A traceable wrapper is stored as given — the wiring decides what the manager runs — but a listener reading the event wants the real authenticator, so the wrapper is opened here rather than at construction.
get_request ¶
Return the request that failed to authenticate, as a message.
get_passport ¶
Return the passport, if one was produced before the failure.
get_response ¶
Return the response a listener set to answer the failure, if any.
set_response ¶
Answer the failure with response instead of the failure handler.
LoginSuccessEvent ¶
LoginSuccessEvent(authenticator: AuthenticatorInterface, passport: Passport, token: TokenInterface, request: ServerRequestInterface, response: ResponseInterface | None, firewall_name: str, previous_token: TokenInterface | None = None)
Bases: Event
Announces that authentication succeeded, was stored, and produced a response.
Dispatched after the token has been set on the storage and the authenticator's success handler has run. A listener reads the passport — to migrate an outdated password hash, to write an audit line — and may replace the response the success handler produced with one of its own.
Not a frozen dataclass: a listener replacing the response mutates it.
Attributes:
-
authenticator–The authenticator that authenticated the request.
-
firewall_name–The firewall the authentication ran under.
Record the login's whole context, the token the storage held included.
Parameters:
-
authenticator(AuthenticatorInterface) –The authenticator that authenticated the request.
-
passport(Passport) –The passport authentication settled on.
-
token(TokenInterface) –The token authentication settled on.
-
request(ServerRequestInterface) –The request that authenticated, as a message.
-
response(ResponseInterface | None) –The response the success handler produced, if any.
-
firewall_name(str) –The firewall the authentication ran under.
-
previous_token(TokenInterface | None, default:None) –The token the storage held before this login set its own — what a listener migrating a session compares against.
get_authenticator ¶
Return the authenticator that authenticated the request, unwrapped.
A traceable wrapper is stored as given — the wiring decides what the manager runs — but a listener reading the event wants the real authenticator, so the wrapper is opened here rather than at construction.
get_authenticated_token ¶
Return the token authentication settled on.
get_previous_token ¶
Return the token the storage held before this login, if any.
get_user ¶
Return the user the passport loaded, the login's whole point.
get_request ¶
Return the request that authenticated, as a message.
get_response ¶
Return the response the success handler produced, if any.
set_response ¶
Replace the response the login produced with response.
LogoutEvent ¶
Bases: Event
Announces that a request asked to log out, and carries its outcome.
Dispatched by the logout listener once the request proved it is asking for a logout — the configured path matched, the cross-site request forgery token checked out — and before the token is cleared, so the listeners of this event still see the token being logged out. Each listener does its own part of the logout — invalidating the session, clearing cookies and tokens, answering the request — and the first response set on the event is the one the request is answered with.
Not a frozen dataclass: a listener answering the logout replaces the response, and the event is the one place that answer gathers.
Record the request asking to log out and the token it logs out.
Parameters:
-
request(ServerRequestInterface) –The request that asked for the logout, as a message.
-
token(TokenInterface | None) –The token the request's storage held, or
Nonewhen it held none — a logout is asked for as readily by a request that never authenticated.
get_request ¶
Return the request that asked for the logout, as a message.
get_token ¶
Return the token being logged out, or None when there is none.
set_response ¶
Answer the logout with response.
The first listener to answer decides the request: the listeners that run after one that set a response see it here and leave it alone.
get_response ¶
Return the response a listener answered the logout with, if any.
SwitchUserEvent ¶
SwitchUserEvent(request: ServerRequestInterface, target_user: UserInterface, token: TokenInterface | None = None)
Bases: Event
Announces a user switching to another, or an impersonation being left.
Dispatched under
:attr:~xtr_security_http.security_events.SecurityEvents.SWITCH_USER
— the second event that carries a name of its own, because an
application listens for a user switch across the whole flow rather
than at one step — once per switch: before the switched-to token is
stored, and once per exit, before the original token is restored. A
listener reads the request the switch was asked through and the user
being switched to, and may replace the token the switch settles on —
the dispatcher's answer is the token the flow stores.
Not a frozen dataclass: a listener replaces the token.
Attributes:
-
request–The request the switch was asked through.
-
target_user–The user being switched to — on an exit, the user returned to.
Record the request, the user being switched to, and the token.
Parameters:
-
request(ServerRequestInterface) –The request the switch was asked through.
-
target_user(UserInterface) –The user being switched to — on an exit, the user returned to.
-
token(TokenInterface | None, default:None) –The token the switch settles on, when the announcer already built it.
get_request ¶
Return the request the switch was asked through.
get_target_user ¶
Return the user being switched to — on an exit, the user returned to.
get_token ¶
Return the token the switch settles on, or None before one is set.
set_token ¶
Replace the token the switch settles on.
A listener may hand the flow a token of its own — one carrying extra roles, say — and the switch stores what the event now carries instead of what it was announced with.
TokenDeauthenticatedEvent
dataclass
¶
TokenDeauthenticatedEvent(original_token: TokenInterface, request: ServerRequestInterface, reason: str | None = None, provider_classes: tuple[type, ...] = (), exception: AuthenticationError | None = None)
Bases: Event
Announces that the token read from the session was deauthenticated.
Dispatched when refreshing the user a session token carried ended in no provider vouching for it — the user changed under the session, or no provider could find it. A listener clears what the login left behind: a remember-me cookie, a session of an upstream provider.
Attributes:
-
original_token(TokenInterface) –The token as the session stored it, before the refresh refused it.
-
request(ServerRequestInterface) –The request the refresh ran for, as a message.
-
reason(str | None) –A sentence explaining the deauthentication, or
None. -
provider_classes(tuple[type, ...]) –The classes of the user providers that contributed to the deauthentication decision.
-
exception(AuthenticationError | None) –The authentication error a listener of the refreshed-user check gave as its reason, when one did.
get_original_token ¶
Return the token as the session stored it, before the refresh refused it.
get_request ¶
Return the request the refresh ran for, as a message.
get_reason ¶
Return the sentence explaining the deauthentication, if there is one.
get_provider_classes ¶
Return the user providers that contributed to the deauthentication.
get_exception ¶
Return the error a refreshed-user listener gave as its reason, if one did.
AuthenticationProofsListener ¶
Bases: EventSubscriberInterface
Records the methods an interactive login proved, and carries proofs across logins.
An interactive login, other than a remember-me one, is recorded at the moment it succeeds: the methods its authentication method badge states are added to whatever the token already holds, the newer entry winning; with no badge, an unspecified method is recorded only when the token holds nothing yet. A remember-me login records nothing — presenting a cookie proves nothing about the credentials — and an authenticator that records its own proofs on the token keeps them, since only a gap is ever filled.
A login whose previous token names the same user carries that token's proofs over, the token's own entries winning, so a second factor proven at login survives a later password re-check.
Record the reader of the current instant, the proofs are stamped with.
Parameters:
-
clock(ClockInterface | None, default:None) –The reader of the current instant. Defaults to the system clock.
get_subscribed_events
classmethod
¶
Listen to a successful, stored login, ahead of the other login-success listeners.
on_login_success
async
¶
Record the login's proofs, then carry the previous token's over.
The proofs are recorded on the authenticated token, and only then is the previous token consulted: the carry-over merges into what the login has just recorded, not the reverse.
CheckCredentialsListener ¶
CheckCredentialsListener(hasher: UserPasswordHasherInterface, dummy_hasher: PasswordHasherInterface)
Bases: EventSubscriberInterface
Verifies the credentials a passport carries, on the passport check.
A PasswordCredentials is verified against the user's stored hash through
the user password hasher, run in a worker thread so the argon2 cost never
blocks the event loop. A match resolves the credentials and adds a
PasswordUpgradeBadge carrying the plaintext — always, not only when
the hash is outdated, so the migrating listener owns that judgement and
rehashes what needs it. When the user is unknown — or known but carrying
no password — a dummy hash is still verified, so the timing of a bad
username, a passwordless user and a wrong password all match and none
reveals which was wrong. The dummy hash is computed once at construction
from the required dummy hasher.
A CustomCredentials is verified by running its own check against the
resolved user.
Record the user password hasher and, for the timing guard, a dummy hasher.
get_subscribed_events
classmethod
¶
Burn for an unknown user before the pre-check, verify after it.
resolve_user
async
¶
Resolve the user a password passport names, burning a dummy on no user.
Runs before the account pre-check, which loads the user too and would
otherwise let a UserNotFoundError escape before the credentials
check could charge the dummy. Only a passport carrying an unresolved
password is touched; a known user is loaded (and cached) with no burn,
leaving the pre-check and the verify to run as before.
Raises:
-
BadCredentialsError–When no user answers the identifier, after a dummy has been burned so the timing matches a wrong password.
check_passport
async
¶
Verify the password and any custom credentials the passport carries.
CheckRememberMeConditionsListener ¶
CheckRememberMeConditionsListener(options: Mapping[str, object] | None = None, logger: LoggerInterface | None = None)
Bases: EventSubscriberInterface
Enables the remember-me badge when a login asked for the cookie.
Three conditions, and only together do they earn a cookie: the passport carries the badge — the authenticator knows a login may be remembered — the firewall configured the feature — this listener runs — and the login asked for it, either because the application always wants the cookie or because the request carried the remember-me parameter. The parameter is read where a submitted form carries it and the query string second, and the badge's own parameters are read first, so an authenticator that already knows the answer — a login link, a token login — states it there.
Runs before the listener that sets the cookie, so the badge it enables is the one that listener reads.
Record the options the conditions are checked with, and the logger.
Parameters:
-
options(Mapping[str, object] | None, default:None) –always_remember_me— the application wants the cookie for every login — andremember_me_parameter— the name the request carries its ask under; merged over the defaults. -
logger(LoggerInterface | None, default:None) –Where the decision is logged, or
None.
get_subscribed_events
classmethod
¶
Listen to a successful login, ahead of the listener that sets the cookie.
on_login_success
async
¶
Enable the badge when the login asked to be remembered.
A passport without the badge is a login through an authenticator that never offered remembering — nothing to enable. With the badge, the ask is checked: always, or the request's parameter.
ClearedCookie
dataclass
¶
ClearedCookie(path: str = '/', domain: str | None = None, secure: bool = False, samesite: str | None = None)
The attributes a cookie was set with, which clearing it must repeat.
A browser tells cookies apart by their name, path and domain together,
so the header that clears one must repeat the path and the domain it was
set with — clearing name alone would leave a cookie set under
another path or domain untouched.
Attributes:
-
path(str) –The path the cookie was set under; the whole site by default.
-
domain(str | None) –The domain the cookie was set to; every host that reads it when
None. -
secure(bool) –Whether the cookie was set to travel only over a secure connection.
-
samesite(str | None) –The cross-site rule the cookie was set with —
"lax","strict"or"none"— orNonewhen it was set with none.
ClearSiteDataListener ¶
Bases: EventSubscriberInterface
Answers a logout with the header that clears the site's client data.
A logout is the moment a browser should forget what the site kept on the
caller — its cache, its cookies, its storage — and the
Clear-Site-Data header is the browser's own way of being told. The
values configured are the directives the header carries, quoted and
comma-joined the way the header reads them: "*" for everything, or
any of "cache", "cookies", "storage",
"clientHints", "executionContexts", "prefetchCache" and
"prerenderCache".
The header is set on the response a listener before this one answered
the logout with — the default logout listener's redirect, typically —
and only when the response does not already carry one: a listener that
answered with its own Clear-Site-Data decided what a browser should
clear, and that decision stands. A logout no listener answered is left
alone — there is no response to carry the header, and the default logout
listener is the one that answers it.
Record the site-data directives the header clears.
Parameters:
-
site_data(Sequence[str], default:('*',)) –The directives the
Clear-Site-Dataheader carries —"*"or a subset of the directive names — quoted and joined when the header is set.
get_subscribed_events
classmethod
¶
Listen to a logout, beside the listeners that answer it.
on_logout
async
¶
Set the site-data header on the response the logout was answered with.
Runs after the default logout listener — the one that answers a logout nothing else answered — so a response is there to carry the header, and before the listeners that only clean up after it.
CookieClearingListener ¶
Bases: EventSubscriberInterface
Answers a logout with the headers that clear the configured cookies.
A logout should drop the cookies the site kept for the caller's
convenience — a remember-me, a preference, a tracking id — and the ones
configured here are cleared on the response the logout was answered with:
a Set-Cookie header dated behind now for each, so the browser drops
it at once. The path and the domain each cookie was set with are the
ones the clearing header repeats, because a browser tells its cookies
apart by all three.
Runs last of the logout's listeners — after the default logout listener answered the request, so there is a response to clear the cookies on, and after the listeners that might still read one.
Record the cookies a logout of this firewall clears.
Parameters:
-
cookies(Mapping[str, ClearedCookie]) –Each cookie to clear, mapped to the attributes it was set with — the path and the domain the clearing header must repeat, the secure flag and the cross-site rule it was set under.
get_subscribed_events
classmethod
¶
Listen to a logout, after every listener that answers or reads it.
on_logout
async
¶
Clear the configured cookies on the response the logout was answered with.
A logout no listener answered carries no response, and there is nothing to clear the cookies on; the headers the response already carries are kept, the clearing ones added beside them.
CsrfProtectionListener ¶
Bases: EventSubscriberInterface
Checks the forgery token a passport's badge carries, on the passport check.
An authenticator whose form carries a forgery token adds a
:class:~xtr_security_http.authenticator.passport.badge.csrf_token_badge.CsrfTokenBadge
naming the token's id and the value the request presented. This listener
hands the pair to the token manager, which compares the value with what
it stored when the page was rendered; a token the manager vouches for
settles the badge, and one it does not fails the login with
:class:~xtr_security_http.exception.invalid_csrf_token_error.InvalidCsrfTokenError
— an authentication failure the manager's failure machinery answers, never
a missing credential.
The badge is all the listener reads: the authenticator already read the request when it built the passport, so the presented value travels on the badge and the listener needs nothing else from the event. A passport with no badge — an authenticator whose form carries no token — is left alone, and so is a badge another listener already settled.
Until the badge is settled it reports unresolved, and the passport check fails on it: a request that skipped this listener cannot authenticate through a form whose token was never checked.
Record the manager that vouches for the values tokens are checked against.
Parameters:
-
csrf_token_manager(CsrfTokenManagerInterface) –Compares a presented token value with the value stored under its id.
get_subscribed_events
classmethod
¶
Listen to the passport check, ahead of the account and credentials checks.
check_passport
async
¶
Vouch for the token the badge carries, then settle the badge.
Raises:
-
InvalidCsrfTokenError–When the request presented no value, or one the manager does not vouch for.
CsrfTokenClearingListener ¶
Bases: EventSubscriberInterface
Clears every stored cross-site request forgery token on a logout.
A token minted for a session answers for the requests of that session — a form rendered to the caller, an action they were asked to confirm — and a logout ends the session's say. The tokens minted under it must not outlive it: a value stolen before the logout would otherwise still vouch after it, so the storage that minted them drops them all.
The storage is the one the firewall's cross-site request forgery protection minted its tokens through, and it is cleared whole: the listener holds no list of its own, because the storage knows what it minted.
Record the storage whose minted tokens a logout drops.
Parameters:
-
csrf_token_storage(ClearableTokenStorageInterface) –The clearable token storage the firewall's cross-site request forgery protection minted through — the one whose every token a logout clears.
get_subscribed_events
classmethod
¶
Listen to a logout, beside the listeners that answer it.
on_logout
async
¶
Drop every token the storage minted.
The storage is the request's own — built over the session the request reattached — so clearing it touches nothing another request minted under a session of its own. The event itself is not read: the tokens to drop are the storage's whole say, not the logout's.
DefaultLogoutListener ¶
Bases: EventSubscriberInterface
Answers a logout with a redirect, when no listener answered it first.
A logout needs an answer — the request asked for one — and the listeners before this one are the ones that may give it their own: a farewell page, a JSON body, a redirect of the application's choosing. This listener is the last word: a logout they left unanswered is answered with a redirect to the configured target, so the caller lands somewhere rather than in the void a request that changed nothing would.
Runs ahead of the listeners that only clear — the session, the cookies, the stored tokens — so they still run after a logout this one answered, and behind the ones that answer with something of their own.
Record where an unanswered logout redirects to.
Parameters:
-
http_utils(HttpUtils) –Builds the redirect, and guards its target against the configured domain rules.
-
target_url(str, default:'/') –Where an unanswered logout redirects to — the home path by default.
get_subscribed_events
classmethod
¶
Listen to a logout, after the listeners that answer it their own way.
on_logout
async
¶
Redirect to the target, unless a listener before this one answered.
The first response wins: a listener that answered the logout before this one decided where the caller lands, and this one leaves it alone.
LoginThrottlingListener ¶
LoginThrottlingListener(limiter: RequestRateLimiterInterface, limiter_name: str | None = None, dispatcher: EventDispatcherInterface | None = None, clock: ClockInterface | None = None)
Bases: EventSubscriberInterface
Throttles the login attempts a request carries, through one request limiter.
On the passport check the attempt is counted, so concurrent attempts past the limit are refused before any password is checked; a failed login counts nothing more. A successful one forgets the account's count — the local one only, the limiter's own asymmetry. A refused attempt is turned away with the core too-many-attempts error, carrying the minutes the caller must wait, and announced as an exceeded rate limit on the dispatcher the listener was given.
Record the limiter, its configured name, and the dispatcher to announce on.
Parameters:
-
limiter(RequestRateLimiterInterface) –The request limiter the attempts count under — one that builds its own keys, such as the :class:
~xtr_security_http.rate_limiter.DefaultLoginRateLimiter. -
limiter_name(str | None, default:None) –The configured limiter's name, for the exceeded event's readers;
Nonewhen the limiter is not a named configuration. -
dispatcher(EventDispatcherInterface | None, default:None) –The dispatcher to announce an exceeded rate limit on, when the listener was given one; the firewall's own, where the rest of the flow announces.
-
clock(ClockInterface | None, default:None) –The reader of the current instant, for turning a refused attempt's wait into minutes.
get_subscribed_events
classmethod
¶
Count the attempt on the passport check first of all; forget on success.
check_passport
async
¶
Count the attempt, and refuse it over the limit before any other check spends anything.
The username the passport names is parked on the request's security state first — the limiter reads its keys from there, and the form that renders again reads the same.
Raises:
-
TooManyLoginAttemptsAuthenticationError–When the attempt is over the limit, carrying the minutes the caller must wait.
on_successful_login
async
¶
Forget the account's count.
The global count, over the address, survives the login: the limiter keeps that asymmetry itself.
OidcBackChannelLogoutListener ¶
Deauthenticates a token whose provider session a back-channel logout ended.
The login stops working on the next request the browser makes. The logout token arrives outside of any request of the end-user, so its arrival can only be written down; this is where it is acted on, the token being the one thing saying which provider session the login belongs to.
It is a plain callable rather than a subscriber, registered by the wiring on the dispatcher the refreshed-user check is announced on: the check runs on every request of a stateful firewall, and this listener is the application's to place — one per firewall, over the ended sessions that firewall's provider pushed.
Running on every firewall does not make it refuse the logins of another:
a token names the firewall it was minted on, and only the listener of
that firewall acts on it. Two providers minting the same opaque sid
for two firewalls would otherwise have one end the logins of the other.
It costs one cache lookup on each request carrying an oidc_sid
attribute, and nothing on the others.
Deauthenticating is where it stops, which is what a password change does too: an application wanting its session invalidated as well reads the session-ended error off the deauthentication event.
Record the ended sessions this firewall's provider pushed.
Parameters:
-
ended_sessions(OidcEndedSessions) –The ended sessions of the provider this firewall logs in through.
-
firewall_name(str) –The firewall whose provider sessions
ended_sessionsrecords.
OidcEndSessionListener ¶
OidcEndSessionListener(discovery: OidcDiscovery, http_utils: HttpUtils, post_logout_redirect_path: str | None = None, logger: LoggerInterface | None = None)
Bases: EventSubscriberInterface
Handles RP-Initiated Logout by redirecting to the provider.
The logout redirects to the end_session_endpoint of the OIDC
provider, so the provider ends its own session of the login too. The
redirect carries the ID token the login keeps as its id_token_hint
— the provider knows from it which session of which client is being
asked to end — and the page to come back to, when one is configured.
Record where the end-session endpoint is read, and how the redirect is built.
Parameters:
-
discovery(OidcDiscovery) –Reads the
end_session_endpointoff the provider's discovery document. -
http_utils(HttpUtils) –Builds the redirect, and writes the URI the post-logout page becomes.
-
post_logout_redirect_path(str | None, default:None) –The page the provider sends the caller back to once it ended its session, or
Noneto leave the landing to the provider. -
logger(LoggerInterface | None, default:None) –Writes the fallback to a local logout, when given.
get_subscribed_events
classmethod
¶
Listen to a logout, ahead of the default logout listener that answers it.
on_logout
async
¶
Redirect to the provider's end-session endpoint, unless a listener answered first.
A login carrying no OIDC ID token is left to the listeners that
answer a local logout. A provider that announces no usable
end_session_endpoint — or one that cannot be reached — leaves
the logout a local one too: the default logout listener answers it,
and logging out of the application never depends on the provider
being up.
PasswordMigratingListener ¶
PasswordMigratingListener(hasher: UserPasswordHasherInterface, password_upgrader: PasswordUpgraderInterface | None = None, logger: LoggerInterface | None = None)
Bases: EventSubscriberInterface
Rehashes and re-stores a password whose old hash the login verified.
A successful password login left a
:class:~xtr_security_http.authenticator.passport.badge.password_upgrade_badge.PasswordUpgradeBadge
on the passport. This listener checks whether the stored hash is
outdated and, when it is, rehashes the plaintext with the current
algorithm in a worker thread and hands the new hash to an upgrader to
store. The upgrader is whichever answers first: the one the badge
carries, the one injected here, or — when the passport's user loader is
a provider's bound method and that provider upgrades passwords — that
provider. The upgrade is best-effort — it runs after the caller is
already authenticated — so a failure is swallowed, and the hash is
upgraded on the next login instead.
Record the hasher, the upgrader used when a badge carries none, and a logger.
RememberMeListener ¶
RememberMeListener(remember_me_handler: RememberMeHandlerInterface, logger: LoggerInterface | None = None)
Bases: EventSubscriberInterface
Answers a login's remember-me ask, and every ending that must drop the cookie.
On a successful login, the cookie is set only when the badge was enabled — the conditions listener's doing — and any cookie the request still carries is cleared first, so a login as another user never leaves the previous one remembered. On a failed login, a logout and a deauthentication, the cookie is cleared: a login that did not happen must not remember one that did, and a session the refresh refused must not be re-established by what it left behind.
Record the handler that sets and clears the cookie, and the logger.
Parameters:
-
remember_me_handler(RememberMeHandlerInterface) –The one voice on what the cookie holds — every set and clear this listener asks for goes through it.
-
logger(LoggerInterface | None, default:None) –Where the decisions are logged, or
None.
get_subscribed_events
classmethod
¶
Listen to a login's both outcomes, and to the endings that drop the cookie.
on_login_success
async
¶
Set the cookie the login asked for, after clearing any it still carried.
A passport without the badge is a login through an authenticator that never offered remembering, and nothing is touched. With the badge, any cookie the request still carries is cancelled first — a login must not leave the previous user remembered — and a badge that was never enabled, the conditions unmet, leaves it at that: cleared, and nothing new staged.
clear_cookie
async
¶
Clear the cookie on an ending that must not leave a login remembered.
SaveSessionListener ¶
Bases: EventSubscriberInterface
Saves the session a stateful request reattached, and stages its cookie.
The session is the one the request's security state carries — the object the context listener built and every step of the request wrote to — so what the chain wrote between requests is what the storage holds. A session that was never started is left entirely alone: nothing was read from it and nothing written, so it saves nothing and mints no cookie — a request that never touched its session must not tell the client to carry one.
The response half saves before the head leaves, so a storage that fails fails the request loudly rather than losing the session quietly, and stages the ID cookie the session says is due — a fresh session, or one a login rotated. The finish half runs on every path, so a request that failed without producing a response still keeps what it wrote; it skips the requests the response half already saved, and stages no cookie — by the finish there is no head left to carry one.
get_subscribed_events
classmethod
¶
Listen to the response, and to the finish that runs on every path.
on_kernel_response
async
¶
Save the parked session, then stage the cookie its ID asks for.
Raises:
-
SessionError–When the storage fails to write the session — before the head leaves, so the failure is the request's to answer, not a loss nobody hears.
on_kernel_finish_request
async
¶
Save the parked session a request that never answered still wrote.
The finish runs whether the request was answered or not; the response half has already saved the answered ones, and its mark is what keeps this from writing the same session twice. A session whose ID still needs its cookie is not saved here: by the finish no head is left to carry the cookie, so the entry would be stored under an ID no client will ever send back.
Raises:
-
SessionError–When the storage fails to write the session.
SessionLogoutListener ¶
Bases: EventSubscriberInterface
Invalidates the session a logging-out request reattached.
A session is what keeps a caller logged in across requests, so a logout ends it: the session is invalidated — its attributes dropped, its stored entry deleted, its ID re-issued — so the next request of the same browser reattaches a session that answers for nobody.
The session is the one the request's security state carries — the one the context listener parked when the request reattached it, the same object the login's session strategy rotates. A logout of a request with no session — a stateless firewall, or a logout outside a stateful chain — has nothing to invalidate, and the listener leaves it at that.
get_subscribed_events
classmethod
¶
Listen to a logout, beside the listeners that answer it.
on_logout
async
¶
Invalidate the session the request's security state carries.
The parked session is how this stack says a request has one: it is the one object the request's halves share, and the one whose invalidation ends the login the request is logging out.
SessionStrategyListener ¶
Bases: EventSubscriberInterface
Rotates the session after a successful login, the way the firewall configured.
A subscriber on the login-success event, on the firewall's own dispatcher: the login has been stored and the success handler has answered, and the request that authenticated is still the one being answered — the moment the session's ID is rotated, so the response re-issues the rotated ID and the token is written back under it.
The listener skips a login that has no session to move: the request whose security state carries no session — a stateless firewall, or a login outside a stateful chain — has nothing the strategy could rotate. It skips a re-authentication of the same account, too: the previous token names the same, non-empty user identifier and is of the same class as the new one, so the session already answers for this account and rotating it would log out the very login it celebrates.
Register it on every stateful firewall's dispatcher, with the strategy the firewall configured.
Record the strategy this firewall's logins hand the session to.
Parameters:
-
session_authentication_strategy(SessionAuthenticationStrategyInterface) –The strategy the firewall configured — what one of its logins does to the session the request reattached.
get_subscribed_events
classmethod
¶
Listen to a successful, stored login.
on_login_success
async
¶
Hand the login's request and token to the strategy, unless it is a re-login.
The strategy is reached with the event's own request and authenticated token, at the default priority a subscriber carries — beside the other listeners of the login-success event, in the order they were added.
UserCheckerListener ¶
Bases: EventSubscriberInterface
Gates a user's own state, before credentials are checked and again after.
Before the credentials check, on the passport check, it loads the user and runs the pre-authentication check — the account must not be disabled or locked to go on — unless the passport states the user was pre-authenticated elsewhere, an authentication that already vouched for the account. After a token is settled, on the success event, it runs the post-authentication check against the user the token carries, when that user is a user at all.
Record the checker the account state is gated by.
get_subscribed_events
classmethod
¶
Check pre-auth on the passport check, post-auth on the success event.
pre_check_credentials
async
¶
Load the user and run the pre-authentication account check.
A passport carrying a PreAuthenticatedUserBadge is skipped: the
user was authenticated before the passport was built, and that
authentication already vouched for the account's state.
post_check_credentials
async
¶
Run the post-authentication account check against the token's user.
A token whose user is not a UserInterface — an anonymous or a
stringly-typed one — has no account state to check.
UserProviderListener ¶
Bases: EventSubscriberInterface
Sets a user badge's loader from the firewall's provider, when it has none.
Runs first on the passport check, so the listeners after it — the early
user resolve, the account check, the credentials check — can load the
user. An authenticator that already gave the badge a loader (a bearer
handler that resolved the user from a token's claims) is left alone. The
provider's load_user_by_identifier is set as the loader directly, so
a badge with attributes reaches an attributes-based provider's
two-argument method and a plain provider's one-argument one — the badge
chooses by the method's own shape.
Record the provider a badge's loader is built from.
ExpiredLoginLinkError ¶
Bases: ExpiredSignatureError, InvalidLoginLinkErrorInterface
A login link whose hash is sound but whose moment has passed.
Derives from the core's expired-signature error — a link's hash is a signature, and everything the core says about one past its expiry holds here — wearing the marker so the flow that refused the link catches it with the rest.
ImpersonationError ¶
Bases: SecurityError, RuntimeError
A generated impersonation address was asked for and could not be built.
Also a :class:RuntimeError. The causes are configuration gaps: no
firewall with a user switch for the request, a switch that asks for a
cross-site request forgery token while no manager was given to mint
one, or a dedicated path configured as a route name, which no routing
component here can resolve.
InvalidAccessTokenError ¶
InvalidAccessTokenError(message: str | None = None, *, message_key: str | None = None, message_data: Mapping[str, object] | None = None)
Bases: AuthenticationError
A bearer access token could not be trusted.
The token was present but malformed, expired, signed with the wrong key,
or otherwise not verifiable. A protected resource answers such a token
with a challenge naming invalid_token.
InvalidCsrfTokenError ¶
InvalidCsrfTokenError(message: str | None = None, *, message_key: str | None = None, message_data: Mapping[str, object] | None = None)
Bases: AuthenticationError
A cross-site request forgery token was presented but could not be vouched for.
The passport carried a token badge, and the value the request presented with it did not match what the token manager stored under the badge's id — or the request presented no value at all. The login the badge was meant to guard is refused: a request the page that rendered the form did not ask for cannot authenticate through it.
InvalidLoginLinkAuthenticationError ¶
InvalidLoginLinkAuthenticationError(message: str | None = None, *, message_key: str | None = None, message_data: Mapping[str, object] | None = None)
Bases: AuthenticationError
A login through a link failed because the link does not check out.
The flow's one authentication-layer answer to every refusal the handler raises: the caller learns the link was invalid or expired, and nothing else — which parameter failed the link's reading stays in the error the handler already raised.
InvalidLoginLinkError ¶
Bases: SecurityError, RuntimeError, InvalidLoginLinkErrorInterface
A request presented a login link the handler cannot accept.
The link's own reading failed — a parameter missing or malformed, a
hash that verifies under no secret, a user the provider does not
know — before any authentication ran; the error names the link, not
a login attempt. The authentication layer's answer to it is
:class:~xtr_security_http.exception.InvalidLoginLinkAuthenticationError.
InvalidLoginLinkErrorInterface ¶
Bases: Exception
An error saying a login link does not check out.
A handler refuses a link for more than one reason — a parameter it cannot read, a hash no secret signs, a moment that has passed — and each refusal raises its own error; the authenticator that hands the link to the handler catches them all with this one base and answers with the single authentication error of its own.
The marker is a class the refused errors inherit, not a Protocol
a runtime check would answer True for regardless: it is caught,
and a catch must name a base the errors actually derive from.
InvalidSessionStrategyError ¶
Bases: SecurityError, RuntimeError
A session strategy was asked to act under a name that is none of its own.
The strategy names — none, migrate, invalidate — are the
application's configuration, carried as a string; one that matches
no name is heard the first time the strategy runs, carrying the name
as it was configured. Also a :class:RuntimeError.
Record the unknown strategy name.
Parameters:
-
strategy(str) –The configured strategy name that matched none of the strategy's own.
get_strategy ¶
Return the configured strategy name that matched none of the strategy's own.
LogoutError ¶
Bases: SecurityError, RuntimeError
A request reached the logout step and failed its proof.
Also a :class:RuntimeError. The one cause today is a cross-site
request forgery token that does not check out: a request that names
the logout path must still prove it came from a page the application
rendered, and one that cannot is refused rather than logged out.
MissingSessionError ¶
Bases: SecurityError, RuntimeError
A session strategy found no session on the request it was asked to move.
The session a strategy moves is the one the request's security state
carries — the context listener's park, built from the request through
the session storage. A request whose state holds none reached a
strategy through a caller that ran no stateful machinery for it, and
the strategy refuses to guess: rotating a session that does not exist
would read as protection while protecting nothing. Also a
:class:RuntimeError.
MissingStateBagError ¶
Bases: SecurityError, RuntimeError
A listener was asked to support a request that carries no state bag.
The caller that runs a firewall's chain parks the kernel event's state
bag on the request it hands to each listener's supports, so a
listener that needs the flow's per-request carrier reaches the one the
event carries. A request without one reached the chain through a caller
that skipped that step, and the listener refuses to guess: a silently
fresh carrier would park the flow's handoffs where the event's readers
never find them. Also a :class:RuntimeError.
UnknownFirewallError ¶
Bases: SecurityError, LookupError
No firewall is configured under the name asked for.
Also a :class:LookupError. Names the firewalls that are configured, so
the mistake — a typo, a firewall never declared — is plain from the error.
Attributes:
-
name(str) –The name that matched no firewall.
-
configured(tuple[str, ...]) –The names that are configured.
Record the unknown name and the names that are configured.
AbstractListener ¶
Bases: FirewallListenerInterface
The parts of a firewall listener every kind shares.
Gives a listener the chain's default priority — 0, the middle
of the road, ahead of the listeners that only clean up and behind
the ones that authenticate — and leaves :meth:supports and
:meth:authenticate to the subclass: no two kinds of listener
decide the same way, so the template decides nothing for them. A
concrete listener overrides both, and :meth:get_priority when
the chain must run it somewhere else.
AccessListener ¶
AccessListener(token_storage: TokenStorageInterface, access_decision_manager: AccessDecisionManagerInterface, access_map: AccessMapInterface, exception_on_no_token: bool = False)
Bases: AbstractListener
Requires of a request whatever its firewall's first matching rule demands.
A chain step: supports asks the access map which rule the request
matches and parks the attributes that rule requires on the request's
security state, answering True when there is something to decide and
None — the lazy join — when there is not, so a public-only or
unmatched request still reaches the step. authenticate reads what
was parked back, decides the token against it with the request itself as
the subject, and raises when the decision refuses.
The token comes from the token storage, a null token standing in for an
anonymous request: the decision, not the listener, is what turns an
anonymous request away from a rule that needs authentication. A
PUBLIC_ACCESS rule is decided like any other — the authenticated
voter grants it for every token, null ones included — so the decision
record explains why the request passed. (Upstream skips a public-only
match on the lazy response event; this kernel has no such event yet, so
the branch has nothing to skip on.)
Until the firewall's chain runs the request, the same rules are decided
the way the firewall runner always has, through :meth:check_access: the
runner hands the token it authenticated, the listener matches the map
again and decides. The two paths share the deciding and the refusal; only
where the token comes from, and where the matched attributes are parked,
differ.
Record the storage, the manager and the rules this step decides with.
Parameters:
-
token_storage(TokenStorageInterface) –Where the step reads the token the request was authenticated under.
-
access_decision_manager(AccessDecisionManagerInterface) –Decides the token against the matched rule's attributes.
-
access_map(AccessMapInterface) –The firewall's rules, matched to find what a request must satisfy.
-
exception_on_no_token(bool, default:False) –A vestigial flag from an older contract, kept to fail loudly in a caller that still passes it: only
Falseis accepted.
Raises:
-
InvalidArgumentError–When
exception_on_no_tokenis true — the step decides an anonymous request against a null token by design, so a caller asking it to refuse one instead is asking for a behaviour this step no longer has.
supports
async
¶
Park what the matched rule requires, and answer whether there is a decision to make.
The attributes are parked on the request's security state — the
carrier the chain's caller reaches through the state bag parked on
the request — for authenticate to read back, so the matching runs
once for both hooks. A rule that requires nothing of the request, or
only public access, still joins the chain lazily: None, not
False, because the step wants its say even when the request's
head committed it to nothing.
authenticate
async
¶
Decide the request against the attributes the supports pass parked.
The parked attributes are read and removed, so a later ask over the same request finds nothing parked and decides nothing. Nothing parked at all means no supports pass ran — the request is left alone, its access decided by whatever the route itself requires.
Raises:
-
AccessDeniedError–When the decision refuses, carrying the attributes, the request as the subject, and the decision.
check_access
async
¶
Decide token against the first rule request matches.
The path the firewall runner drives: it has authenticated the request and hands the token it authenticated, so the step matches the map and decides, parking nothing. A rule that requires only public access short-circuits here — the resource is open, so no decision is made — and a request matching no rule is left alone.
Raises:
-
AccessDeniedError–When a matching rule's attributes are not granted, carrying the attributes, the request as the subject, and the decision.
get_priority
staticmethod
¶
Return the chain position: after authentication, before the cleanup steps.
AuthenticatorManagerListener ¶
AuthenticatorManagerListener(authenticator_manager: AuthenticatorManagerInterface, bridge: StarletteHttpFactoryInterface)
Bases: AbstractListener
Runs a firewall's authenticators over the request, as a chain step.
A thin delegation: the manager's supports pass answers supports, and
the pass that authenticates answers the request — a response it produced
is set on the event, which is also what stops the chain. The listener
decides nothing of its own; skipping it when no authenticator applies is
the chain's job, driven by the answer the manager gave.
The manager's two passes hand each other what they learned through the
request's security state, which rides the event's bag. authenticate
reads it off the event; supports is asked about the request alone,
so the caller running the chain parks that bag on the request it asks
about — the one place both hooks reach the same carrier.
A url-encoded form — a POST encoded as one — is read before the
manager is handed the request: the request the lifecycle serves is born
with its body unread, and its parsed side answers only what a read has
yielded. Reading it first hands the form's fields to whatever asks for
the parsed body without reading the stream — an authenticator, a handler
or a listener of the login written against the message contract alone;
the body stays readable for the route behind the firewall. A multipart
form is not read here: it may be an upload of any size, so it is left to
whoever asks for it — the form login reads its fields when it handles one.
A response the manager produced is a message; the event answers with what the framework sends, so a pure message is converted through the bridge — the kernel's rule for messages from elsewhere — while the kernel's own dual response is set as it is.
Build the chain step over the firewall's manager and the bridge.
Parameters:
-
authenticator_manager(AuthenticatorManagerInterface) –Drives the firewall's authenticators over the request.
-
bridge(StarletteHttpFactoryInterface) –Turns a handler's pure message response into one the event accepts.
supports
async
¶
Answer whether any of the firewall's authenticators applies.
authenticate
async
¶
Authenticate the request, answering it when a handler produced a response.
The request handed to the manager carries the event's bag, parked the
way :meth:supports sees it, so the re-check, the authenticator and
the success and failure hooks all reach the same carrier — a hook
reading the bag off the request finds it in the live chain too.
ChannelListener ¶
ChannelListener(access_map: AccessMapInterface, responses: ResponseFactoryInterface, bridge: StarletteHttpFactoryInterface, *, logger: LoggerInterface | None = None, http_port: int = _HTTP_PORT, https_port: int = _HTTPS_PORT)
Bases: AbstractListener
Redirects a request onto the scheme its matched rule demands it arrive over.
A chain step over the access map's channel half — the same rules the
access step decides attributes from, asked the same question.
supports reads the channel the request's matched rule demands and
answers True when the request did not arrive over it: https
demanded of a plain request, http of an encrypted one. Every other
answer — no rule matched, the rule demands no channel, the request
already carries the demanded one — is False, the strict skip: the
step parks nothing, so a request with nothing to change has nothing to
come back for. authenticate answers the request with a permanent
redirect to the same request over the demanded scheme, which is also
what stops the chain.
The scheme a request is read by is its URI's own — the connection's answer, not a forwarded header's claim; this stack has no trusted-proxy machinery to weigh one, so a proxy terminating the encryption in front of the server leaves the request reading plain and the redirect this step builds would loop. The step says so in its log when the forwarded headers claim the request was encrypted already.
The redirect keeps everything but the scheme: the host, the whole path
with its query string, and the port the target scheme is configured
to answer on — spelled out only when it is not that scheme's default,
so a redirect to plain https names no port while one to https
on 8443 does. The port the request itself arrived on is left
behind: the target scheme has a port of its own.
Build the step over the firewall's rules and what it answers with.
Parameters:
-
access_map(AccessMapInterface) –The firewall's rules, whose matched rule names the scheme the request must arrive over.
-
responses(ResponseFactoryInterface) –Builds the redirect, so the class names no response class.
-
bridge(StarletteHttpFactoryInterface) –Turns the redirect — a pure message — into one the event accepts.
-
logger(LoggerInterface | None, default:None) –Writes the step's redirects, when given.
-
http_port(int, default:_HTTP_PORT) –The port plain
httpanswers on; spelled out in a redirect tohttpwhen it is not80. -
https_port(int, default:_HTTPS_PORT) –The port
httpsanswers on; spelled out in a redirect tohttpswhen it is not443.
supports
async
¶
Answer whether the matched rule demands a scheme the request lacks.
Only the channel half of the map's answer is weighed — the attributes are the access step's to decide — and the scheme is the request's own, the one its URI carries.
authenticate
async
¶
Answer the request with a permanent redirect to the demanded scheme.
The redirect is built as a message and set on the event through the bridge — the kernel's rule for messages from elsewhere — which is also what stops the chain: the steps after this one would be deciding about a request already answered.
ContextListener ¶
ContextListener(token_storage: TokenStorageInterface, user_providers: Sequence[UserProviderInterface], context_key: str, session_storage: SessionStorageInterface, *, logger: LoggerInterface | None = None, dispatcher: EventDispatcherInterface | None = None, trust_resolver: AuthenticationTrustResolverInterface | None = None, cookie: SessionCookieConfig = _DEFAULT_COOKIE)
Bases: AbstractListener
Reads the token a session carries into this request, and writes it back.
A chain step for a stateful firewall: the session a request reattaches holds the token its login stored, and this listener restores it, reloads the user it carries through the firewall's providers — a session outlives the data it was minted from, so the user is read fresh every request — and deauthenticates the token when the reload changed the user: the password was changed elsewhere, a role was withdrawn, the account is gone.
supports answers None always: nothing in a request's head commits
this listener, but it wants its say on every request of a stateful
firewall — the lazy join, so the chain runs it before it knows whether a
session even holds a token.
The response half — :meth:on_response, registered beside the chain on
the kernel's response event — writes the token back: what the request
authenticated is stored under the same session key, and an anonymous
request's key is removed, so a logout does not linger in the session.
It runs only for the requests this listener's own request half marked —
the firewall-run mark, parked with the session key as its value — so a
response of a request another firewall ran is left to that firewall's
listener.
The session is built from the request through the storage the application pointed the session at — the one request-to-session path — and parked on the request's security state, so both halves of one request reach the same session and nothing one request set reaches another. This is the only place a firewall's session is built, so the cookie it is given is the one every later step stages: the login's rotation, the logout's invalidation, the save that writes the session back.
A session holds JSON and nothing else, whatever storage keeps it, so the
token is stored as the envelope a
:class:~xtr_security_http.session.session_token_serializer.SessionTokenSerializer
writes — its class, its own state, and its user's: a user that keeps
itself whole, or a snapshot of its identifier, its roles and the digest of
its password — and rebuilt from it on the next request. A token whose
class cannot be kept, or whose attributes do not come back from JSON as
they went in, fails the response loudly rather than being lost quietly.
Build the listener over one firewall's session key and providers.
Parameters:
-
token_storage(TokenStorageInterface) –Where the restored token is set for the request's own authentication to read.
-
user_providers(Sequence[UserProviderInterface]) –The providers the session token's user is reloaded through, in order; the first that supports the user's class and vouches for it wins.
-
context_key(str) –The firewall's own name, composed into the session key its context is stored under.
-
session_storage(SessionStorageInterface) –Where the session's attributes are kept between requests; the session is built from the request through it.
-
logger(LoggerInterface | None, default:None) –Writes the refresh's decisions, when given.
-
dispatcher(EventDispatcherInterface | None, default:None) –Where the refreshed-user check and the deauthentication are announced, when given.
-
trust_resolver(AuthenticationTrustResolverInterface | None, default:None) –Reads whether the response half's token is authenticated; the base resolver when none is given.
-
cookie(SessionCookieConfig, default:_DEFAULT_COOKIE) –The cookie the session's ID is read from and written to; the session's default when none is given.
Raises:
-
InvalidArgumentError–When
context_keyis empty — the session key it composes would name no firewall, and two firewalls would share one context.
supports
async
¶
Answer the lazy join: None, on every request.
Nothing in a request's head commits this listener — the session is
read, not the request — so it never answers True, and it never
skips: a stateful firewall restores its context on every request,
token or no token, because the absence of one is what the request
half leaves in the storage for the access decision to weigh.
authenticate
async
¶
Restore the token the request's session carries, refreshed through the providers.
The session is built from the request and parked on its security state, beside the firewall-run mark that gates the response half — both under this listener's own key, so a second firewall's listener answers for its requests alone. A session holding no token leaves the storage empty; so does one holding something that is no token envelope — a corrupt payload, an object, an envelope of another version, a token or user class no class loaded now answers to, a state its class refuses — with a warning. Either way the request goes on anonymous, and the access decision is what turns it away.
A token the session holds is refreshed before it is stored: its user is reloaded through the providers, and a reload that changed the user deauthenticates — the token is not stored, and the deauthentication is announced with the reason and the providers that contributed to it.
Raises:
-
InvalidArgumentError–When a session token envelope keeps no user — the session was written by something that stored a token no authentication could have produced.
-
UnsupportedUserError–When no user provider supports the class of the user the session token carries.
on_response
async
¶
Store what the request authenticated back into the session it reattached.
Runs only for the requests this listener's request half marked with its own session key: a response of a request another firewall ran — or none at all — is left alone. An authenticated token is stored under the session key, as its envelope; an anonymous request's key is removed, so a logout does not linger in the session and answer for the next request.
Raises:
-
InvalidArgumentError–When the token cannot be kept in a session — its class defines no
from_sessionof its own, or an attribute or its user's state does not come back from JSON as it went in.
ExceptionListener ¶
ExceptionListener(token_storage: TokenStorageInterface, trust_resolver: AuthenticationTrustResolverInterface, responses: ResponseFactoryInterface, bridge: StarletteHttpFactoryInterface, firewall_name: str, entry_point: AuthenticationEntryPointInterface | None = None, error_page: str | None = None, access_denied_handler: AccessDeniedHandlerInterface | None = None, scope_denied_handler: AccessDeniedHandlerInterface | None = None, logger: LoggerInterface | None = None, stateless: bool = True, re_authentication_entry_point: ReAuthenticationEntryPointInterface | None = None)
Turns a security error raised while handling a request into a response.
One listener per firewall, built from that firewall's own parts — its name, its entry point, its access-denied handler — and parked by the firewall on the request's carrier, so a request's failure is answered by the firewall that ran it. The firewall's subscriber routes the request's failure here; a request no firewall matched is nobody's here, and its failure is the kernel's to answer.
The failure is walked along its chain of causes: the first link that is
one of this listener's is answered — an
:class:~xtr_security_core.exception.AuthenticationError starts the
entry point's challenge, an
:class:~xtr_security_core.exception.AccessDeniedError is answered by
denial, a :class:~xtr_security_http.exception.LogoutError — a logout
that failed its proof — by a plain refusal. The one later link of the
upstream order — a lazy response waiting for the response phase — has no
local shape: the lazy-response decision is P2.10's to record, so its
branch here is vacant until then.
An authentication error starts the entry point's challenge, keeping the
path the request was heading for on the session — unless the firewall is
stateless, or the entry point only stands in and starts no authentication
— and clearing the token when the error is an account-status one, so a
disabled account cannot loop its own challenge. A firewall with no entry
point answers a bare 401.
A denial from a caller who is not fully authenticated is really an
authentication gap: the entry point is started with an
:class:~xtr_security_core.exception.InsufficientAuthenticationError —
naming the masked authentication error the manager parked, when one was,
so the challenge answers what actually failed. A denial from a fully
authenticated caller is a refusal: a re-authentication entry point may
answer a recency refusal with a fresh proof of the caller it holds;
otherwise the firewall's scope handler answers a scope shortfall, its
access-denied handler a configured refusal, and a plain 403 is the
last word.
The upstream error page — a sub-request rendering a denial — has no local
counterpart: this kernel has no sub-request mechanism, so the
error_page parameter is taken and kept for the surface that will
carry it, and the branch is vacant: the refusal chain falls through to
the plain 403. Recorded as a deviation for the error-page work.
A response that already is what the framework sends — the kernel's own dual response, a message and a framework response at once — is set on the event as it is; a pure message is converted through the bridge first, which is the kernel's rule for messages from elsewhere.
Build the listener from one firewall's parts.
Parameters:
-
token_storage(TokenStorageInterface) –The request's token storage, cleared when an account-status error must not loop its own challenge.
-
trust_resolver(AuthenticationTrustResolverInterface) –Weighs the token the firewall authenticated.
-
responses(ResponseFactoryInterface) –Builds the bare
401/403answers, so the listener names no response class. -
bridge(StarletteHttpFactoryInterface) –Turns a handler's pure message response into one the lifecycle's event accepts.
-
firewall_name(str) –The firewall this listener answers for, and whose name keys the target path on the session.
-
entry_point(AuthenticationEntryPointInterface | None, default:None) –Answers an unauthenticated request with a challenge, or
Nonefor a bare401. -
error_page(str | None, default:None) –Kept for the error-page surface; vacant — this kernel has no sub-request mechanism, so a configured page is not rendered and the refusal chain falls through to
403. -
access_denied_handler(AccessDeniedHandlerInterface | None, default:None) –Answers a denied, fully authenticated caller, or
Nonefor a plain refusal. -
scope_denied_handler(AccessDeniedHandlerInterface | None, default:None) –Answers a denied OAuth2 scope with its own challenge, ahead of the plain access-denied handler.
-
logger(LoggerInterface | None, default:None) –Logs the branches as they are taken, when one is given.
-
stateless(bool, default:True) –Whether the firewall keeps no session; a stateless firewall keeps no target path.
-
re_authentication_entry_point(ReAuthenticationEntryPointInterface | None, default:None) –Starts a fresh proof for a caller who is already authenticated, or
Nonewhile no surface configures one.
on_exception
async
¶
Answer the request when the failure, or one of its causes, is one this listener owns.
The chain of causes is walked first-link-first: the earliest security error in the chain is the one that decided the request's fate, so it is the one answered. A failure that is none of this listener's — and whose causes are none either — is left to whatever else handles it.
The request every answer is built from carries the event's state bag, parked the way the chain's steps hand their request on, so an entry point or a handler reading the request's session — a login keeping its state there, a re-authentication keeping the identifier for the form — finds the one the chain parked.
Firewall ¶
Bases: EventSubscriberInterface
Runs the firewall a request matched over the request lifecycle's events.
At the request: the map is asked which firewall claims the request, and
that firewall's chain is run in the order the bundle's sorting pass left
it in. Each step is asked first — only a strict False skips it;
None and True both go on — and a step that answered the request
ends the chain: the steps after it would be deciding about a request
already dealt with. The logout listener, when the firewall has one, is
inserted ahead of the first step running at a lower priority, so a
logout is handled before the steps that would only clean up after it.
The matched firewall is parked on the request's security state — the per-request carrier — so a failure of the request reaches the entry point and the handlers of the firewall that ran it, and its exception listener is parked there for the exception phase, which routes the request's failure to the listener of the firewall that ran it; the finish phase puts the reference away. The carrier is one object per request, so nothing one request parked reaches another.
A failure the chain raises at the request is announced on the same
lifecycle: the exception event is dispatched, and whichever listener
answers it — the matched firewall's stored listener first, the
listeners that only observe the failure after it — has its response
set on the request's event, so the request is answered rather than
failing. A failure no listener answers is raised as it was raised: the
steps after the one that failed — the access decision among them — never
ran, so letting the request go on would hand the route a request nobody
decided about. The firewall fails closed, and the request fails with the
error. A caller driving the events by hand, with no dispatcher handed to
on_request, sees every failure raise as it was raised.
The kernel has one lifecycle per request — no request is handled inside another — so the main-request-only guard the upstream subscriber opens with has nothing to guard here.
A step's supports is asked about the request alone, while the state
the flow keeps rides the event's bag: the request handed to it carries
that bag, parked under
:attr:~xtr_security_http.security_request_attributes.SecurityRequestAttributes.STATE_BAG,
so both hooks of a step reach one carrier per request.
Build the firewall over the application's firewalls.
Parameters:
-
firewall_map(FirewallMapInterface) –Answers a request with the firewall that matched it — its chain, its exception listener and its logout listener.
get_subscribed_events
classmethod
¶
Listen to the request, the exception and the finish of every request.
on_request
async
¶
on_request(event: RequestEvent, name: str | None = None, dispatcher: EventDispatcherInterface | None = None) -> None
Run the chain of the firewall that matched the event's request.
A request no firewall claims runs nothing: no chain, nothing parked,
so a failure of such a request is answered by whatever else handles
it. An open firewall — one configured security=False — runs its
chain but parks no context: it authenticates nothing, so there is no
entry point of its own to answer with.
Parameters:
-
event(RequestEvent) –The request the lifecycle announced.
-
name(str | None, default:None) –The name the event was dispatched under; unused.
-
dispatcher(EventDispatcherInterface | None, default:None) –Where a failure the chain raises is announced. The dispatcher passes itself; a caller driving the events by hand leaves it out and sees the failure raise.
Raises:
-
Exception–Whatever a step raised, when no listener answered it.
on_exception
async
¶
Route the failure to the listener of the firewall that ran the request.
A request whose firewall stored no listener — none matched it, or the failure predates the request phase — is left to whatever else handles the failure.
on_finish_request
async
¶
Put away the listener the request's firewall stored.
The carrier does not outlive the request's bag; this frees the listener reference at the moment the request is done with it, which is what the finish of a request is for.
FirewallListenerInterface ¶
Bases: Protocol
One step of a firewall's chain of listeners over a request.
A firewall runs its listeners in the order the bundle sorted them —
by :meth:get_priority, highest first — and each one gets the same
two questions. :meth:supports is asked first, and only a listener
that did not answer False has :meth:authenticate called: the
chain skips a listener on a strict False alone, while None
and True both go on to authenticate. None is the lazy
answer — nothing in the request's head committed this listener, but
it still wants a say, the way a listener that only reacts once the
token storage is read does.
:meth:authenticate does the work — typically answering the
request by setting a response on the event, which is also what
stops the chain: a listener that answered decides the request, and
the ones after it would be deciding about a request that has
already been dealt with. A listener that only wants to read or
annotate the request leaves the response alone and the chain runs
on.
Both hooks are async: the request-inspecting collaborators of this package — the access map, the request matchers, the authenticator manager — answer asynchronously, so a listener's questions await.
The event is the kernel's request event, which carries the request as a message and the per-request state bag the security state rides on.
supports
async
¶
Tell whether this listener handles request.
False skips the listener; None and True both run
:meth:authenticate — None marking a listener that joins
lazily rather than eagerly.
authenticate
async
¶
Handle the request request_event carries.
A listener that answers the request sets a response on the event, which also stops the chain; one that leaves the response alone lets the chain run on.
get_priority
staticmethod
¶
Return this listener's position in the chain: the higher, the earlier it runs.
The bundle's sorting pass orders a firewall's chain by this, highest first, keeping the registration order of listeners that share a priority.
LogoutListener ¶
LogoutListener(token_storage: TokenStorageInterface, http_utils: HttpUtils, dispatcher: EventDispatcherInterface, bridge: StarletteHttpFactoryInterface, csrf_token_manager: CsrfTokenManagerInterface | None = None, *, csrf_parameter: str = '_csrf_token', csrf_token_id: str = 'logout', logout_path: str = '/logout')
Bases: AbstractListener
Logs a request out: announces the logout, then clears the token.
A chain step for a firewall configured with a logout path. supports
answers whether the request is asking for a logout — its path is the
configured one — and authenticate carries the logout out: the request
proves itself first, when a cross-site request forgery manager is wired,
then the logout event is announced on the firewall's own dispatcher, where
the firewall's logout listeners each do their part, and the token is
cleared from the storage and the request's state. A response one of the
event's listeners answered with is set on the request's event, which also
stops the chain.
The event is announced before the token is cleared, so its listeners read the token being logged out; the storage is cleared after, so a listener that answers with the token's last sight — a farewell page naming the user — still can.
Build the step over one firewall's logout parts.
Parameters:
-
token_storage(TokenStorageInterface) –The request's token storage, cleared by the logout.
-
http_utils(HttpUtils) –Matches the request's path against the configured logout path.
-
dispatcher(EventDispatcherInterface) –The firewall's own dispatcher, where the logout event is announced — the same one the firewall's login listeners run on, so an application listening there hears a logout too.
-
bridge(StarletteHttpFactoryInterface) –Turns a logout listener's pure message response into one the lifecycle's event accepts.
-
csrf_token_manager(CsrfTokenManagerInterface | None, default:None) –Vouches for the token a logout request presents, or
Nonewhile the firewall asks for no proof — the cross-site request forgery protection is optional, the way the logout configuration's is. -
csrf_parameter(str, default:'_csrf_token') –The name the request carries the forgery token under, in its submitted form or its query string.
-
csrf_token_id(str, default:'logout') –The id the forgery token is stored under.
-
logout_path(str, default:'/logout') –The path a request asks for a logout by.
supports
async
¶
Answer whether request is asking for a logout.
A request that is not asking for one — its path is not the
configured logout path — answers a strict False, so the chain
skips this step and runs on.
authenticate
async
¶
Carry the logout out: prove the request, announce it, clear the token.
The request the event carries holds the request event's state bag, the way the authentication step hands its request on, so a listener of the logout reaches what the chain parked there: the session it invalidates is the one the context step reattached.
Raises:
-
LogoutError–When a cross-site request forgery manager is wired and the request presented no token value, or one the manager does not vouch for.
get_priority
staticmethod
¶
Return the logout step's position in the chain: behind the deciders.
OidcTokenRefreshListener ¶
OidcTokenRefreshListener(token_storage: TokenStorageInterface, refresher: OidcTokenRefresher, logger: LoggerInterface | None = None)
Bases: AbstractListener
Renews the OIDC access tokens of the logged-in user before they expire.
A chain step for a stateful firewall whose logins went through the OIDC
login: the token the context step restored from the session carries the
access and refresh tokens the provider issued, and this step hands it to
the refresher, which renews the access token once it comes within the
refresher's leeway of expiring. It runs after the context step — declared
through @FirewallListenerOrder, at the priority the two share — so
what it renews is the token the request reads and the context step's
response half writes back into the session.
Failing to renew only ends the login when the provider says the refresh token is gone for good: the refresher's invalid-grant error clears the token from the storage — the request goes on anonymous, and the context step's response half removes the session's copy with it — while any other renewal failure is only warned about and left for the next request, the tokens untouched. A provider that cannot be reached would otherwise log every user out at once.
The refresher this step hands the token to stays a typing-only
reference: importing the OIDC client machinery it lives in would pull
the JOSE toolkit behind the oidc extra into every application
importing this package, listener or no listener. The wiring that builds
this step resolves the class where the extra is already required.
Build the step over the request's token storage and the token refresher.
Parameters:
-
token_storage(TokenStorageInterface) –Where the context step restored the request's token; the renewal reads it, and a rejected grant clears it.
-
refresher(OidcTokenRefresher) –Renews the OIDC tokens the stored token carries.
-
logger(LoggerInterface | None, default:None) –Writes the renewal's outcomes, when given.
supports
async
¶
Answer the lazy join: None, on every request.
The chain asks supports before the context step has restored the
token, so the storage this step would have to decide on is still
empty: answering about the token here would skip this step on every
request. None keeps the join lazy, and :meth:authenticate is
the one that reads the storage.
authenticate
async
¶
Renew the OIDC tokens the stored token carries, when they are due.
A request with no token stored — an anonymous one, or a firewall that restored none — is left alone. A token the refresher renews is renewed in place: it keeps its seat in the storage, and the context step's response half writes the renewed attributes back into the session. A refresh token the provider no longer honors clears the storage — the one failure that ends the login — and any other renewal failure is logged and left for the next request, so an unreachable provider costs a warning per request, not every user's login.
RefreshUserResult
dataclass
¶
RefreshUserResult(token: TokenInterface | None = None, deauthentication_reason: str | None = None, provider_classes: tuple[type, ...] = (), exception: AuthenticationError | None = None)
What came of reloading a session token's user through its providers.
The token is the outcome when the reload held: the same token, its user
replaced by the provider's fresh copy. A None token is a
deauthentication — no provider vouched for the user — and the rest of the
fields say why, for the deauthentication event to carry: the reason as a
sentence, the providers that contributed to the decision, and the
authentication error a listener gave when one did.
Attributes:
-
token(TokenInterface | None) –The refreshed token, or
Nonewhen the user was deauthenticated. -
deauthentication_reason(str | None) –A sentence explaining the deauthentication, or
Nonewhen the token held. -
provider_classes(tuple[type, ...]) –The classes of the user providers that contributed to the deauthentication decision — the ones that detected a change in the user, or the ones that could not find it.
-
exception(AuthenticationError | None) –The authentication error a listener of the refreshed-user check gave as its reason to deauthenticate.
SwitchUserListener ¶
SwitchUserListener(token_storage: TokenStorageInterface, provider: UserProviderInterface, user_checker: UserCheckerInterface, firewall_name: str, access_decision_manager: AccessDecisionManagerInterface, bridge: StarletteHttpFactoryInterface, http_utils: HttpUtils, logger: LoggerInterface | None = None, username_parameter: str = '_switch_user', role: str = 'ROLE_ALLOWED_TO_SWITCH', dispatcher: EventDispatcherInterface | None = None, stateless: bool = False, path: str | None = None, csrf_token_manager: CsrfTokenManagerInterface | None = None, csrf_parameter: str = '_csrf_token', csrf_token_id: str = 'switch_user')
Bases: AbstractListener
Lets a user temporarily act as another one, like the su command.
A chain step for a firewall configured with a user switch. supports
answers whether the request is asking for a switch — it carries the
configured parameter naming the user to become — and authenticate
carries the switch out: the request proves itself first, when a
cross-site request forgery manager is wired, then the right to switch
is decided — the configured role, against the target user as the
subject — and the target user is loaded, checked, and settled on a
token that keeps the way back. The request is answered with a
redirect to the page it was asked at, the switch's own parameters
stripped from the address.
The exit is the same parameter carrying the exit value: the original token the switch started from is restored, its user reloaded first, and the request redirected the same way. A user already switched may switch again — the current switch is left seamlessly before the new one begins — and asking for the user already impersonated changes nothing.
The load of the target user is timing-equalised: a second, throwaway identifier no provider can know is loaded beside it, and a target that cannot be loaded burns a load of the current user instead, so the time a switch takes never tells whether a user exists.
Build the step over one firewall's switch parts.
Parameters:
-
token_storage(TokenStorageInterface) –The request's token storage, read for the token to switch from and written with the token a switch settles on.
-
provider(UserProviderInterface) –Loads the user a switch asks to become.
-
user_checker(UserCheckerInterface) –Checks the target user's account state once the switch is decided.
-
firewall_name(str) –The firewall the switch happens in, recorded on the switched token.
-
access_decision_manager(AccessDecisionManagerInterface) –Decides the right to switch — the configured role, against the target user as the subject.
-
bridge(StarletteHttpFactoryInterface) –Turns the redirect into what the lifecycle's event accepts — the kernel's rule for messages from elsewhere.
-
http_utils(HttpUtils) –Builds the redirect, and matches the request's path when the switch is scoped to one. The upstream step takes its HTTP utilities optionally and builds its redirect directly; here they are the one redirect builder — the class names no response class — so both are required.
-
logger(LoggerInterface | None, default:None) –Writes the switch's decisions, when given.
-
username_parameter(str, default:'_switch_user') –The name a request carries the user to switch to under.
-
role(str, default:'ROLE_ALLOWED_TO_SWITCH') –The role the right to switch is decided by.
-
dispatcher(EventDispatcherInterface | None, default:None) –Where the switch event is announced, when given.
-
stateless(bool, default:False) –Leaves the request unanswered — no redirect — for a firewall that keeps no session.
-
path(str | None, default:None) –The dedicated path a switch is asked at, or
Noneto read the parameter on any page. -
csrf_token_manager(CsrfTokenManagerInterface | None, default:None) –Vouches for the token a switch request presents, or
Nonewhile the firewall asks for no proof. -
csrf_parameter(str, default:'_csrf_token') –The name a request carries the forgery token under.
-
csrf_token_id(str, default:'switch_user') –The id the forgery token is stored under.
Raises:
-
InvalidArgumentError–When
firewall_nameis empty.
EXIT_VALUE
class-attribute
instance-attribute
¶
The parameter value that asks to leave an impersonation, not start one.
supports
async
¶
Answer whether request is asking for a user switch.
Scoped to a dedicated path, only a request both at that path and
carrying the parameter asks; on any page, the parameter alone
asks, wherever the request carries it — a request that is not safe
has the form it posted read for it, so a switch posted in a form
asks too. The username it names is parked on the request's
security state for authenticate.
authenticate
async
¶
Carry the switch out, and answer with a redirect to the page it was asked at.
Raises:
-
AccessDeniedError–When a wired forgery token does not check out, the right to switch is refused, or the switch itself failed — the last always as a plain refusal, so a failed switch never tells whether a user exists.
-
AuthenticationCredentialsNotFoundError–When no token is held to switch from, or an exit is asked with no switch to leave.
FirewallContextInterface ¶
Bases: Protocol
The runtime pieces of one firewall, resolved once and shared for its lifetime.
Groups the manager that authenticates a request, the access listener that decides it, the entry point and handlers that answer it, and the listener chain it runs — already ordered by the bundle's sorting pass, so the order it is held in is the order it runs in.
Attributes:
-
name(str) –The firewall's name — the key it is looked up by, and the memo key that keeps its authentication to one pass per request.
-
authenticator_manager(AuthenticatorManagerInterface) –Runs the firewall's authenticators.
-
access_listener(AccessListener) –Decides a request against the firewall's rules.
-
security(bool) –Whether the firewall authenticates at all;
Falselets every request through untouched. -
entry_point(AuthenticationEntryPointInterface | None) –Answers an unauthenticated request with a challenge.
-
access_denied_handler(AccessDeniedHandlerInterface | None) –Answers a fully-authenticated caller's denial.
-
scope_denied_handler(AccessDeniedHandlerInterface | None) –Answers a denied OAuth2 scope with its own challenge, ahead of the plain access-denied handler.
-
listeners(tuple[FirewallListenerInterface, ...]) –The firewall's chain of listeners, in the order they run.
-
exception_listener(ExceptionListener | None) –The listener that answers a security error the firewall's request raised.
-
logout_listener(FirewallListenerInterface | None) –The listener that performs a logout the firewall's request asks for, or
Nonewhile the firewall has none.
FirewallMap ¶
Bases: FirewallMapInterface
Holds an application's firewalls, found by name or by matching a request.
A firewall is matched to the first firewall whose request matcher claims the request, in the order they were registered, so a narrow firewall must be registered before a catch-all it would shadow.
Each firewall is paired with a
:class:~xtr_http_foundation.request_matcher_interface.RequestMatcherInterface
from xtr-http-foundation — a path, host, method, address or callable
matcher, or a chain of them — so the map matches a request without a
notion of matching of its own. A chain of no matchers claims every
request, the catch-all a firewall registered last relies on.
The contexts it holds are read through
:class:~xtr_security_http.firewall_context_interface.FirewallContextInterface,
so the map works over whatever concrete context the bundle gathers. The
listener chain, the exception listener and the logout listener a request's
firewall runs are read off that context, so the map answers a request with
the parts the firewall that runs them needs, without a notion of how the
bundle ordered the chain.
Record the firewalls, keyed by name and kept in matching order.
Raises:
-
InvalidArgumentError–When two firewalls share a name.
get ¶
match
async
¶
Return the first firewall whose matcher claims request, or None.
get_listeners
async
¶
get_listeners(request: ServerRequestInterface) -> tuple[tuple[FirewallListenerInterface, ...], ExceptionListener | None, FirewallListenerInterface | None]
Return the matched firewall's chain, exception listener and logout listener.
A request no firewall claims answers an empty chain and no exception or logout listener — the firewall that runs the chain then has nothing to run, and no listener to answer an error or a logout with.
FirewallMapInterface ¶
Bases: Protocol
Holds an application's firewalls, found by name or by matching a request.
A firewall bound by name is looked up directly; an unbound one is matched to the first firewall whose matcher claims the request, in registration order.
get ¶
match
async
¶
Return the first firewall whose matcher claims request, or None.
get_listeners
async
¶
get_listeners(request: ServerRequestInterface) -> tuple[tuple[FirewallListenerInterface, ...], ExceptionListener | None, FirewallListenerInterface | None]
Return the matched firewall's listener chain, and its exception and logout listeners.
The chain is the matched firewall's listeners in the order they run — the order the bundle's sorting pass left them in. A request no firewall claims answers an empty chain and no exception or logout listener.
HttpUtils ¶
HttpUtils(responses: ResponseFactoryInterface, uri_builder: Callable[[str], str] | None = None, domain_regexp: str | None = None, secure_domain_regexp: str | None = None)
Encapsulates the logic needed to redirect the caller, and to match paths.
A path is always a literal path — an absolute path (/login) or an
absolute URL (https://…) — never a route name: this stack has no
routing component to resolve one by, the recorded deviation, so a
relative path is refused as the configuration mistake it is here. The URI
a path becomes is written by the injected URI builder — the path itself
by default, an absolute URL when the application's builder writes one.
Attributes:
-
domain_regexp–A regexp the target of an HTTP redirection must match, scheme included, with a
%sslot for the request's host. -
secure_domain_regexp–The same, weighed only when the request arrived over
https.
Record the response factory, the URI builder and the redirect-target guards.
Parameters:
-
responses(ResponseFactoryInterface) –Builds the redirect responses, so the class names no response class.
-
uri_builder(Callable[[str], str] | None, default:None) –Writes the URI a path becomes. Left out, a path is its own URI — a
Locationmay carry one, and the framework resolves it against the request's host. -
domain_regexp(str | None, default:None) –A regexp the target of an HTTP redirection must match, scheme included, with a
%sslot for the request's host; a target that fails it is replaced by/.Noneallows any target. -
secure_domain_regexp(str | None, default:None) –The same, weighed only when the request arrived over
https.Noneallows any target.
check_request_path ¶
Tell whether path is the path of request.
The request's path is read as it travels — percent-decoded — and compared with the configured one, which is the whole path the message carries: the same path a firewall's matcher matches, so an application mounted under a prefix configures its paths with the prefix, the one place this stack records where the application begins.
Raises:
-
InvalidArgumentError–When
pathis not an absolute path or an absolute URL — a route name, which no routing component here can resolve.
generate_uri ¶
Generate a URI, based on the given path or absolute URL.
An empty path or an absolute URL is returned as it is; an absolute path goes through the URI builder; anything else is a route name, which nothing here can resolve.
Raises:
-
InvalidArgumentError–When
pathis neither an absolute path nor an absolute URL.
create_redirect_response ¶
create_redirect_response(request: ServerRequestInterface, path: str, status: int = 302) -> ResponseInterface
Create a redirect response to path, answering with status.
A target that names another host is weighed against the configured
domain regexps first — the secure one while the request arrived
over https — and a target neither allows is replaced by /,
so a redirect can never leave the application's own domain by the
word of a path an attacker chose.
ImpersonateUrlGenerator ¶
ImpersonateUrlGenerator(config_lookup: SwitchUserConfigLookupInterface, token_storage: TokenStorageInterface, uri_builder: Callable[[str, ServerRequestInterface | None], str] | None = None, csrf_token_manager: CsrfTokenManagerInterface | None = None)
Provides the impersonation and exit paths, URLs and forms of a firewall.
Asked for the address a switch to a user — or the exit from one — is started by, the generator reads how the request's firewall asks for switches and writes the address: the page the request is at, carrying the switch's parameter, or the firewall's dedicated path when it has one. The exit addresses answer empty while the current user impersonates nobody, so a template can skip them.
The request is a parameter of every method, where the upstream stack reads it from a request stack this kernel does not have; and the firewall's switch configuration is read through the lookup the generator is built with, where the upstream generator reaches into the bundle's own firewall map — the recorded deviations.
A path is always a literal path — an absolute path (/switch) or
an absolute URL (https://…) — never a route name: this stack has
no routing component to resolve one by, the recorded deviation. The
URI a path becomes in the URL methods is written by the injected URI
builder — the path itself by default, an absolute URL when the
application's builder writes one.
Record the lookup, the storage and the builders the generation reads.
Parameters:
-
config_lookup(SwitchUserConfigLookupInterface) –Answers the switch-user configuration of the firewall a request runs in.
-
token_storage(TokenStorageInterface) –Read to tell whether the current user is impersonating anyone, which the exit addresses stand on.
-
uri_builder(Callable[[str, ServerRequestInterface | None], str] | None, default:None) –Writes the absolute URI a path becomes in the URL methods. Left out, a path is its own URI — a
Locationmay carry one, and the framework resolves it against the request's host. -
csrf_token_manager(CsrfTokenManagerInterface | None, default:None) –Mints the token a generated address carries, when the firewall's switch asks for one.
generate_impersonation_path
async
¶
generate_impersonation_path(request: ServerRequestInterface, identifier: str, target_uri: str | None = None) -> str
Generate the path a switch to identifier is started by.
generate_impersonation_url
async
¶
generate_impersonation_url(request: ServerRequestInterface, identifier: str, target_uri: str | None = None) -> str
Generate the absolute URL a switch to identifier is started by.
generate_exit_path
async
¶
Generate the path an exit from the current switch is asked by.
generate_exit_url
async
¶
Generate the absolute URL an exit from the current switch is asked by.
generate_impersonation_form
async
¶
generate_impersonation_form(request: ServerRequestInterface, identifier: str, target_uri: str | None = None) -> ImpersonationForm
Return the action and the hidden fields of a form triggering the switch.
Unlike the URLs, this keeps the parameters out of the address bar
and works with a path restricted to POST requests. The fields
hold the identifier of the user to switch to, the page to come
back to on a dedicated path, and the forgery token when the
switch asks for one.
generate_exit_form
async
¶
generate_exit_form(request: ServerRequestInterface, target_uri: str | None = None) -> ImpersonationForm
Return the action and the hidden fields of a form exiting the switch.
The action is empty when the current user is not impersonating anyone, so that a template can skip the form.
ImpersonationForm ¶
Bases: TypedDict
The action and the hidden fields of a form triggering a user switch.
Unlike the URLs, the form keeps the switch's parameters out of the
address bar: they ride in hidden fields, so the form suits a switch
restricted to POST requests. Render each field as a hidden input
of a form posted to the action.
Attributes:
-
action(str) –The path the form is posted to — the page the switch is asked at, or the dedicated path when the firewall has one.
-
fields(dict[str, str]) –The hidden fields, each mapped to the value it carries: the user to switch to, the page to come back to on a dedicated path, and the forgery token when the switch asks for one.
-
csrf_field(str | None) –The name of the field carrying the forgery token, for a template to mark for client-side scripts, or
Nonewhen the form carries none.
SwitchUserConfig
dataclass
¶
SwitchUserConfig(parameter: str = '_switch_user', enable_csrf: bool = False, csrf_parameter: str = '_csrf_token', csrf_token_id: str = 'switch_user', path: str | None = None)
The parts of a firewall's configuration a generated switch address reads.
The defaults are the switch listener's own, so a firewall configured with nothing but the switch itself generates addresses the listener reads back.
Attributes:
-
parameter(str) –The name a request carries the user to switch to under.
-
enable_csrf(bool) –Whether a switch asks for a cross-site request forgery token.
-
csrf_parameter(str) –The name a request carries the forgery token under.
-
csrf_token_id(str) –The id the forgery token is stored under.
-
path(str | None) –The dedicated path a switch is asked at, or
Noneto ask by the parameter on any page.
SwitchUserConfigLookupInterface ¶
Bases: Protocol
Answers the switch-user configuration of the firewall a request runs in.
The generator's one question about the world around it: how the firewall the request belongs to asks for a user switch — or that it does not ask for one at all. Kept an interface of its own, with nothing else on it, so whatever knows the firewalls — a bundle's wiring, an application's own map — can answer without the generator knowing how the firewalls are held, and the generator stays usable with no bundle behind it.
get_switch_user_config
async
¶
Return the switch-user configuration of request's firewall, or None.
A request no firewall claims answers None, the same as a
firewall configured without a switch: neither has an address to
generate.
LoginLinkDetails ¶
The link a handler minted: its URL and the moment it stops counting.
The value a handler hands the caller that asked for a link — a mailer that sends it, a page that shows it. The URL is the whole link, query string and all; the expiry is the moment the hash inside it stops verifying, the same moment the caller should stop presenting it.
Record the link's URL and the moment it stops counting.
Parameters:
LoginLinkHandler ¶
LoginLinkHandler(user_provider: UserProviderInterface, signature_hasher: SignatureHasher, options: Mapping[str, object] | None = None, uri_builder: Callable[[str, ServerRequestInterface | None], str] | None = None, clock: ClockInterface | None = None, *, uses_limiter_factory: RateLimiterFactoryInterface | None = None)
Bases: LoginLinkHandlerInterface
Signs links with the core hasher, and checks the links presented back.
A link is stateless: nothing is stored, and the link vouches for itself by a hash the core signature hasher computes over the user, the expiry and the link's extra parameters — checked against the identifier before the user is loaded, then against the loaded user's own covered fields, so a changed password retires every link issued before it. Which is also the limit: a single link cannot be revoked alone, only every link of the user, by changing what the signature covers.
The link's URL is the configured path with the signed parameters as its query string. The URI the path becomes is written by the injected URI builder — the path itself by default — and the builder also receives the request the link is generated against, when there is one: the translation of building the link for that request's own address. This stack has no routing component to resolve a route name by, so the option is a literal path and a route name is refused.
Record the provider, the hasher, the options, the builder and the clock.
Parameters:
-
user_provider(UserProviderInterface) –Loads the user a presented link names, after the hash has proved the link sound.
-
signature_hasher(SignatureHasher) –Signs the links this handler mints and checks the ones it is handed.
-
options(Mapping[str, object] | None, default:None) –The link's shape, merged over the defaults —
lifetime, andpath, the literal path every minted link leads to, required. -
uri_builder(Callable[[str, ServerRequestInterface | None], str] | None, default:None) –Writes the URI a path becomes, receiving the request the link is generated against when there is one; the path itself while
None. -
clock(ClockInterface | None, default:None) –Reads the current instant, for the moment each new link counts until; the system clock when
None. -
uses_limiter_factory(RateLimiterFactoryInterface | None, default:None) –Counts each link's uses, keyed by its hash, refusing one past the limit the factory sets — a window as long as the link's lifetime makes the limit hold for as long as the link does.
Noneleaves a link usable any number of times until it expires.
Raises:
-
InvalidArgumentError–When
optionscarries nopath, or names where a link leads by a route name.
create_login_link
async
¶
create_login_link(user: UserInterface, request: ServerRequestInterface | None = None, lifetime: int | None = None, parameters: Mapping[str, str | bool | int | float] | None = None) -> LoginLinkDetails
Sign a link for user, until a lifetime from now.
The extra parameters are sorted and their names listed in the
link's hash_parameters — the list the reading back walks —
and every one of them is covered by the hash, so a link cannot be
re-pointed by editing what it carries. The names the link's own
reading uses are reserved: user, expires, hash and
hash_parameters.
Raises:
-
InvalidArgumentError–When a parameter's name is malformed or reserved, or the configured path is a route name.
consume_login_link
async
¶
Check the link request presents, and load the user it signs in.
The link's parameters are read from the query string, or the body
of a request that is not a GET; the hash is checked against
the identifier before the user is loaded — an unproven link must
not cost a user lookup — then against the loaded user's own
covered fields. The extra parameters the link carried are parked
on the request's security state under the login-link parameters
key, for the handlers that answer the login.
Raises:
-
InvalidLoginLinkError–When a parameter is missing or malformed, the hash verifies under no secret, or the provider knows no such user, or the link has been used as many times as the uses limiter allows.
-
ExpiredLoginLinkError–When the link's moment has passed.
LoginLinkHandlerInterface ¶
Bases: Protocol
Creates the links a login is asked to arrive by, and consumes them.
A login link is a URL the handler signs for one user until one moment; presenting it back is the login. The handler is the one voice on what a link carries: it mints one for a user, and checks the one a request presents, loading the user the link was signed for.
create_login_link
async
¶
create_login_link(user: UserInterface, request: ServerRequestInterface | None = None, lifetime: int | None = None, parameters: Mapping[str, str | bool | int | float] | None = None) -> LoginLinkDetails
Mint a link that authenticates as user, until it expires.
Parameters:
-
user(UserInterface) –The user the link signs in.
-
request(ServerRequestInterface | None, default:None) –The request the link is generated against, when there is one — the link's URI is built for that request's own address.
-
lifetime(int | None, default:None) –How long the link counts, in seconds; the handler's configured lifetime when
None. -
parameters(Mapping[str, str | bool | int | float] | None, default:None) –Extra query parameters the link carries, covered by its hash.
Raises:
-
InvalidArgumentError–When a parameter's name is malformed or reserved, or the handler's configured path is a route name.
consume_login_link
async
¶
Check the link request presents, and load the user it signs in.
The extra parameters the link carried are exposed on the request's security state under the login-link parameters key, for the handlers that answer the login.
Raises:
-
InvalidLoginLinkError–When the link does not check out — a parameter missing or malformed, a hash that verifies under no secret, a user the provider does not know.
-
ExpiredLoginLinkError–When the link's moment has passed.
LogoutForm ¶
Bases: TypedDict
The action and the hidden fields of a form triggering a logout.
Unlike the logout URLs, the form keeps the cross-site request forgery
token out of the address bar: the token rides in a hidden field, so the
form suits a logout restricted to POST requests. Render each field
as a hidden input of a form posted to the action.
Attributes:
-
action(str) –The path the form is posted to — the firewall's logout path.
-
fields(dict[str, str]) –The hidden fields, each mapped to the value it carries; the forgery token under its parameter name, when the firewall's logout asks for one.
-
csrf_field(str | None) –The name of the field carrying the forgery token, for a template to mark for client-side scripts, or
Nonewhen the form carries none.
LogoutUrlGenerator ¶
LogoutUrlGenerator(uri_builder: Callable[[str], str] | None = None, token_storage: TokenStorageInterface | None = None)
Provides the logout path, URL and form of a registered firewall.
Each firewall with a logout registers itself here — its path, the cross-site request forgery token its logout asks for, and the context it runs in — and whatever renders a page asks for the logout's address by the firewall's name, or without one: the firewall the current request runs under is found from the token the request is authenticated by, or the one the application last named, or the one sharing the current context, in that order.
A path is always a literal path — an absolute path (/logout) or an
absolute URL (https://…) — never a route name: this stack has no
routing component to resolve one by, the recorded deviation. The URI a
path becomes in :meth:get_logout_url is written by the injected URI
builder — the path itself by default, an absolute URL when the
application's builder writes one.
Record the URI builder and the token storage the resolution reads.
Parameters:
-
uri_builder(Callable[[str], str] | None, default:None) –Writes the absolute URI a path becomes in :meth:
get_logout_url. Left out, a path is its own URI — aLocationmay carry one, and the framework resolves it against the request's host. -
token_storage(TokenStorageInterface | None, default:None) –Read to find the firewall the current request is authenticated by — the token it holds names the firewall that authenticated it. Left out, a keyless lookup resolves over the current firewall alone.
register_listener ¶
register_listener(key: str, path: str, csrf_token_id: str | None, csrf_parameter: str | None, csrf_token_manager: CsrfTokenManagerInterface | None = None, context: str | None = None) -> None
Record one firewall's logout, for the generator to generate from.
Parameters:
-
key(str) –The firewall's name — the key its logout is generated by.
-
path(str) –The path a request asks that firewall's logout by.
-
csrf_token_id(str | None) –The id the forgery token is stored under, or
Nonewhile the firewall's logout asks for no proof. -
csrf_parameter(str | None) –The name a request carries the forgery token under, or
Nonewith the id. -
csrf_token_manager(CsrfTokenManagerInterface | None, default:None) –Mints the token the generated address carries, or
Nonewhile the generated address carries none. -
context(str | None, default:None) –The context the firewall runs in, matched when no firewall is named — the shared context of a firewall pair, a stateless API beside a stateful login.
get_logout_path
async
¶
Generate the logout path of key, or of the current firewall.
The path itself — the configured logout path, or the absolute URL it is when it was configured as one — beside the query a forgery token adds, when the registered logout carries one.
get_logout_url
async
¶
Generate the absolute logout URL of key, or of the current firewall.
The path through the URI builder — the path itself while no builder writes absolute URIs — beside the query a forgery token adds, when the registered logout carries one.
get_logout_form
async
¶
Return the action and the hidden fields of a form triggering the logout.
Unlike the URLs, this keeps the forgery token out of the address
bar, and suits a logout restricted to POST requests. Render each
field as a hidden input of a form posted to the action; the
csrf_field key names the field that carries the token, for a
template to mark for client-side scripts, or is None when the
form carries none.
set_current_firewall ¶
Name the firewall a keyless generation generates for.
The application — or the bundle wiring it — names the firewall while running a request of its own, so a template generating a logout address with no key names this firewall's. The context is matched when no firewall is named, against the context each registered logout carries.
reset ¶
Put the current-firewall tracking back to no firewall.
What a request named does not answer for the next one: a worker or a test that reuses the generator starts untracked, and a keyless generation resolves over the token or fails loudly instead of answering for a firewall no request of its own runs under.
Implemented without the service contracts' ResetInterface: this
package does not depend on that one, and this method is the whole of
what the interface asks.
DefaultLoginRateLimiter ¶
DefaultLoginRateLimiter(global_factory: RateLimiterFactoryInterface, local_factory: RateLimiterFactoryInterface, secret: str)
Bases: AbstractRequestRateLimiter
Counts a login under the account it named and the address it came from.
Two limits, one strict each way: the local one counts the attempts on one account from one address, and the global one counts everything one address tries, across accounts — a breadth-first sweep of usernames is bounded even when no single account sees two attempts. Both keys are HMAC digests of what they name, prefixed with a secret the application supplies, so a store shared across servers keeps no readable account or address.
A successful login forgets the local count only: the global one bounds how many accounts one client may try, so it must survive the successful login of any one of them.
Record the two factories and the secret their keys are derived with.
Parameters:
-
global_factory(RateLimiterFactoryInterface) –The factory handing out the limiters one address counts under.
-
local_factory(RateLimiterFactoryInterface) –The factory handing out the limiters one account from one address counts under.
-
secret(str) –The secret the keys are derived with.
Raises:
-
InvalidArgumentError–When
secretis empty — a key derived with no secret names what it counts in the clear.
get_limiters ¶
Return the limiters a login attempt counts under.
The global limiter counts the address, the local one the account from that address — the username read off the request's security state, where the throttling listener parks it, lower-cased so the same account is one account whatever capitalisation it arrived with.
reset
async
¶
Forget the account's count only, leaving the address's standing.
The address's limit bounds how many accounts one client may try, so it must survive the successful login of any one of them.
AbstractRememberMeHandler ¶
AbstractRememberMeHandler(user_provider: UserProviderInterface, options: Mapping[str, object] | None = None, logger: LoggerInterface | None = None)
Bases: RememberMeHandlerInterface
Loads the user a cookie names, and stages the cookie every method sets.
The two halves of a remember-me flow that no handler differs on: the user a cookie names is loaded through the user provider before the handler's own check runs, and the cookie — set or cleared — is staged on the request's security state, under the one key the response pass reads, because no response exists to put it on yet.
A subclass implements :meth:process_remember_me: the check that the
details still count, and the fresh cookie a consumed one must leave
behind.
Record the provider, the cookie's options and the logger.
Parameters:
-
user_provider(UserProviderInterface) –Loads the user a cookie names, before the handler's own check runs.
-
options(Mapping[str, object] | None, default:None) –The cookie's shape, merged over the defaults —
name,lifetime,path,domain,secure,httponly,samesite, and the two the conditions listener reads,always_remember_meandremember_me_parameter. -
logger(LoggerInterface | None, default:None) –Where the flow's decisions are logged, or
Noneto log nowhere.
consume_remember_me_cookie
async
¶
consume_remember_me_cookie(request: ServerRequestInterface, remember_me_details: RememberMeDetails) -> UserInterface
Load the user the details name, then hand both to the check.
The user is loaded before the check runs, because the check needs the user it is remembering — a signature is verified against the user's own fields, a stored token against what the user still is.
Raises:
-
AuthenticationError–When the provider knows no such user, or the handler's own check refuses the details.
clear_remember_me_cookie
async
¶
Stage the clearing of the cookie, under the attributes it was set with.
process_remember_me
abstractmethod
async
¶
process_remember_me(request: ServerRequestInterface, remember_me_details: RememberMeDetails, user: UserInterface) -> None
Check the details against the user, and stage the fresh cookie.
A consumed cookie is spent: the check runs here, and the fresh cookie the caller's next request will present is staged on the request — unless the handler's own policy keeps the current one, as a rotation window may.
Raises:
-
AuthenticationError–When the details do not check out against the user.
PersistentRememberMeHandler ¶
PersistentRememberMeHandler(token_provider: TokenProviderInterface, user_provider: UserProviderInterface, options: Mapping[str, object] | None = None, logger: LoggerInterface | None = None, token_verifier: TokenVerifierInterface | None = None, signature_properties: Sequence[str] | None = None, clock: ClockInterface | None = None)
Bases: AbstractRememberMeHandler
Stores every cookie's series and value, so one login can be revoked.
Each cookie carries a series — the login it belongs to — and a value, both 33 random bytes in the cookie's alphabet, and the store keeps the one value the series expects next. A presented value that matches is spent on the spot: a fresh one is stored and staged for the response, so a stolen copy of the old cookie finds nothing left to present. A value that does not match was already spent — the cookie was copied, and the whole series is dropped so the thief and the owner are both logged out.
The value also carries a digest of the user's signature properties — the password by default — so a changed password retires the series even though its random parts never changed. Properties the user does not expose are skipped while the list is the default one, which keeps a user class without any of them working as before.
A store that can afford it may accept a slightly outdated value — the rotation window — through a verifier, so a request that raced its own rotation still logs in.
Record the store, the provider, the bound properties and the clock.
Parameters:
-
token_provider(TokenProviderInterface) –Keeps every series' current value — a database in an application, reached over I/O.
-
user_provider(UserProviderInterface) –Loads the user a cookie names.
-
options(Mapping[str, object] | None, default:None) –The cookie's shape, merged over the defaults.
-
logger(LoggerInterface | None, default:None) –Where the flow's decisions are logged, or
None. -
token_verifier(TokenVerifierInterface | None, default:None) –Accepts a presented value the store no longer holds exactly — the rotation window's policy — and records a rotation without spending one; the provider itself when it implements the verifier's contract, and
Nonefor the plain equality. -
signature_properties(Sequence[str] | None, default:None) –The user properties whose digest the value carries, retiring the series when any of them changes; the password alone when
None, skipping the properties the user does not expose. -
clock(ClockInterface | None, default:None) –Reads the current instant, for the expiry and the rotation window; the system clock when
None.
create_remember_me_cookie
async
¶
Start a new series for user, and stage its first cookie.
The series and the value are one draw of randomness split in two — 33 bytes each, the length the store's column was sized around — so neither can be derived from the other.
consume_remember_me_cookie
async
¶
consume_remember_me_cookie(request: ServerRequestInterface, remember_me_details: RememberMeDetails) -> UserInterface
Check the presented value against the stored one, and hand the rest on.
The details the cookie carried stop being trusted the moment the stored token is read: everything the check needs comes from the store, and the details handed on are rebuilt from the stored token — the last use, the series and the value the rotation will spend.
Raises:
-
AuthenticationError–When the value is not a series and a value, when the stored token names another user, or when the series has not been used within its lifetime.
-
CookieTheftError–When the presented value was already spent — the cookie was copied, and the caller must be logged out with the thief.
process_remember_me
async
¶
process_remember_me(request: ServerRequestInterface, remember_me_details: RememberMeDetails, user: UserInterface) -> None
Rotate the stored value, unless the rotation window still holds.
The value the details carry is the one the consume rebuilt from the store: when the user was last seen, the series, and the value that was current. A rotation within the window changes nothing — the concurrent requests that raced one another keep the value they all presented. Past the window, a fresh value is drawn, the digest of the user's signature properties is bound to it, the store rotates, and the fresh cookie is staged for the response.
The store rotates only over the value the request presented: of two requests rotating it at once, one wins. The other stages no cookie — its value was never stored — and is let through when the stored value was rotated within the window; otherwise the value it carried was spent long ago, and that is a stolen cookie.
Raises:
-
AuthenticationError–When the digest the value carries no longer matches the user — a changed password.
-
CookieTheftError–When the rotation lost to anything but a rotation within the window.
clear_remember_me_cookie
async
¶
Clear the cookie, and drop the series the request presented.
The cookie the request itself carries names the series being left — a logout knows which login it ends by the cookie it drops. A cookie too malformed to read is ignored: the clearing must not fail the response over a value nobody wrote.
RememberMeCookie
dataclass
¶
RememberMeCookie(name: str, value: str | None, expires: datetime | None = None, path: str | None = '/', domain: str | None = None, secure: bool = False, httponly: bool = True, samesite: str | None = None)
One remember-me cookie, staged on the request until a response exists.
A handler sets or clears the cookie while the request is still being
authenticated — long before anything is sent — so it stages the whole
cookie here, and the response pass moves it onto the outgoing head. The
value is the cookie's own: None means the cookie is being cleared,
which is not the same as being set to nothing, because the caller that
staged a clear wants the browser to drop what it holds.
Attributes:
-
name(str) –The cookie's name.
-
value(str | None) –The cookie's value;
Noneto clear the cookie. -
expires(datetime | None) –When the cookie stops being kept;
Nonefor one that lives for the session. A cleared cookie carries none — clearing dates it behind now on its own. -
path(str | None) –The path the cookie is available under; the whole site by default.
-
domain(str | None) –The domain the cookie is available to; every host that reads it when
None. -
secure(bool) –Whether the cookie travels only over a secure connection.
-
httponly(bool) –Whether the cookie stays out of the scripts a page runs.
-
samesite(str | None) –Whether the cookie travels on cross-site requests —
"lax","strict"or"none"— orNoneto write no attribute.
header_value ¶
Return the value a Set-Cookie header carries for this cookie.
Setting and clearing are the one operation read two ways: a value is written with its expiry, and the lack of one writes the form a browser answers by dropping the cookie — dated behind now, on the same path and domain it was set under, because a browser tells its cookies apart by all three.
RememberMeDetails ¶
Who a remember-me cookie remembers, until when, and by what value.
The cookie's whole content in one value object: the identifier of the
user it remembers, the expiry the value stops counting at, and the value
the handler that issued it can check. The serialization is the format
itself — :meth:from_raw_cookie reads what :meth:__str__ writes, so a
cookie written by one handler is read by the same one, and the layout is
pinned rather than implied by a serializer's choices.
Record the identifier, the expiry and the handler's own value.
from_raw_cookie
classmethod
¶
Read a cookie's value back into the details it was written from.
The Set-Cookie header carries the value percent-encoded — the
separator among what it encodes — and a browser sends it back exactly
so, so the value is percent-decoded first; a value that holds no
escape reads the same either way.
A value carrying no separator at all was written base64-encoded as a whole, so it is decoded first — the layout then continues as always. A value that does not split into the four fields, whose identifier is not base64 in the URL-safe alphabet, or whose expiry is not a number, is not a cookie this flow issued, and is refused as such.
Parameters:
-
raw_cookie(str) –The cookie's value, exactly as the request carried it: percent-encoded, as the header wrote it, or already decoded.
Returns:
-
RememberMeDetails–The details the value was written from.
Raises:
-
AuthenticationError–When the value is not a remember-me cookie this flow could have written.
from_persistent_token
classmethod
¶
Write a persistent token's series and value into a cookie's value.
The persistent handler's value is the series and the token value it expects next, separated the way the cookie's own fields are — so the one separator layout serves both, and the handler reading the cookie back finds its two parts where it wrote them.
Parameters:
-
token(PersistentToken) –The persistent token a series stored.
-
expires(int) –The expiry the cookie stops counting at, as a Unix timestamp.
Returns:
-
RememberMeDetails–The details for the cookie that hands the token to the caller's
-
RememberMeDetails–next request.
with_value ¶
Return details carrying value in place of this one's own.
The rotation writes a new value into details it already read the rest of — the identifier and the expiry stand, only the value moves.
get_user_identifier ¶
Return the identifier of the user this cookie remembers.
get_expires ¶
Return the expiry this cookie stops counting at, as a Unix timestamp.
RememberMeHandlerInterface ¶
Bases: Protocol
Keeps the remember-me cookie of the request being handled.
A handler is the one voice on what the cookie holds: it writes the cookie a login asks for, checks the cookie a returning request presents, and clears the cookie a logout or a failure must drop. Every method takes the request the flow is running, because the cookie is staged on that request's own security state — there is no request stack to read the current one from, so the caller that holds the request hands it in.
The cookie each method sets or clears is not returned: it is staged on the request, and the response pass moves it onto the response.
create_remember_me_cookie
async
¶
Stage the remember-me cookie that remembers user.
Raises:
-
AuthenticationError–When the user cannot be remembered — a handler that signs its values may refuse one it cannot sign.
consume_remember_me_cookie
async
¶
consume_remember_me_cookie(request: ServerRequestInterface, remember_me_details: RememberMeDetails) -> UserInterface
Check the cookie remember_me_details was read into, and load its user.
Every cookie is spent by being used: a handler that stores its tokens rotates the stored value, and every handler stages a fresh cookie for the response to carry back.
Raises:
-
AuthenticationError–When the cookie does not check out — an unknown user, a value that no longer counts, a theft.
clear_remember_me_cookie
async
¶
Stage the clearing of the remember-me cookie.
ResponseListener ¶
Bases: EventSubscriberInterface
Writes the remember-me cookie a handler staged onto the outgoing head.
A handler sets or clears the cookie while the request is still being
authenticated — before any response exists — so it stages the whole
cookie on the request's security state, and this listener, on the
lifecycle's response event, is the pass that moves it: the finished
Set-Cookie value is appended to the headers that are about to leave,
beside whatever the response already carries.
A request whose state staged no cookie leaves the response untouched — most requests never present or earn one. This kernel has no sub-request mechanism, so every response event is the request's own; there is no main-request guard to keep, and none is kept.
SignatureRememberMeHandler ¶
SignatureRememberMeHandler(signature_hasher: SignatureHasher, user_provider: UserProviderInterface, options: Mapping[str, object] | None = None, logger: LoggerInterface | None = None, clock: ClockInterface | None = None)
Bases: AbstractRememberMeHandler
Signs the cookie's value, so the cookie vouches for itself.
The cookie's value is a signature over the user, the expiry and the user's covered fields — checked against the identifier before the user is even loaded, then against the loaded user's own fields, so a changed password retires every cookie issued before it. Nothing is stored: no series, no token value, which is also the limit — a single cookie cannot be revoked alone, only every cookie of the user, by changing what the signature covers. A handler that must revoke one login reaches for the persistent one instead.
A consumed cookie is reissued: the login it re-establishes stages a fresh cookie, signed until a new expiry, so a remembered session carries on without the user ever seeing a login page.
Record the hasher, the provider, the options and the clock.
Parameters:
-
signature_hasher(SignatureHasher) –Signs the cookie's value and checks it — the same hasher the login links use, bound to the user's covered fields.
-
user_provider(UserProviderInterface) –Loads the user a cookie names.
-
options(Mapping[str, object] | None, default:None) –The cookie's shape, merged over the defaults.
-
logger(LoggerInterface | None, default:None) –Where the flow's decisions are logged, or
None. -
clock(ClockInterface | None, default:None) –Reads the current instant, for the expiry each new cookie is signed until; the system clock when
None.
create_remember_me_cookie
async
¶
Stage a cookie signed for user, until a lifetime from now.
consume_remember_me_cookie
async
¶
consume_remember_me_cookie(request: ServerRequestInterface, remember_me_details: RememberMeDetails) -> UserInterface
Check the signature against the identifier, then against the user.
The first check — the HMAC alone, before the user is loaded — keeps
an unproven cookie from costing a user lookup; the second, in
:meth:process_remember_me, weighs the covered fields once the user
is there to be weighed.
Raises:
-
AuthenticationError–When the signature matches neither the identifier nor any secret, or the expiry has passed.
process_remember_me
async
¶
process_remember_me(request: ServerRequestInterface, remember_me_details: RememberMeDetails, user: UserInterface) -> None
Verify the signature against the loaded user, then reissue the cookie.
Raises:
-
AuthenticationError–When the covered fields no longer add up to the signed value — a changed password — or the expiry has passed.
CsrfTokenChecker ¶
Checks the token a request presents against the value stored for its id.
The route marker —
:class:~xtr_security_http.decorator.is_csrf_token_valid.IsCsrfTokenValid
— states which token id a route proves and where the request carries the
value; this service hands the presented value to the token manager, which
compares it with what it stored when the page was rendered. A request
that presents no value, or one the manager does not vouch for, is refused
with a 403: the caller is already identified, so a missing or wrong
proof is a forbidden request, not a challenge to authenticate.
The service is registered only where a token manager is: without one wired, the definition is dropped, so an application that ships no cross-site request forgery storage never builds a checker that cannot answer.
Build the checker over the manager that mints and vouches for tokens.
Parameters:
-
csrf_token_manager(CsrfTokenManagerInterface) –Compares a presented token value with the value stored under its id.
check
async
¶
Vouch for the value a request presented under the marker's token id.
Raises:
-
HTTPException–403— when the request presented no value, or one the manager does not vouch for.
IsGrantedChecker ¶
IsGrantedChecker(token_storage: TokenStorageInterface, access_decision_manager: AccessDecisionManagerInterface)
Decides a route's attribute over its subject, through the voters.
The route marker —
:class:~xtr_security_http.decorator.is_granted.IsGranted — states what
must be granted and how a denial answers; this service runs that statement
through the access-decision machinery, so the deciding lives in one place —
testable without the web framework, and reusable behind any other
enforcement mechanism.
The decision is made against the request's token, or the anonymous token
when no firewall ran. A denial raises
:class:~xtr_security_core.exception.AccessDeniedError carrying the
attribute, the subject and the decision — answered 403 by the
firewall's exception listener — or, when the marker states a
status_code, an :class:HTTPException answering with that status
directly.
The security scopes a route declared natively are ignored unless the
marker opted in: consume_security_scopes on the marker turns each
accumulated scope into an oauth2_scope(...) attribute the voter stack
must grant, one by one; without it, scopes stay what declaring them alone
ever makes them — documentation.
Build the checker over the request's storage and the decision manager.
Parameters:
-
token_storage(TokenStorageInterface) –Holds the token the firewall authenticated for this request.
-
access_decision_manager(AccessDecisionManagerInterface) –Decides the attribute over the subject.
check
async
¶
check(is_granted: IsGranted, subject: object = None, *, security_scopes: Sequence[str] = ()) -> None
Decide is_granted's attribute over subject, denying when it fails.
Parameters:
-
is_granted(IsGranted) –The route marker stating the attribute and how a denial answers.
-
subject(object, default:None) –The subject the attribute is decided over.
-
security_scopes(Sequence[str], default:()) –The request's accumulated security scopes, each decided as an
oauth2_scope(...)attribute the voters must grant — passed only where the marker opted in.
Raises:
-
AccessDeniedError–When the attribute (or an opted-in scope) is not granted and the marker states no
status_code. -
HTTPException–When the attribute is not granted and the marker states a
status_code— answered with that status.
SecurityTokenResolver ¶
Fills a route argument with the token the request authenticated.
Where :class:~xtr_security_http.resolver.user_value_resolver.UserValueResolver
hands an endpoint the user, this hands it the token — the roles
authentication settled on, the attributes an authenticator attached — for
an endpoint that decides something itself. An anonymous request against a
marker that does not allow it raises
:class:~xtr_security_core.exception.AuthenticationCredentialsNotFoundError,
answered 401; an optional marker yields None instead.
Build the resolver over the request's token storage.
Parameters:
-
token_storage(TokenStorageInterface) –Holds the token the firewall authenticated for this request.
resolve
async
¶
Return the token current_token asks for, or None when it may.
Raises:
-
AuthenticationCredentialsNotFoundError–When no token is authenticated and
current_tokenis notoptional.
UserValueResolver ¶
Fills a route argument with the user the request authenticated.
The route marker —
:class:~xtr_security_http.decorator.current_user.CurrentUser — states
what the argument wants: the class (or classes) the user must be, and
whether an anonymous request may yield None. This service reads that
statement against the request's token storage, so the type matching and
the two denials live in one place — testable without the web framework,
and reusable behind any other filling mechanism.
The denials stay distinct, so a caller can tell them apart: an anonymous
request against a marker that does not allow it raises
:class:~xtr_security_core.exception.AuthenticationCredentialsNotFoundError
(answered 401), while a user of another class raises
:class:~xtr_security_core.exception.UnsupportedUserError.
Build the resolver over the request's token storage.
Parameters:
-
token_storage(TokenStorageInterface) –Holds the token the firewall authenticated for this request.
resolve
async
¶
Return the user current_user asks for, or None when it may.
Raises:
-
AuthenticationCredentialsNotFoundError–When no user is authenticated and
current_useris notoptional. -
UnsupportedUserError–When the user is not of the class (or any of the classes)
current_userstates.
SecurityEvents ¶
The names of the security events, and the classes they belong to.
The named events — an interactive login, a user switch — are the ones an application listens for across the whole flow rather than at one authenticator, which is why they carry a name of their own instead of running under their class's qualified name.
:attr:ALIASES is the lookup between the two spellings: every event
class this package raises today, mapped to the name it runs under. The
class-keyed ones map to the qualified name the dispatcher derives; the
named ones — the interactive login, the user switch — map to the names
they carry.
INTERACTIVE_LOGIN
class-attribute
instance-attribute
¶
Announced after a user actively authenticated — a form submitted, a login link followed — as opposed to a session or a bearer token re-establishing the same user passively.
SWITCH_USER
class-attribute
instance-attribute
¶
Announced before a user switches to another by impersonating them, and before an impersonation is left.
ALIASES
class-attribute
instance-attribute
¶
ALIASES: Final[Mapping[type[Event], str]] = {AuthenticationTokenCreatedEvent: event_name_of(AuthenticationTokenCreatedEvent), CheckPassportEvent: event_name_of(CheckPassportEvent), CheckRefreshedUserEvent: event_name_of(CheckRefreshedUserEvent), InteractiveLoginEvent: INTERACTIVE_LOGIN, LoginFailureEvent: event_name_of(LoginFailureEvent), LoginSuccessEvent: event_name_of(LoginSuccessEvent), LogoutEvent: event_name_of(LogoutEvent), OidcAuthorizationRequestEvent: event_name_of(OidcAuthorizationRequestEvent), SwitchUserEvent: SWITCH_USER, TokenDeauthenticatedEvent: event_name_of(TokenDeauthenticatedEvent)}
Every event class this package raises today, mapped to the name it is dispatched under.
SecurityRequestAttributes ¶
Every key the security flow parks on a request's state bag or session.
The flow's steps hand each other what they learned through these keys —
the carrier holding the request's security state, the authenticators a
supports pass chose, the cookie a handler staged before a response
existed — and the user-facing edges of a login keep what a form or an
error page reads under the _security. spelling. One class holds
them all so no step invents its own key and no two steps disagree
about one.
ACCESS_DENIED_ERROR
class-attribute
instance-attribute
¶
The access-denied error of the request, kept for the error page that explains the denial.
AUTHENTICATION_ERROR
class-attribute
instance-attribute
¶
The last authentication error, kept for the page that answers a failed login.
LAST_USERNAME
class-attribute
instance-attribute
¶
The username the last login attempt carried, for the form to re-fill.
UNSUPPORTED_REASONS
class-attribute
instance-attribute
¶
Why each authenticator did not support the request, collected while the supports pass runs and read by the tooling that explains a firewall's decision.
RE_AUTHENTICATION_ATTRIBUTE
class-attribute
instance-attribute
¶
The security attribute a re-authentication was started for, so an entry point asking its question in several ways knows which one was asked here.
TARGET_PATH
class-attribute
instance-attribute
¶
The session key a login saves the path it interrupted under, formatted with the firewall's name — the page the flow returns the user to once they have authenticated.
SECURITY_STATE
class-attribute
instance-attribute
¶
The per-request carrier of the flow's state, parked on the request's state bag; everything the flow learns about one request gathers under this one key.
STATE_BAG
class-attribute
instance-attribute
¶
The kernel event's state bag, parked on the request a firewall chain's
caller hands to a listener's supports — the same bag the event
carries, so a listener asked from the request alone and one asked from
the event derive one carrier per request.
EXCEPTION_LISTENER
class-attribute
instance-attribute
¶
The exception listener of the request's matched firewall, handed from the request phase that ran the chain to the exception phase that answers the request's failure, and put away when the request finishes.
AUTHENTICATORS
class-attribute
instance-attribute
¶
The authenticators that supported the request, handed from the pass that asks to the pass that authenticates.
SKIPPED_AUTHENTICATORS
class-attribute
instance-attribute
¶
The authenticators that did not support the request, kept for the tooling that explains a firewall's decision.
ACCESS_CONTROL_ATTRIBUTES
class-attribute
instance-attribute
¶
The security attributes the matched access rule requires, handed from the pass that matches to the pass that decides.
FIREWALL_RUN
class-attribute
instance-attribute
¶
Marks the requests the firewall actually ran for, so the response pass stores the context only for those.
SESSION
class-attribute
instance-attribute
¶
The session the context listener built for the request, handed from the request half that read the token to the response half that stores it, so both halves of one request reach the same session.
SESSION_SAVED
class-attribute
instance-attribute
¶
Marks the requests whose session the response half already wrote through, so the finish half — which runs on every path — saves a session once per request and never twice.
PRE_AUTHENTICATED_USERNAME
class-attribute
instance-attribute
¶
Reserved for the username a pre-authenticated authenticator read from the request. Nothing parks it today: a request message is immutable and the pass that authenticates is handed the request as it arrived, so the pre-authenticated authenticators read the username again through their own extraction hook instead of handing one over.
LOGIN_LINK_PARAMETERS
class-attribute
instance-attribute
¶
The extra parameters a consumed login link carried, exposed to the handlers that answer the login.
REMEMBER_ME_COOKIE
class-attribute
instance-attribute
¶
The remember-me cookie a handler staged on the request before a response existed, moved onto the response by the response pass.
SWITCH_USER_USERNAME
class-attribute
instance-attribute
¶
The user a request asks to switch to, handed from the supports pass that read the parameter to the pass that carries the switch out.
PasswordSessionUser ¶
Bases: SessionUser, PasswordAuthenticatedUserInterface
A session's snapshot of a user that carried a password, with its digest.
The snapshot keeps the
:func:~xtr_security_core.user.password_digest.password_digest of the
password, never the hash, and :meth:get_password answers that digest:
the comparison weighing the reload reads a stored password of eight
characters that is the digest of the reloaded one as the same password,
so the user stays signed in until the password really changes.
Record who the user was, the roles it held, and its password's digest.
Parameters:
-
identifier(str) –The identifier the user was kept under.
-
roles(Sequence[str]) –The roles the user held.
-
password(str | None) –The digest of the user's password, or
Nonewhen the user carried none.
Raises:
-
InvalidArgumentError–When
identifieris empty.
get_password ¶
Return the digest of the user's password, or None when it carried none.
SessionAuthenticationStrategy ¶
SessionAuthenticationStrategy(strategy: str, csrf_token_storage: ClearableTokenStorageInterface | None = None)
Bases: SessionAuthenticationStrategyInterface
What a successful login does to the session the request reattached.
Three answers, one per strategy name:
NONE— the session is left as it is: the ID it reattached under is kept, for a firewall whose every request authenticates on its own and the session is only a carrier.MIGRATE— the session's attributes are carried to a fresh ID and the entry under the old one destroyed: a session fixation — an ID an attacker planted before the login — stops answering for the account the login just named. The CSRF tokens minted under the old ID are dropped with it, through the clearable token storage, so a value stolen before the rotation cannot answer after it.INVALIDATE— the session is emptied and its entry destroyed: nothing of the session before the login survives it.
The session is the one the request's security state carries — the one the context listener built from the request and parked there — so the ID this strategy rotates is the ID the response half writes the token back under, and not a second session built beside it.
An unknown strategy name is refused when the strategy is asked to act, not when it is built: the name is the application's configuration, and a configuration error is heard the first time the configured thing runs.
Record the strategy name and the CSRF storage a rotation clears.
Parameters:
-
strategy(str) –One of :attr:
NONE, :attr:MIGRATE, :attr:INVALIDATE. -
csrf_token_storage(ClearableTokenStorageInterface | None, default:None) –The clearable CSRF token storage, emptied when a migration rotates the session — the tokens minted under the old ID must not answer for the new. Only the migration clears it; the other strategies leave the storage alone.
MIGRATE
class-attribute
instance-attribute
¶
The session's ID is rotated, its attributes kept.
INVALIDATE
class-attribute
instance-attribute
¶
The session's ID is rotated, its attributes dropped.
on_authentication
async
¶
Move the request's session the way the configured strategy names.
Parameters:
-
request(ServerRequestInterface) –The request that authenticated, carrying the session on its security state.
-
token(TokenInterface) –The token the authentication settled on; the strategy itself does not read it, but a strategy of an application's own may.
Raises:
-
MissingStateBagError–When the request carries no state bag — no firewall chain ran for it.
-
MissingSessionError–When the request's security state carries no session — no stateful context listener ran for it, so there is no session for the strategy to move.
-
InvalidSessionStrategyError–When the configured strategy name is none of the three.
SessionAuthenticationStrategyInterface ¶
Bases: Protocol
Updates the session after a successful authentication.
A login is the moment a session's ID is most worth stealing: the account it now carries is the prize. What the session itself must do about that — carry its attributes to a fresh ID, or empty out entirely — is this interface's one call, made while the request that authenticated is still the one being answered, so the ID the response re-issues is the rotated one.
on_authentication
async
¶
Perform whatever changes the login asks of the session.
Parameters:
-
request(ServerRequestInterface) –The request that authenticated, carrying the session on its security state.
-
token(TokenInterface) –The token the authentication settled on.
SessionTokenSerializer ¶
Turns a security token into the JSON envelope a session keeps, and back.
A session holds JSON and nothing else, whatever storage keeps it, so a
token is kept as an envelope: {"v": 1, "kind": …, "state": …, "user":
…}. The kind names the token's class as module:qualified name, the
state is what the token's own to_session answers, and the user part is
either the user's own state — a user implementing
:class:~xtr_security_core.user.session_serializable_user_interface.SessionSerializableUserInterface,
named by its kind — or a snapshot of any other user: its identifier, its
roles, and the digest of its password, never the hash.
Reading is the mirror, and it never trusts the session: a kind is looked
up only among the classes this process already loaded — the subclasses of
the token and user contracts — and never imported, so a session can name
nothing but a class that was meant to be rebuilt from one. Anything that is
not such an envelope — another version, a kind no loaded class answers to,
a state its class refuses as malformed — reads as no token; an envelope
keeping no user rebuilds a token carrying none, for the caller to refuse.
A snapshot is rebuilt as a :class:SessionUser stand-in — a
:class:PasswordSessionUser when the user carried a password — for the
firewall to reload by its identifier.
encode ¶
Return the envelope a session keeps token in.
A switch's original is kept nested in the switch's state through this same method, so every refusal below holds for it too.
Raises:
-
InvalidArgumentError–When the token cannot be kept — its class defines no
from_sessionof its own, one of its attributes does not come back from JSON exactly as it went in, or the state of its user does not — naming the class or the attribute that cannot.
decode ¶
Rebuild the token a session kept as value, or None when it kept none.
None answers anything but an envelope this serializer writes, of
a token class loaded now, whose state and user part rebuild: a
malformed state is no token, not a failure. A user part of None
rebuilds the token with no user.
SessionUser ¶
Bases: UserInterface
Who a session's user was, and the roles it held — and nothing more.
A session holds JSON, and a user that cannot turn itself into JSON is kept as a snapshot instead: its identifier and its roles. This is what the snapshot is rebuilt as, so the request that reads the session knows who to reload — the firewall's providers load the user by this identifier, and this stand-in is never handed to one as a user of its own.
A user that carried a password is rebuilt as the
:class:~xtr_security_http.session.password_session_user.PasswordSessionUser
subclass instead, so the comparison weighing the reload still sees which
side stopped carrying one.
Record who the user was and the roles it held.
Raises:
-
InvalidArgumentError–When
identifieris empty.
is_sensitive ¶
Tell whether error should be hidden from the client at level.
An account-status failure that carries its own client-facing message is
never sensitive: it was raised to be shown. Otherwise, at ALL nothing
is hidden; at ACCOUNT_STATUS a disabled or locked account is revealed
but an unknown user is not; at NONE both are hidden.
mask ¶
Return error, or a bad-credentials error hiding it, at level.
A hidden failure becomes a
:class:~xtr_security_core.exception.BadCredentialsError chained to the real
one, so the client learns only that its credentials failed while the cause
survives on __cause__ for the log.
oauth2_scope ¶
Build the attribute string that asks for scopes.
oauth2_scope("books:read", "books:write") returns
"OAUTH2_SCOPE(books:read books:write)" — the attribute an access rule or
an IsGranted hands to
:class:OAuth2ScopeVoter.
Raises:
-
InvalidArgumentError–When called with no scopes, which would build an attribute that grants any scoped token.
parse_oauth2_scope ¶
Read the scopes out of an OAUTH2_SCOPE(...) attribute, or None.
The module-level spelling of
:meth:OAuth2ScopeVoter.get_required_scopes, kept for the callers that
hold a plain attribute rather than the voter: the exception listener, and
anything an application writes itself. Anything not a string reads as
None.
firewall_listener_order_of ¶
Return what @FirewallListenerOrder recorded on listener_class, or None.
Only the class's own declaration is read: a subclass states its place in the chain itself, or inherits none.
parked_session_of ¶
Return the session the request's security state carries, if it carries one.
The parked session is how this stack says a request has one: the context listener builds it while reattaching the request's token and parks it on the request's security state, and every later step of the same request — the login's session strategy, a logout, a form login's error page — reaches the same object through here. A request whose state carries none is a stateless one, or one no stateful machinery ran for.
get_target_path
async
¶
Return the URI the caller was heading for, when one was kept.
Parameters:
-
session(SessionInterface) –The request's session, where the path waits out the login.
-
firewall_name(str) –The firewall that started the authentication.
Returns:
-
str | None–The saved URI, or
Nonewhen this firewall kept none.
remove_target_path
async
¶
Drop the kept path, once the caller has been returned to it.
Parameters:
-
session(SessionInterface) –The request's session, where the path waited out the login.
-
firewall_name(str) –The firewall that started the authentication.
save_target_path
async
¶
Set the path the caller should be returned to once they authenticate.
Parameters:
-
session(SessionInterface) –The request's session, where the path waits out the login.
-
firewall_name(str) –The firewall that started the authentication, so its return trip never overwrites another firewall's.
-
uri(str) –The URI the interrupted request was heading for.