xtr_security_core ¶
The security core for xtr applications.
Users, tokens, roles, voters and the authorization decision — everything that needs no HTTP edge and no JSON Web Tokens. This module gathers the public surface so an application imports it from one place.
AuthenticationMethod ¶
The authentication methods a token can hold a proof of, named as RFC 8176 registers them.
They key the mapping
:meth:~xtr_security_core.authentication.token.token_interface.TokenInterface.get_authentication_proofs
returns, so that a trust resolver can require a specific one. The values are
those of the OpenID Connect amr claim, which a provider may extend beyond
this list — hence a set of names rather than a closed enumeration.
See https://www.rfc-editor.org/rfc/rfc8176.html#section-2.
UNSPECIFIED
class-attribute
instance-attribute
¶
A proof whose method the authenticator did not state; not a registered value.
FINGERPRINT
class-attribute
instance-attribute
¶
Fingerprint biometric.
GEOLOCATION
class-attribute
instance-attribute
¶
Use of geolocation information.
HARDWARE_KEY
class-attribute
instance-attribute
¶
Proof-of-possession of a hardware-secured key.
KNOWLEDGE_BASED
class-attribute
instance-attribute
¶
Knowledge-based authentication.
MULTIPLE_CHANNELS
class-attribute
instance-attribute
¶
Multiple-channel authentication, e.g. confirming a login over another channel.
MULTIPLE_FACTORS
class-attribute
instance-attribute
¶
Multiple-factor authentication, when the provider names no individual factor.
ONE_TIME_PASSWORD
class-attribute
instance-attribute
¶
One-time password, e.g. a TOTP.
PIN
class-attribute
instance-attribute
¶
Personal identification number or pattern.
PASSWORD
class-attribute
instance-attribute
¶
Password-based authentication.
RISK_BASED
class-attribute
instance-attribute
¶
Risk-based authentication.
SOFTWARE_KEY
class-attribute
instance-attribute
¶
Proof-of-possession of a software-secured key.
TELEPHONE_CALL
class-attribute
instance-attribute
¶
Confirmation by telephone call.
USER_PRESENCE
class-attribute
instance-attribute
¶
User presence test.
WINDOWS_INTEGRATED
class-attribute
instance-attribute
¶
Windows integrated authentication.
AuthenticationTrustResolver ¶
AuthenticationTrustResolver(recent_lifetime: int = 2 * 3600, very_recent_lifetime: int = 5 * 60, clock: ClockInterface | None = None)
Bases: AuthenticationTrustResolverInterface
Reads authentication strength from a token.
A token is authenticated when it carries a user, and fully authenticated
when it is also not a remembered one. The base resolver recognizes no
remembered token of its own, so :meth:is_remember_me is false here and
every authenticated token is fully authenticated; a resolver that knows a
remembered token overrides it.
Recency is answered on time alone, counted from whichever method was proven last in the token's authentication proofs.
Parameters:
-
recent_lifetime(int, default:2 * 3600) –Seconds during which an authentication counts as recent.
-
very_recent_lifetime(int, default:5 * 60) –Seconds during which it counts as very recent.
-
clock(ClockInterface | None, default:None) –The clock reading the current time; the system clock when
None.
Record the two recency windows and the clock that measures them.
is_authenticated ¶
Tell whether token carries a user.
is_remember_me ¶
Tell whether token was remembered; never, as no remembered token exists here.
is_full_fledged ¶
Tell whether token is authenticated and not merely remembered.
is_authenticated_recently ¶
Tell whether the last authentication proof is within the recent window.
The default answers on time alone. An application that wants a stricter
policy — a second factor, a password entered minutes ago — overrides
this method rather than the attribute it answers, and reads the same
proofs to do so. It repeats the :meth:is_full_fledged check the voter
already enforces, because it is also callable on its own.
is_authenticated_very_recently ¶
Tell whether the last authentication proof is within the very-recent window.
The bar for a step that must follow a fresh proof of the credentials, such as changing the password; an override is where "very recently" can mean a stronger proof rather than a shorter time.
AuthenticationTrustResolverInterface ¶
Bases: Protocol
Resolves the authentication status of a given token.
A voter granting IS_AUTHENTICATED asks only whether anyone is behind
the token; one granting IS_AUTHENTICATED_FULLY asks whether they proved
their credentials rather than being remembered; one granting
IS_AUTHENTICATED_RECENTLY asks how long ago they did. This contract
answers each without any voter having to know how a token was made.
is_authenticated ¶
Resolve whether token is authenticated.
is_remember_me ¶
Resolve whether token is authenticated using remember-me capabilities.
is_full_fledged ¶
Resolve whether token is fully authenticated.
is_authenticated_recently ¶
Resolve whether the user authenticated recently enough for a sensitive action.
is_authenticated_very_recently ¶
Resolve whether the user authenticated recently enough for the most sensitive actions.
A stricter bar than :meth:is_authenticated_recently.
PersistentToken ¶
Who a remember-me series remembers, and the value it expects next.
A remember-me login is a series of one-time values: each presentation of a value rotates it, and only the current one is kept. This is that entry — the identifier of the user it remembers, the series it belongs to, the value expected next, and when the value was last used.
Record who the token remembers, its series, its value and its last use.
Raises:
-
InvalidArgumentError–When the identifier, the series or the value is empty.
get_user_identifier ¶
Return the identifier of the user this token remembers.
TokenProviderInterface ¶
Bases: Protocol
Keeps the persistent remember-me token of every series.
A database backs this in an application, which is why every method is awaitable: the store is reached over I/O, and the remember-me flow that calls it runs async.
load_token_by_series
async
¶
Load the current token of series.
Raises an error when no token exists for the series. Which error is the provider's own, so its caller can tell a series that no longer exists apart from a store that failed.
delete_token_by_series
async
¶
Delete every token of series.
update_token
async
¶
Rotate series's token to token_value if it still holds expected_value.
The check and the write are one step — a conditional UPDATE in a
database — so of two requests rotating the same value at once only
one wins; the other is told so and stores nothing.
Returns:
-
bool–Truewhen the value was rotated and its last use recorded; -
bool–Falsewhen the stored value was no longerexpected_value.
Raises an error when no token exists for the series, as
:meth:load_token_by_series does.
create_new_token
async
¶
Store token as a first entry of a new series.
TokenVerifierInterface ¶
Bases: Protocol
Decides whether a presented value still matches a persistent token.
The plain check is equality, but a store that can afford it may accept a
slightly outdated value — the rotation window — and this is where that
policy plugs in. Comparisons must run in constant time
(:func:hmac.compare_digest), so a presented value cannot be timed out
of the real one.
AbstractToken ¶
Bases: TokenInterface
A user, the roles fixed at creation, and a bag of attributes.
Implements :class:~xtr_security_core.authentication.token.token_interface.TokenInterface.
The token's role names are decoupled from the user's roles on purpose:
they describe the authentication context, not the user's permanent role
assignment. That is why :meth:set_user only updates the user reference
and leaves the role names untouched. Concrete tokens derive from this and
add whatever their own kind needs.
A session keeps a token as JSON, through :meth:to_session and
:meth:from_session: the roles and the attributes here, and whatever a
concrete token adds in its own overrides. A token class is kept in a
session only when it defines :meth:from_session in its own body — the
rebuild must know every field the class adds, and an inherited one does
not.
Copy the roles fixed on this token; the user is set through :meth:set_user.
get_role_names ¶
Return the roles fixed on this token at creation.
get_user_identifier ¶
Return the identifier of the user, or the empty string for nobody.
set_user ¶
Set the authenticated user; the role names are left untouched.
get_attributes ¶
Return a read-only snapshot of the attributes attached to this token.
The mapping is a copy taken now, so a later
:meth:set_attribute does not change a mapping already returned.
set_attributes ¶
Replace every attribute attached to this token with attributes.
get_attribute ¶
set_attribute ¶
Attach value under name, replacing any attribute there.
get_authentication_proofs ¶
Return the authentication methods the user proved, each mapped to its last proof.
set_authentication_proofs ¶
Record the authentication methods the user proved, each mapped to its last proof.
to_session ¶
Return the state a session keeps this token as: its roles and attributes.
The user is not part of it — the code writing the session keeps the
user beside the state, and hands it back to :meth:from_session.
Every attribute must come back from JSON exactly as it went in, or
the token is refused when the session is written.
Parameters:
-
encode_token(Callable[[TokenInterface], dict[str, object]]) –How the session keeps a token, handed down for a token nesting another to keep that one the same way; a token nesting none leaves it unused.
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 as state, carrying user.
Built without the class's constructor, which asks for what the
session hands back separately: the roles come from state, so a
token restores the roles fixed when it was created, not the user's
current ones. Pure — no I/O — and every field is type-checked.
Parameters:
-
state(Mapping[str, object]) –What :meth:
to_sessionreturned. -
user(UserInterface | None) –The user the session kept beside the state, rebuilt;
Nonewhen it kept none, which a session token never should. -
decode_token(Callable[[object], TokenInterface | None]) –How the session rebuilds a token, handed down for a token nesting another; a token nesting none leaves it unused.
Raises:
-
InvalidArgumentError–When a field of
stateis missing or of the wrong type.
NullToken ¶
Bases: TokenInterface
A token carrying no user, no roles, no attributes: the anonymous caller.
An access decision is always made against a token; when authentication settled on nobody, it is made against this one. It answers every question about itself with nothing, and refuses anything that would make it someone: setting a user, an attribute or an authentication proof raises.
OfflineTokenInterface ¶
Bases: TokenInterface, Protocol
A token standing in for a user who is not the current caller.
:meth:~xtr_security_core.authorization.authorization_checker.AuthorizationChecker.is_granted_for_user
builds one to decide access for a given user — or for a guest — rather than
the one calling: a consent screen, a background worker. It carries that
user's roles, so role checks decide as they would for the user; how that
user authenticated is unknown, so a voter asked about authentication
strength refuses to decide on one that carries a user.
It adds nothing to :class:TokenInterface: it is a mark, declared by
inheriting from it, and read nominally —
OfflineTokenInterface in type(token).__mro__. It is deliberately not
runtime-checkable: with no member of its own, a structural check would
match every token.
PreAuthenticatedToken ¶
Bases: AbstractToken
A user proven by the request itself, the firewall that read it, and the roles.
Some requests carry the authenticated identity in themselves — a trusted header, a certificate, a pre-shared key. This is the token an authenticator settles on for those: the user, the firewall that read the identity, and the roles fixed at that moment.
Attributes:
-
firewall_name–The firewall (or unit of work) that read the identity.
Record the user, the firewall that read their identity, and the roles.
Raises:
-
InvalidArgumentError–When
firewall_nameis empty.
get_firewall_name ¶
Return the firewall (or unit of work) that read the user's identity.
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.
RememberMeToken ¶
Bases: AbstractToken
A user remembered from an earlier login, not freshly proven.
A remember-me cookie re-establishes who is calling without a password. The token carries the user and the firewall the cookie was issued for, with the user's own roles — a remembered login has no moment of its own to fix roles at, so it reads them from the user when the cookie is presented. It is an authenticated token, but a weaker one: a trust resolver tells it apart from a fully proven login.
Rebuilt from a session, it restores the roles it was created with: they were read from the user when the cookie was presented, and a role the user lost since is what the reload of the user weighs, not what the rebuild hides.
Attributes:
-
firewall_name–The firewall the remember-me cookie was issued for.
Record the remembered user and the firewall their cookie was issued for.
Raises:
-
InvalidArgumentError–When
firewall_nameis empty.
get_firewall_name ¶
Return the firewall the remember-me cookie was issued for.
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, with the roles it kept, not the user's.
Raises:
-
InvalidArgumentError–When a field of
stateis missing or of the wrong type, or the firewall is empty.
SwitchUserToken ¶
SwitchUserToken(user: UserInterface, firewall_name: str, roles: Sequence[str], original_token: TokenInterface, originated_from_uri: str | None = None)
Bases: UsernamePasswordToken
A user impersonating another one, with the way back kept.
Switching user re-authenticates as the target while keeping the token the switch started from, so the impersonator can return to themselves. For everything downstream the token is a full username/password token for the target user — the switch itself is the proof — plus the original token and, when the switch came from a request, where that request was.
A session keeps the original token nested in this one's state, the same way it keeps any token, so the way back survives the request too.
Attributes:
-
originated_from_uri–The URI the switch was made at, when it was made at one.
Record the target user, the original token, and where the switch happened.
Parameters:
-
user(UserInterface) –The user being switched to.
-
firewall_name(str) –The firewall the switch happened in.
-
roles(Sequence[str]) –The roles fixed on the target user's token.
-
original_token(TokenInterface) –The token of the user who switched.
-
originated_from_uri(str | None, default:None) –The URI the switch was made at, when it was.
Raises:
-
InvalidArgumentError–When
firewall_nameis empty.
get_original_token ¶
Return the token of the user who switched.
get_originated_from_uri ¶
Return the URI the switch was made at, or None when it was not.
to_session ¶
Return the switched token's state, the original kept nested as any token is.
from_session
classmethod
¶
from_session(state: Mapping[str, object], user: UserInterface | None, decode_token: Callable[[object], TokenInterface | None]) -> Self
Rebuild the switch a session kept, the original rebuilt as any token is.
Raises:
-
InvalidArgumentError–When a field of
stateis missing or of the wrong type, or the original is no token the session can rebuild.
TokenInterface ¶
Bases: Protocol
The result of authentication: who is calling, and what was decided about them.
A token names a user and the roles that authentication settled on. Those roles are fixed when the token is created, decoupled from whatever the live user object may report later, so a decision reads a stable snapshot. Attributes carry extra data an authenticator or a listener attached — the scopes of a bearer token, the client it was issued to. The authentication proofs record which methods the user proved, and when.
get_user_identifier ¶
Return the identifier of the user, or the empty string for nobody.
get_role_names ¶
Return the roles fixed on this token at creation.
set_user ¶
Set the authenticated user on this token.
Raises:
-
BadMethodCallError–When this token accepts no user.
get_attributes ¶
Return every attribute attached to this token, read-only.
set_attributes ¶
Replace every attribute attached to this token with attributes.
get_attribute ¶
set_attribute ¶
Attach value under name, replacing any attribute there.
get_authentication_proofs ¶
Return the authentication methods the user proved.
Each key is an
:class:~xtr_security_core.authentication.authentication_method.AuthenticationMethod
value, mapped to the Unix timestamp of the last proof of that method.
set_authentication_proofs ¶
Record the authentication methods the user proved.
Each key is an
:class:~xtr_security_core.authentication.authentication_method.AuthenticationMethod
value, mapped to the Unix timestamp of the last proof of that method.
UsernamePasswordToken ¶
Bases: AbstractToken
A user proven by a password, the firewall that did it, and the roles.
The token an authentication settles on when a user answered with a password. It carries the user, the firewall (or unit of work) that authenticated them, and the roles fixed at that moment — decoupled from the live user's roles, as every token in this library is. Open for subclassing, because a token can be a password token with something added — the switch-user token is one.
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.
TokenStorage ¶
Bases: TokenStorageInterface, ResetInterface
Holds the current token of one unit of work.
A scoped service: one instance per request, message or command, so two units of work never see each other's token. Its isolation comes from that scope alone — each unit is built a fresh, empty instance, and the instance goes with the unit. The container's resetter never touches it: it resets singletons only, since resetting a scoped instance from whichever unit ended first would clear the token of another still running.
It still satisfies
:class:~xtr_service_contracts.reset_interface.ResetInterface, for an
owner that holds one instance across several units of its own — a hand-built
storage reused between tasks — and must clear it itself in between. It
declares no __slots__, so instances stay weakly referenceable.
An initializer, when set, runs once — the first time the token is read, or just before one is stored — so the token can be produced lazily, only when something actually asks for it.
Start with no token.
get_token ¶
Return the current token, or None when none was set.
A pending initializer runs first, once.
set_token ¶
Store token as the current one, or clear it with None.
Storing a token runs any pending initializer first, so it cannot overwrite the token later; either way the initializer is dropped.
set_initializer ¶
Set the callable that produces the token the first time it is needed, or clear it.
TokenStorageInterface ¶
Bases: Protocol
The one place the authenticated token lives for a unit of work.
Authentication writes a token here; everything downstream — an access decision, a facade reading the current user, a listener turning an error into a response — reads it from here. Reading and writing are synchronous: the token is already in hand by the time it is stored.
AuthenticationEvents ¶
One name per authentication event, for listeners registered by name.
An event is keyed by the qualified name of its class, so a listener declared on a typed parameter and one registered under the matching constant here are registered for the same event. The constants serve where a class cannot be written — a listener whose event is chosen at runtime, a subscriber mapping names to methods.
AUTHENTICATION_SUCCESS
class-attribute
instance-attribute
¶
A user was authenticated by one authenticator.
Access ¶
Bases: IntEnum
A voter's answer to one access question.
Ordered on purpose: GRANTED above ABSTAIN above DENIED, so a
strategy can compare and count answers as integers. A voter that has no
opinion abstains rather than denying — abstaining leaves the decision to
the others, while denying weighs against access.
AccessDecision
dataclass
¶
What was decided, by which strategy, and every vote behind it.
A decision is not only a yes or no: it is the votes that produced it. The
manager fills one of these as the voters answer, so a refusal can be
explained — the :attr:message reads the denying voters' reasons. A nested
decision made while one is in progress shares the same record, so its votes
are gathered here too.
Attributes:
-
is_granted(bool) –The outcome, once the manager has decided.
-
votes(list[Vote]) –Every vote cast, in the order they were cast.
-
strategy(str | None) –The name of the strategy that decided, once set.
AccessDecisionManager ¶
AccessDecisionManager(voters: Sequence[VoterInterface] = (), strategy: AccessDecisionStrategyInterface | None = None)
Bases: AccessDecisionManagerInterface
Runs the voters for one attribute and reduces their votes with a strategy.
Deciding is on exactly one attribute at a time: a rule or a call asking for
several at once is refused, so that "granted" never quietly means "granted
one of these". The voters are asked in order; a voter that has declared,
through
:class:~xtr_security_core.authorization.voter.cacheable_voter_interface.CacheableVoterInterface,
that it never votes on this attribute or this subject type is skipped, and
that applicability is remembered so the next decision does not ask again.
A decision made by a voter while it votes — a closure asking a nested question — joins the decision already in progress, so every vote lands in one record.
Record the voters and the strategy, and bind any closure voters.
decide
async
¶
decide(token: TokenInterface, attributes: Sequence[object], subject: object = None, access_decision: AccessDecision | None = None) -> bool
Decide whether token may have the one attribute over subject.
AccessDecisionManagerInterface ¶
Bases: Protocol
Runs the voters for one attribute and reduces their votes with a strategy.
decide
async
¶
decide(token: TokenInterface, attributes: Sequence[object], subject: object = None, access_decision: AccessDecision | None = None) -> bool
Decide whether token may have the one attribute over subject.
Parameters:
-
token(TokenInterface) –The token to decide for.
-
attributes(Sequence[object]) –Exactly one attribute; more is refused.
-
subject(object, default:None) –The subject the attribute concerns, or
None. -
access_decision(AccessDecision | None, default:None) –A record to fill; a fresh one when omitted, or the one already in progress when this call is nested inside a vote.
Raises:
-
InvalidArgumentError–When
attributesdoes not hold exactly one.
AccessDecisionStrategyInterface ¶
Bases: Protocol
Reduces the voters' answers to a single decision.
The voters each granted, denied or abstained; a strategy says what the collection of those answers means — whether one grant is enough, whether a single denial is fatal, what to do when they all abstain or split evenly.
The answers arrive lazily: results is an async iterator that runs the
next applicable voter only when the strategy pulls from it, so a strategy
that can settle early leaves the voters it never reaches unasked.
decide
async
¶
Return whether access is granted given the voters' results.
AffirmativeStrategy
dataclass
¶
Bases: AccessDecisionStrategyInterface
Grants as soon as one voter grants, whatever the others say.
The permissive default: a single grant is enough, and a denial only counts
when nobody granted. It stops at the first grant, so the voters after it are
never asked. When every voter abstained, the answer is
:attr:allow_if_all_abstain.
Attributes:
-
allow_if_all_abstain(bool) –What to answer when no voter had an opinion.
decide
async
¶
Grant on the first grant, pulling no further; else deny or the abstain rule.
AuthenticatedVoter ¶
Bases: CacheableVoterInterface
Votes on the authentication attributes, most restrictive to least restrictive.
IS_AUTHENTICATED_VERY_RECENTLY, IS_AUTHENTICATED_RECENTLY,
IS_AUTHENTICATED_FULLY, IS_AUTHENTICATED_REMEMBERED and
IS_AUTHENTICATED read how strongly — and how recently — the token was
authenticated; IS_REMEMBERED and IS_IMPERSONATOR how it came to be;
PUBLIC_ACCESS, asked alone, is always granted. It defers every question
of strength to a trust resolver, so it need not know how a token was made.
Record the resolver that reads a token's authentication strength.
vote
async
¶
vote(token: TokenInterface, subject: object, attributes: Sequence[object], vote: Vote | None = None) -> Access
Grant when a recognised attribute holds for token, else deny or abstain.
Raises:
-
InvalidArgumentError–When asked about authentication for an offline token that carries a user — how that user authenticated is unknown.
supports_attribute ¶
Tell whether attribute is one this voter reads.
supports_type ¶
Vote on any subject: authentication is read from the token alone.
AuthorizationChecker ¶
AuthorizationChecker(token_storage: TokenStorageInterface, access_decision_manager: AccessDecisionManagerInterface)
Bases: AuthorizationCheckerInterface, GuestAuthorizationCheckerInterface
The main authorization point: answers for the current token, or for a given user.
:meth:is_granted reads the token from the storage — the anonymous
:class:~xtr_security_core.authentication.token.null_token.NullToken when
none is set, or when the one set carries no user.
:meth:is_granted_for_user steps outside the current caller: it builds an
offline token — an
:class:~xtr_security_core.authentication.token.offline_token_interface.OfflineTokenInterface
— from the user's own roles, or none for a guest, and decides against that.
Any question asked of this checker while that decision runs, by a voter
that has the checker injected, is decided against the same offline token.
Record where the current token lives and who decides.
is_granted
async
¶
is_granted(attribute: object, subject: object = None, access_decision: AccessDecision | None = None) -> bool
Tell whether the current token may have attribute over subject.
is_granted_for_user
async
¶
is_granted_for_user(user: UserInterface | None, attribute: object, subject: object = None, access_decision: AccessDecision | None = None) -> bool
Tell whether user — or a guest, for None — may have attribute.
AuthorizationCheckerInterface ¶
Bases: Protocol
Decides an attribute against the token of the current unit of work.
The everyday way to ask an authorization question: it reads the current token from the storage — the anonymous token when none is set — and hands it, the attribute and the subject to the decision manager.
is_granted
async
¶
is_granted(attribute: object, subject: object = None, access_decision: AccessDecision | None = None) -> bool
Tell whether the current token may have attribute over subject.
CacheableVoterInterface ¶
Bases: VoterInterface, Protocol
A voter that declares which attributes and subject types it votes on.
A decision manager asks many voters about the same kinds of attribute and
subject over and over. A voter that can answer, cheaply and without state,
whether it has anything to say about an attribute or a subject type lets
the manager remember that answer and skip the voter when it does not —
turning a per-request scan into a lookup. It is a
:class:~xtr_security_core.authorization.voter.voter_interface.VoterInterface
that adds this declaration.
ClosureVoter ¶
Bases: CacheableVoterInterface
Grants an attribute that is itself the check: a callable.
Where a role is a string to match, a closure is a decision to run. The
attribute is a callable taking an
:class:~xtr_security_core.authorization.is_granted_context.IsGrantedContext
and the subject, and answering true or false — synchronously or not. It
covers the checks too specific for a reusable voter ("is this token the
owner of this order?") without an expression language.
Each closure's nested questions are decided against the same token, each in a decision of its own, so the voter can report the reasons they gave and forward a re-authentication one of them requested. The voter needs the decision manager for that; the manager binds itself when it is built from a voter list containing this one.
Start unbound; the decision manager binds itself when it is built.
bind_manager ¶
Record the decision manager a closure's nested questions are decided by.
Raises:
-
InvalidArgumentError–When already bound to a different manager, which would silently route a shared voter's nested questions to whichever manager was built last.
supports_attribute ¶
Never vote on a string attribute: the attributes read here are callables.
vote
async
¶
vote(token: TokenInterface, subject: object, attributes: Sequence[object], vote: Vote | None = None) -> Access
Run each callable attribute: grant on the first that returns true.
Raises:
-
InvalidArgumentError–When the voter was never bound to a decision manager.
ConsensusStrategy
dataclass
¶
Bases: AccessDecisionStrategyInterface
Grants when grants outnumber denials, and vice versa.
The majority rules, so every voter is asked: the tally is only complete once
the last one has answered. A tie between grants and denials is broken by
:attr:allow_if_equal_granted_denied; a vote in which everyone abstained
is decided by :attr:allow_if_all_abstain.
Attributes:
-
allow_if_all_abstain(bool) –What to answer when no voter had an opinion.
-
allow_if_equal_granted_denied(bool) –What to answer on a grant/deny tie.
decide
async
¶
Compare grants to denials, breaking a tie and an all-abstain by the flags.
GuestAuthorizationCheckerInterface ¶
Bases: UserAuthorizationCheckerInterface, Protocol
Extends the user authorization checker with support for guests.
A None user means a guest: the attribute is voted on with no user and
no roles.
is_granted_for_user
async
¶
is_granted_for_user(user: UserInterface | None, attribute: object, subject: object = None, access_decision: AccessDecision | None = None) -> bool
Tell whether user — or a guest, for None — may have attribute.
Parameters:
-
user(UserInterface | None) –The user to decide for, or
Nonefor a guest. -
attribute(object) –A single attribute to vote on.
-
subject(object, default:None) –The subject the attribute concerns, or
None. -
access_decision(AccessDecision | None, default:None) –A record explaining the decision, if given.
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.
PriorityStrategy
dataclass
¶
Bases: AccessDecisionStrategyInterface
Grants or denies on the first voter that does not abstain.
Order is everything: the voters are asked in the order they were given, and
the first one to grant or deny settles it — the rest are never consulted,
because the strategy stops pulling from the voters the moment one has an
opinion. When all of them abstain, the answer is :attr:allow_if_all_abstain.
Attributes:
-
allow_if_all_abstain(bool) –What to answer when no voter had an opinion.
decide
async
¶
Answer on the first non-abstaining result, pulling no further; else the abstain rule.
RoleHierarchyVoter ¶
Bases: RoleVoter
Uses a role hierarchy to determine the roles granted to the user before voting.
The same as :class:~xtr_security_core.authorization.voter.role_voter.RoleVoter,
except the token's roles are first expanded through the hierarchy — so a
token holding ROLE_ADMIN is granted ROLE_USER when the hierarchy
says the one reaches the other.
Record the hierarchy to expand the token's roles through.
RoleVoter ¶
Bases: CacheableVoterInterface
Votes if any attribute starts with a given prefix — ROLE_ by default.
Grants one when it is among the token's roles. The prefix keeps it out of the way of voters that read other kinds of attribute.
Record the prefix that marks the attributes this voter reads.
vote
async
¶
vote(token: TokenInterface, subject: object, attributes: Sequence[object], vote: Vote | None = None) -> Access
Grant on the first prefixed attribute among the token's roles; else deny or abstain.
supports_attribute ¶
Tell whether attribute carries this voter's prefix.
supports_type ¶
Vote on any subject: a role is checked without regard to it.
TraceableAccessDecisionManager ¶
TraceableAccessDecisionManager(manager: AccessDecisionManagerInterface, recorder: Callable[[Mapping[str, object]], None] | None = None)
Bases: AccessDecisionManagerInterface
Decorates a decision manager to log the voters and the decisions they made.
Each decision is logged with its attributes, its subject, the votes cast —
fed through :meth:add_voter_vote by whatever listens to the votes — and
its result. Meant for one unit of work: the log grows with every decision,
so the manager is built per request and :meth:reset between them.
A decision a closure asks for is made by the decorated manager directly, so it is not logged as a decision of its own; the votes it collects are still fed into the decision in progress.
A recorder hears of every decision as it finishes, its votes in: the
log is this manager's, while a recorder keeps the decisions wherever the
tooling reads them from — the profiler's record of the request, say.
Wrap manager, starting with an empty log.
Parameters:
-
manager(AccessDecisionManagerInterface) –The manager that decides.
-
recorder(Callable[[Mapping[str, object]], None] | None, default:None) –Called with each finished decision — its log entry plus the
strategythat decided it — orNoneto keep the log alone.
decide
async
¶
decide(token: TokenInterface, attributes: Sequence[object], subject: object = None, access_decision: AccessDecision | None = None) -> bool
Decide through the decorated manager, logging the decision.
add_voter_vote ¶
add_voter_vote(voter: VoterInterface, attributes: Sequence[object], vote: Access, reasons: Sequence[str] = ()) -> None
Record a voter's vote on the decision being logged.
A vote cast while no decision of this manager is in progress is ignored: there is no log entry to attach it to.
get_strategy ¶
Return the name of the strategy that made the last decision, or "-".
get_voters ¶
Return each voter that voted, one per voter class.
get_decision_log ¶
Return every finished decision, in the order it finished.
TraceableVoter ¶
Bases: CacheableVoterInterface
Wraps a voter and announces each answer as a :class:VoteEvent.
A transparent decoration: it delegates every vote to the voter it wraps, then dispatches an event carrying the answer and the reasons behind it, so a decision can be traced without the decision manager or the wrapped voter knowing tracing exists. Its applicability declarations follow the wrapped voter's when that voter is cacheable, and otherwise say yes to everything.
Record the voter to trace and the dispatcher to announce votes on.
vote
async
¶
vote(token: TokenInterface, subject: object, attributes: Sequence[object], vote: Vote | None = None) -> Access
Delegate the vote, then announce the answer and its reasons.
supports_attribute ¶
Follow the wrapped voter when it is cacheable, else say yes.
supports_type ¶
Follow the wrapped voter when it is cacheable, else say yes.
UnanimousStrategy
dataclass
¶
Bases: AccessDecisionStrategyInterface
Grants only when not one voter denies.
The strict one: a single denial refuses, however many voters granted, and it
stops at the first denial without asking the rest. It grants when at least
one voter granted and none denied, and falls back to
:attr:allow_if_all_abstain when every voter abstained.
Attributes:
-
allow_if_all_abstain(bool) –What to answer when no voter had an opinion.
decide
async
¶
Refuse on the first denial; grant on a grant; else fall to the abstain rule.
UserAuthorizationCheckerInterface ¶
Bases: Protocol
Checks the authorization of a given user, without needing a session.
For the questions asked about someone other than the caller: a consent screen deciding what the user being consented-for may do, a worker deciding for the account a job belongs to.
is_granted_for_user
async
¶
is_granted_for_user(user: UserInterface, attribute: object, subject: object = None, access_decision: AccessDecision | None = None) -> bool
Tell whether user may have attribute over subject.
Parameters:
-
user(UserInterface) –The user to decide for.
-
attribute(object) –A single attribute to vote on.
-
subject(object, default:None) –The subject the attribute concerns, or
None. -
access_decision(AccessDecision | None, default:None) –A record explaining the decision, if given.
Vote
dataclass
¶
Vote(voter: object | None = None, result: Access = Access.ABSTAIN, reasons: list[str] = list(), extra_data: dict[str, object] = dict())
What one voter answered, and why.
A decision collects a vote per voter that had an opinion, so a refusal can be explained rather than merely returned. A voter fills in its reasons as it decides; the manager records the answer it returned.
Attributes:
-
voter(object | None) –The voter that cast this, once the manager records it. Held loosely — the record does not depend on the voter's contract.
-
result(Access) –The answer the voter gave.
-
reasons(list[str]) –Human-readable reasons the voter added.
-
extra_data(dict[str, object]) –Anything else the voter wants a reader of the decision to see.
re_authentication_attribute
property
¶
The denied attribute a fresh authentication could grant, if one was requested.
request_re_authentication ¶
Tell the firewall a fresh authentication could grant the attribute this vote denies.
Also used for an attribute a closure this vote ran was denied. The firewall then starts a re-authentication rather than answering with a refusal. With a strategy other than the affirmative one, another voter denying the same attribute can leave the user denied after re-authenticating.
Voter ¶
Bases: CacheableVoterInterface, ABC
Turns "does this voter grant this attribute?" into a single answer.
Most voters share a shape: for each attribute they recognise, they decide
yes or no. This template walks the attributes, asks
:meth:vote_on_attribute about each one it :meth:supports, and turns the
yes-or-no answers into the three-valued result — granted the moment one is
granted, denied when it recognised attributes but granted none, abstained
when it recognised none.
It declares itself cacheable but assumes nothing: :meth:supports_attribute
and :meth:supports_type say yes to everything, so a plain subclass is
always consulted. A subclass that knows better narrows them.
vote
async
¶
vote(token: TokenInterface, subject: object, attributes: Sequence[object], vote: Vote | None = None) -> Access
Answer over attributes by asking :meth:vote_on_attribute about each.
supports_attribute ¶
Say yes to any attribute; a subclass that knows better narrows this.
supports_type ¶
Say yes to any subject type; a subclass that knows better narrows this.
supports
abstractmethod
¶
Tell whether this voter has anything to say about attribute.
vote_on_attribute
abstractmethod
async
¶
vote_on_attribute(attribute: object, subject: object, token: TokenInterface, vote: Vote | None) -> bool
Decide whether token is granted attribute over subject.
VoterInterface ¶
Bases: Protocol
Answers whether a token may have an attribute over a subject.
A voter is asked about one access question — an attribute, and the subject it concerns — and answers granted, denied, or abstained. It reads whatever it needs from the token, and because a voter may check ownership against a store, voting is asynchronous.
vote
async
¶
vote(token: TokenInterface, subject: object, attributes: Sequence[object], vote: Vote | None = None) -> Access
Answer whether token may have attributes over subject.
Parameters:
-
token(TokenInterface) –The token the decision is being made for.
-
subject(object) –The thing the attributes concern, or
None. -
attributes(Sequence[object]) –The attributes asked about.
-
vote(Vote | None, default:None) –A record to fill with the reasons behind the answer, if given.
AuthenticationEvent
dataclass
¶
Bases: Event
Carries the token an authentication settled on.
The shared base of the events raised around a successful authentication.
Derive from it and add what a particular moment needs; every one of them
answers :meth:get_authentication_token.
Attributes:
-
token(TokenInterface) –The token the authentication settled on.
get_authentication_token ¶
Return the token this event is about.
AuthenticationSuccessEvent
dataclass
¶
Bases: AuthenticationEvent
Announces that authentication succeeded and settled on a token.
Dispatched once a token has been created for an authenticated user, before
it is put to use. A listener reads the token — through the inherited
:meth:~xtr_security_core.event.authentication_event.AuthenticationEvent.get_authentication_token
— to react to a successful authentication (a post-authentication account
check, an audit line), and may stop the event to keep the listeners after
it from running.
VoteEvent
dataclass
¶
VoteEvent(voter: VoterInterface, subject: object, attributes: Sequence[object], vote: Access, reasons: tuple[str, ...] = ())
Bases: Event
Announces one voter's answer, for tracing and audit.
Dispatched by a
:class:~xtr_security_core.authorization.voter.traceable_voter.TraceableVoter
each time the voter it wraps answers, so a listener can record who voted
what, on which attributes, over which subject, and why — without the
decision manager knowing anything about tracing.
Attributes:
-
voter(VoterInterface) –The voter that cast the answer.
-
subject(object) –The subject the attributes concerned, or
None. -
attributes(Sequence[object]) –The attributes voted on.
-
vote(Access) –The answer the voter gave.
-
reasons(tuple[str, ...]) –The reasons the voter recorded, if any.
AccessDeniedError ¶
AccessDeniedError(message: str = 'Access Denied.', *, attributes: Sequence[object] = (), subject: object = None, access_decision: AccessDecision | None = None)
Bases: SecurityError
Authorization refused a known caller.
Distinct from an authentication failure: who is calling was established;
what they asked to do was not permitted. When the caller turns out not to
be fully authenticated, an entry point may answer this with a challenge
instead of a plain refusal; otherwise it becomes a 403. When a decision is
passed, its :attr:~xtr_security_core.authorization.access_decision.AccessDecision.message
— the denying voters' reasons — is appended to the error message.
Attributes:
-
attributes(tuple[object, ...]) –The attributes that were checked (one, in this library).
-
subject(object) –The subject the attributes were checked against, if any.
-
access_decision(AccessDecision | None) –The decision that refused, with its votes, if built.
Record what was checked, against what, and the decision that refused.
AccountExpiredError ¶
AccountStatusError ¶
AccountStatusError(user: UserInterface | None = None, message: str | None = None, *, message_key: str | None = None, message_data: Mapping[str, object] | None = None)
Bases: AuthenticationError
Authentication is refused because of the account's own state.
The credentials were correct: the account is disabled, locked, or expired.
A user checker raises one of the subclasses; whether the client is told the
real reason or only that its credentials failed is decided by the exposure
level (see :func:~xtr_security_http.authentication.is_sensitive).
A session keeps none of the user: rebuilt from one, the error names no user.
Attributes:
-
user(UserInterface | None) –The user whose account state refused authentication.
Record the user whose account state refused authentication.
from_session
classmethod
¶
Rebuild the error a session kept, naming no user — the session kept none.
AuthenticationCredentialsNotFoundError ¶
AuthenticationCredentialsNotFoundError(message: str | None = None, *, message_key: str | None = None, message_data: Mapping[str, object] | None = None)
Bases: AuthenticationError
No authentication credentials were found in the request.
Distinct from rejected credentials: nothing was presented at all, so the caller is anonymous where authentication was required.
AuthenticationError ¶
AuthenticationError(message: str | None = None, *, message_key: str | None = None, message_data: Mapping[str, object] | None = None)
Bases: SecurityError
Authentication failed: who is calling could not be established.
An authentication error separates two messages. The one passed to
:class:Exception is internal — it may name a user, a claim or a reason,
and belongs in a log, never in a response. :attr:message_key is the safe
public text a client may see, and :attr:message_data the values a
presentation layer substitutes into it. Keeping them apart is what lets a
failure be logged in full while the client learns only that credentials
were rejected.
A failed login that redirects keeps its error in the session for the page
that renders the form again, and a session keeps the public half only:
:meth:to_session answers the key and the data, and :meth:from_session
rebuilds an error of the same class whose internal message is the key —
the internal message never reaches the session store.
Attributes:
-
message_key(str) –Safe, public text describing the failure.
-
message_data(dict[str, object]) –Values a presentation layer may substitute into the key.
Record the internal message and the safe public key and data.
Parameters:
-
message(str | None, default:None) –The internal message; defaults to the public key.
-
message_key(str | None, default:None) –The safe public text; defaults to :attr:
MESSAGE_KEY. -
message_data(Mapping[str, object] | None, default:None) –Values for the public key.
get_message_data ¶
Return the values a presentation layer substitutes into the key.
to_session ¶
Return the public half of this error, for a session to keep.
The key, and the entries of the data that come back from JSON exactly as they went in; an entry that would not is left out rather than refusing the error, since the data only decorates the key. The internal message is not part of it: it may name a user or a reason, and belongs in a log, never in a store outside the process.
from_session
classmethod
¶
Rebuild an error a session kept, as this class, from its public half.
The class's constructor is not run — a subclass's asks for what the
session never kept, a user or a status — so a subclass carrying more
than the key and the data overrides this to settle the rest. The
rebuilt error's internal message is the key: str(error) reads it.
AuthenticationServiceError ¶
AuthenticationServiceError(message: str | None = None, *, message_key: str | None = None, message_data: Mapping[str, object] | None = None)
Bases: AuthenticationError
A service authentication relies on failed.
A database that answers a user lookup, a remote key set that verifies a token — when one of these is unreachable, the caller is neither accepted nor rejected: the attempt could not be completed at all.
BadCredentialsError ¶
BadCredentialsError(message: str | None = None, *, message_key: str | None = None, message_data: Mapping[str, object] | None = None)
Bases: AuthenticationError
The credentials presented were rejected.
The public catch-all of authentication: a wrong password, a malformed token, or a masked sensitive failure all surface as this, so a client learns only that its credentials did not work.
BadMethodCallError ¶
Bases: SecurityError
A method was called that this object refuses by design.
The anonymous token answers every question about itself but accepts no user, attribute or authentication proof; the placeholder provider of a firewall that has none loads nobody. Calling such a method is a mistake in the caller, not a state to recover from.
CookieTheftError ¶
CookieTheftError(message: str | None = None, *, message_key: str | None = None, message_data: Mapping[str, object] | None = None)
Bases: AuthenticationError
A remember-me cookie carried a value that was already spent.
A remember-me value is one-time: presenting it rotates it. The same value arriving twice means the cookie was copied — stolen — and the series it belongs to is dropped so the thief and the owner are both logged out.
CredentialsExpiredError ¶
CustomUserMessageAccountStatusError ¶
CustomUserMessageAccountStatusError(message_key: str, *, user: UserInterface | None = None, message_data: Mapping[str, object] | None = None, message: str | None = None)
Bases: AccountStatusError
An account-status failure whose public text is chosen at the raise site.
Deliberately shown to the client rather than masked: a checker with a safe, specific reason ("your subscription has lapsed") raises this with that reason as the message key.
Record the public message key and the values it substitutes.
CustomUserMessageAuthenticationError ¶
CustomUserMessageAuthenticationError(message_key: str, *, message_data: Mapping[str, object] | None = None, message: str | None = None)
Bases: AuthenticationError
An authentication failure whose public text is chosen at the raise site.
Where the ordinary errors mask their cause, this one is deliberately shown to the client: an authenticator that has a safe, specific reason to give ("your account is not yet activated") raises this with that reason as the message key.
Record the public message key and the values it substitutes.
DisabledError ¶
ExpiredSignatureError ¶
Bases: SecurityError
A signature is sound but past its expiry.
The secret matched and the covered fields did not change; only the moment the hash was valid until has passed. A flow that distinguishes this from an invalid signature can tell the caller to start over rather than that its link or cookie was never issued.
InsufficientAuthenticationError ¶
InsufficientAuthenticationError(message: str | None = None, *, message_key: str | None = None, message_data: Mapping[str, object] | None = None)
Bases: AuthenticationError
Authentication succeeded, but not to the level this resource needs.
Raised when access is denied to a caller who is not fully authenticated: the answer is to authenticate more strongly, not to be forbidden outright.
InvalidArgumentError ¶
Bases: SecurityError, ValueError
A declaration, configuration or call was malformed.
A decision asked for on several attributes at once, an attribute read from
a token that carries none, a firewall referring to a provider that is not
configured — mistakes caught where they are made. Also a
:class:ValueError, so code guarding its configuration with
except ValueError keeps working.
InvalidSignatureError ¶
Bases: SecurityError
A signature matches neither the secret nor the fields it claims.
The hash was forged, or something it covers changed: another user, a rotated password, parameters it was not bound with. Nothing about the request is sound, so nothing is said about why.
LockedError ¶
SecurityError ¶
Bases: Exception
Base class for every error raised by this library.
Catch this to handle anything authentication or authorization can go wrong with; catch a subclass to handle one cause. Every subclass carries the data a caller needs as typed attributes and composes its own message from them.
TooManyLoginAttemptsAuthenticationError ¶
Bases: AuthenticationError
Login is refused because the caller failed too many times.
A throttling listener raises this once the failed attempts cross its limit. The public key says how long the caller must wait, when the limiter could say: the wait is the only thing the caller can act on.
Rebuilt from a session, it reads the wait back from its own data, where
the key's %minutes% keeps it.
Attributes:
-
threshold(int | None) –The minutes the caller must wait, or
Nonewhen the wait is not quantified.
Record the wait and compose the public key from it.
Parameters:
-
threshold(int | None, default:None) –The minutes the caller must wait, if the limiter could count them.
from_session
classmethod
¶
Rebuild the error a session kept, the wait read back from %minutes%.
UnsupportedUserError ¶
Bases: SecurityError, TypeError
A user of the wrong class reached a provider, checker or resolver.
Also a :class:TypeError: the object is not the kind of user the code was
configured to work with, a mistake in wiring rather than in credentials.
UserNotFoundError ¶
UserNotFoundError(user_identifier: str | None = None, message: str | None = None, *, message_data: Mapping[str, object] | None = None)
Bases: AuthenticationError, LookupError
No user matched the identifier presented.
Also a :class:LookupError, so a provider's caller may treat a missing
user like any other failed lookup. Its public key is the one
:class:~xtr_security_core.exception.bad_credentials_error.BadCredentialsError
carries — "Invalid credentials." — rather than anything naming the
identifier: a distinct key would tell a client that a user does not exist,
a way to enumerate accounts, so the identifier stays on
:attr:user_identifier for logs alone.
A session keeps none of the identifier, for the same reason: rebuilt from one, the error names no identifier.
Attributes:
-
user_identifier(str | None) –The identifier that matched no user.
Record the identifier that matched no user.
from_session
classmethod
¶
Rebuild the error a session kept, naming no identifier — the session kept none.
RoleHierarchy ¶
Bases: RoleHierarchyInterface
Expands roles through a declared hierarchy, cycles and wildcards included.
The hierarchy maps a role to the roles it reaches directly:
{"ROLE_ADMIN": ["ROLE_USER"]} makes ROLE_ADMIN reach ROLE_USER.
Reaching is transitive — a role reaches what its children reach — and safe
against cycles: each role is expanded once.
A * in a key is a placeholder that captures a segment of a matching
role and substitutes it into the values:
{"ROLE_TENANT_*_ADMIN": ["ROLE_TENANT_*_USER"]} makes
ROLE_TENANT_42_ADMIN reach ROLE_TENANT_42_USER. Several * in
one key are captured left to right and substituted into the values in the
same order.
Split the declared hierarchy into exact keys and wildcard patterns.
Raises:
-
InvalidArgumentError–When a wildcard key's value asks for more
*placeholders than the key can capture, which would substitute the empty string for the surplus.
get_reachable_role_names ¶
Return roles and every role they reach, transitively.
The expansion of a given set of roles is memoised, so a voter asking the same question every decision runs the search once.
Raises:
-
InvalidArgumentError–When expansion reaches
_MAX_REACHABLEroles, which a finite hierarchy never does — a wildcard entry feeding its own output would otherwise expand without bound.
get_parent_role_names ¶
Return roles and every role of the hierarchy that reaches one of them.
The inverse question of :meth:get_reachable_role_names: which roles,
when held, grant one of roles. Only the declared roles are
considered — a wildcard key is a pattern, not a role anyone can hold.
RoleHierarchyInterface ¶
Bases: Protocol
Turns the roles a token holds into every role they imply.
A role may stand for others: an administrator's role reaches a user's. A voter should not have to know the hierarchy — it asks this to expand the token's roles first, then checks the one it wants against the result.
get_reachable_role_names ¶
Return roles and every role they reach, transitively.
The result contains the input roles themselves, then each role reached through the hierarchy, with no duplicates and safe against cycles.
SignatureHasher ¶
SignatureHasher(signature_properties: Sequence[str], secret: str | Sequence[str], clock: ClockInterface | None = None)
Creates and checks the signed hashes behind login links and remember-me cookies.
A hash covers who it is for (the user's identifier), until when it counts (the expiry), the user's signature properties (so a new password retires every hash issued before it), and any extra parameters the caller binds into it. The text it returns has two parts: an HMAC of all of that with a secret, followed by a digest of the covered fields — the part that does not depend on the secret, so a hash can be checked against the loaded user as well as against a bare identifier.
Parameters:
-
signature_properties(Sequence[str]) –Attribute names on the user; the hash stops verifying when any of them changes.
-
secret(str | Sequence[str]) –The secret, or several to rotate it: the first signs, all of them verify.
-
clock(ClockInterface | None, default:None) –The clock reading the current time; the system clock when
None.
Raises:
-
InvalidArgumentError–When
secretis empty, or a sequence with an empty secret in it.
Record the covered properties, the secrets, and the clock timing expiry.
compute_signature_hash ¶
compute_signature_hash(user: UserInterface, expires: int, parameters: Mapping[str, str | bool | int | float] = _NO_PARAMETERS) -> str
accept_signature_hash ¶
accept_signature_hash(user_identifier: str, expires: int, signature_hash: str, parameters: Mapping[str, str | bool | int | float] = _NO_PARAMETERS) -> None
Check the hash for a user identifier, before the user is loaded.
Only the HMAC is checked here — the covered fields cannot be, without the user — so this is the check for a flow that must not load the user before the hash proves the request sound.
Parameters:
-
user_identifier(str) –The identifier the hash was issued to.
-
expires(int) –The expiry it carries, as a Unix timestamp.
-
signature_hash(str) –The hash as presented.
-
parameters(Mapping[str, str | bool | int | float], default:_NO_PARAMETERS) –The extra values it was bound with.
Raises:
-
ExpiredSignatureError–When the hash is past its expiry.
-
InvalidSignatureError–When the hash matches neither the parameters nor any of the secrets.
verify_signature_hash ¶
verify_signature_hash(user: UserInterface, expires: int, signature_hash: str, parameters: Mapping[str, str | bool | int | float] = _NO_PARAMETERS) -> None
Check the hash against the loaded user, covered fields and all.
Parameters:
-
user(UserInterface) –The user the hash claims to be for.
-
expires(int) –The expiry it carries, as a Unix timestamp.
-
signature_hash(str) –The hash as presented.
-
parameters(Mapping[str, str | bool | int | float], default:_NO_PARAMETERS) –The extra values it was bound with.
Raises:
-
ExpiredSignatureError–When the hash is past its expiry.
-
InvalidSignatureError–When the hash matches neither the user's covered fields nor any of the secrets.
AttributesBasedUserProviderInterface ¶
Bases: UserProviderInterface, Protocol
Loads a user given an identifier and the attributes that came with it.
A bearer token carries more than a sub — claims a provider may want
while building the user. This is the ordinary provider contract
(:class:~xtr_security_core.user.user_provider_interface.UserProviderInterface)
with those attributes passed alongside the identifier; a provider that
ignores them behaves exactly like a plain one.
load_user_by_identifier
async
¶
load_user_by_identifier(identifier: str, attributes: Mapping[str, object] | None = None) -> UserInterface
Load the user named by identifier, given attributes.
Raises:
-
UserNotFoundError–When no user matches
identifier.
ChainUserChecker ¶
Bases: UserCheckerInterface
Runs each checker in order, so the first refusal stops the rest.
An application may gate a user on more than one condition — disabled, then locked out, then expired. Each checker runs in turn; the account-status error one raises propagates, and the checkers after it do not run.
Record the checkers to run, in order.
check_pre_auth
async
¶
Run every checker's pre-authentication check, in order.
Raises:
-
AccountStatusError–As soon as a checker refuses.
check_post_auth
async
¶
Run every checker's post-authentication check, in order.
Raises:
-
AccountStatusError–As soon as a checker refuses.
ChainUserProvider ¶
Bases: AttributesBasedUserProviderInterface, PasswordUpgraderInterface
Asks each provider in order, until one answers.
An application may load users from more than one place — a database and a fixed set of service accounts. This tries each provider for an identifier, catching the not-found of one and moving to the next, and reports not-found only when none answered. When attributes come with the identifier they are handed to every provider that reads them, and a password upgrade fans out to every provider that can perform one for the user's class.
Record the providers to try, in order.
load_user_by_identifier
async
¶
load_user_by_identifier(identifier: str, attributes: Mapping[str, object] | None = None) -> UserInterface
Load identifier from the first provider that has it.
A provider that reads attributes is given them; the rest are asked the plain way.
Raises:
-
UserNotFoundError–When no provider has the user.
supports_class ¶
Tell whether any chained provider loads user_class.
refresh_user
async
¶
Refresh user with the first provider supporting its class that has it.
A provider turning the user away, or no longer finding it, is skipped.
Raises:
-
UserNotFoundError–When a provider supported the user but none found it.
-
UnsupportedUserError–When no provider supports the user's class.
upgrade_password
async
¶
Upgrade user's stored password wherever a provider can.
A provider that cannot upgrade, or does not handle the user's class, is skipped; the rest are asked, so a user stored in more than one place is kept in step. A provider that turns the user away is skipped too.
get_providers ¶
Return the chained providers, in order.
EnabledAwareInterface ¶
Bases: Protocol
A user that answers whether its account is enabled.
A checker reads this to turn away a disabled account before its credentials are ever checked. A user without the method is left alone: the structural check simply does not match it, so no assumption is made either way.
EquatableInterface ¶
Bases: Protocol
A user that decides for itself whether another user is the same.
Object identity is not enough: a user loaded twice is two objects standing for one account. A user implementing this says when another is equal on the terms that matter to it — the identifier, and whatever else changing would make it a different account.
InMemoryUser
dataclass
¶
InMemoryUser(identifier: str, password: str | None = None, roles: Sequence[str] = (), enabled: bool = True)
Bases: SessionSerializableUserInterface, PasswordAuthenticatedUserInterface, EquatableInterface
A user defined by its own fields rather than loaded from a store.
Enough of a user for tests, small fixed sets of accounts, and the anonymous
edges of a system. It carries a password so it can stand in for a stored
user where one is verified, and an enabled flag a checker reads.
Implements the password-carrying user contract: its
:meth:get_password is what a hasher verifies against.
A session keeps it whole — its identifier, roles and enabled flag —
with the digest of its password in place of the password, and rebuilds it
as an in-memory user carrying that digest, which :meth:is_equal_to
recognises as the password it stands for.
get_password ¶
Return the hashed password, or None when the user has none.
to_session ¶
Return the fields a session keeps, the password as its digest.
The hash itself never reaches the session store: the digest says whether the password changed, and nothing a stolen store could crack.
from_session
classmethod
¶
Rebuild the user a session kept, the digest standing as its password.
Raises:
-
InvalidArgumentError–When a field of
stateis missing or of the wrong type.
is_equal_to ¶
Tell whether user is the same in-memory user, field for field.
The password carries the carve-out a session needs: a password of
exactly eight characters that is the digest of user's is the same
password — the spelling this user is rebuilt with from a session, so a
reload of the account it stands for compares equal while the password
has not changed.
InMemoryUserChecker ¶
Bases: UserCheckerInterface
Refuses a user whose account reports itself disabled.
Pairs with :class:~xtr_security_core.user.in_memory_user.InMemoryUser: a user
that carries an is_enabled answering False is turned away before its
credentials are ever checked. A user without that method is left alone —
this checker has nothing to say about it.
check_pre_auth
async
¶
Refuse user when its account reports itself disabled.
Raises:
-
DisabledError–When the account is disabled.
check_post_auth
async
¶
Do nothing after authentication: this checker gates only the account state.
InMemoryUserProvider ¶
Bases: UserProviderInterface
Loads users from a set defined up front, not from a store.
Built either from ready :class:InMemoryUser objects or from a mapping of
identifier to the fields one is made of — {"alice": {"password": ...,
"roles": (...), "enabled": True}} — so a small fixed set of accounts is
a few lines of configuration.
Build the provider from ready users or from their fields.
add_user ¶
Add user to the set, replacing any user with its identifier.
load_user_by_identifier
async
¶
refresh_user
async
¶
Reload user from the set, as a fresh copy of the stored one.
Raises:
-
UnsupportedUserError–When
useris not an in-memory user. -
UserNotFoundError–When the set no longer holds the user.
supports_class ¶
Tell whether user_class is the in-memory user.
MissingUserProvider ¶
Bases: UserProviderInterface
Stands where a firewall's user provider should be, when none was defined.
Building it raises an error naming the firewall, so a firewall whose authentication needs a provider fails — with a message saying why — the first time that provider is asked for, while a firewall that never needs one is unaffected. No instance ever exists, so its methods are never run.
Refuse to build, naming the firewall missing a provider.
Raises:
-
InvalidArgumentError–Always.
OAuth2User ¶
OAuth2User(roles: Sequence[str] = ('ROLE_USER',), scope: str | None = None, client_id: str | None = None, username: str | None = None, token_type: str | None = None, exp: int | None = None, iat: int | None = None, nbf: int | None = None, sub: str | None = None, aud: str | Sequence[str] | None = None, iss: str | None = None, jti: str | None = None, **additional_claims: object)
Bases: UserInterface
The user the access-token workflow settles on with an OAuth2 server.
It carries the standard claims of a token introspection response
(https://datatracker.ietf.org/doc/html/rfc7662#section-2.2) as read-only
attributes and keeps every other member as an additional claim. A sub
or a username is required; the user is identified by the sub when
there is one, by the username otherwise.
Neither OIDC nor OAuth has a notion of role: the user holds ROLE_USER
unless built with other roles — by a provider mapping claims onto roles,
say.
Attributes:
-
scope(Final) –The scopes the token grants, space-separated.
-
client_id(Final) –The client the token was issued to.
-
username(Final) –The resource owner who authorized the token.
-
token_type(Final) –The type of the token.
-
exp(Final) –When the token expires, as a Unix timestamp.
-
iat(Final) –When the token was issued, as a Unix timestamp.
-
nbf(Final) –When the token starts being valid, as a Unix timestamp.
-
sub(Final) –The subject of the token.
-
aud(Final) –The audience — one service-specific identifier, or several.
-
iss(Final) –The issuer of the token.
-
jti(Final) –The identifier of the token.
-
additional_claims(Final[Mapping[str, object]]) –Every other member of the response.
Record the standard claims, and keep every other member as an additional claim.
An additional_claims keyword, when given, is taken as the
additional claims themselves rather than as one of them.
Raises:
-
InvalidArgumentError–When neither a
subnor ausernameis given.
OidcUser ¶
OidcUser(user_identifier: str | None = None, roles: Sequence[str] = ('ROLE_USER',), sub: str | None = None, name: str | None = None, given_name: str | None = None, family_name: str | None = None, middle_name: str | None = None, nickname: str | None = None, preferred_username: str | None = None, profile: str | None = None, picture: str | None = None, website: str | None = None, email: str | None = None, email_verified: bool | None = None, gender: str | None = None, birthdate: str | None = None, zoneinfo: str | None = None, locale: str | None = None, phone_number: str | None = None, phone_number_verified: bool | None = None, address: Mapping[str, object] | None = None, updated_at: datetime | None = None, **additional_claims: object)
Bases: SessionSerializableUserInterface
The user the security workflows with an OpenID Connect server settle on.
It carries the standard claims
(https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims) as
typed fields and keeps every other claim as an additional claim. The sub
claim is required; the user is identified by user_identifier when given,
by sub otherwise.
Neither OIDC nor OAuth has a notion of role: the user holds ROLE_USER
unless built with other roles — by a provider mapping claims onto roles,
say.
A session keeps it whole — every claim and the roles — and rebuilds it as the user it was, since its provider has nothing to reload it from.
Record the standard claims, and keep every other one as an additional claim.
An additional_claims keyword, when given, is taken as the
additional claims themselves rather than as one of them.
Raises:
-
InvalidArgumentError–When the
subclaim is missing or empty.
from_claims
classmethod
¶
Build a user from the claims returned by an OIDC provider.
Claim names are snake-cased onto the constructor arguments, and the
ones matching no argument become additional claims. Every claim is
mapped this way, so a roles claim does grant the roles it holds:
only pass claims you decided to trust, either because you verified
where they come from or because you mapped them yourself. Claims whose
value does not fit the type of their argument are dropped, so that a
misbehaving provider cannot break authentication with a type error.
Raises:
-
InvalidArgumentError–When the
subclaim is missing or empty.
to_session ¶
Return every claim and the roles, each read back through its getter.
updated_at is kept as its ISO 8601 spelling, the one form of a
moment JSON carries without losing its offset.
from_session
classmethod
¶
Rebuild the user a session kept, through the constructor, every claim checked.
Raises:
-
InvalidArgumentError–When a field of
stateis missing or of the wrong type,updated_atspells no moment, or thesubis empty.
get_roles ¶
Return the roles granted to this user; ROLE_USER unless built otherwise.
get_user_identifier ¶
Return user_identifier when given, the sub claim otherwise.
get_preferred_username ¶
Return the preferred_username claim.
get_phone_number_verified ¶
Return the phone_number_verified claim.
get_additional_claims ¶
Return every claim that is not a standard one, read-only.
OidcUserProvider ¶
Bases: AttributesBasedUserProviderInterface
Provides the OIDC users built from the claims returned by an OIDC provider.
OIDC users are self-contained: the user is built from the claims collected during authentication, and returned as-is when refreshed, without any external lookup.
The claims cannot define the security identity nor grant roles: the
identifier is the one authentication validated, and the roles default to
ROLE_USER. Use a provider of your own to map claims onto roles, or to
load the users from your own store.
This provider cannot serve a feature that loads a user by its identifier alone — impersonation, say — as it needs the claims collected during authentication.
load_user_by_identifier
async
¶
load_user_by_identifier(identifier: str, attributes: Mapping[str, object] | None = None) -> OidcUser
Build the user identifier names from the claims in attributes.
Raises:
-
UserNotFoundError–When the claims carry no usable
sub.
refresh_user
async
¶
Return user as-is: an OIDC user has nothing to reload.
Raises:
-
UnsupportedUserError–When
useris not an OIDC user.
PasswordUpgraderInterface ¶
Bases: Protocol
Persists a freshly rehashed password for a user.
A user store implements this so a password verified against an outdated hash is quietly re-stored under the current algorithm — an opportunistic upgrade that happens on a successful login and nowhere else.
The upgrade is best-effort: it runs after the user is already authenticated, so it must not raise. A store that cannot write the new hash swallows the failure — the login still succeeds; the hash is upgraded on the next login instead.
upgrade_password
async
¶
Store new_hashed_password for user; never raise on failure.
SessionSerializableUserInterface ¶
Bases: UserInterface, Protocol
A user that turns itself into JSON for a session, and back.
A stateful firewall keeps the user a token carries in the session between
requests, and a session holds JSON only. A user implementing this is kept
as the state :meth:to_session answers and rebuilt as its own class by
:meth:from_session, so the firewall's provider is handed it through
refresh_user. Any other user is kept as a snapshot — its identifier, its
roles and a digest of its password — and reloaded by its identifier
instead.
Inherit it explicitly: the class a session names is found again among the classes already loaded, by their inheritance, so a user that merely has the two methods is not one a session rebuilds — it is kept as a snapshot.
The state must hold nothing a session store should not: never a password
hash — keep :func:~xtr_security_core.user.password_digest.password_digest
of it instead, which tells a changed password from the same one and
verifies nothing. And the rebuilt user is a snapshot of what the session
held, not the stored record: a provider reloads it, and never persists it
or merges it into what it stores as it is.
to_session ¶
Return the state this user is kept in a session as.
Every value must come back from JSON exactly as it went in — strings,
numbers, booleans, None, lists and objects keyed by strings, never
a tuple — or the token carrying the user is refused when the session
is written.
from_session
classmethod
¶
Rebuild the user a session kept as state.
Pure: no I/O, and nothing but state is read. Every field's type is
checked, because the state comes back from a store outside the
process.
Raises:
-
InvalidArgumentError–When
stateis malformed — a field missing or of the wrong type; the session then reads as holding no token.
UserCheckerInterface ¶
Bases: Protocol
Gates a user's own state around authentication.
Credentials being right is not the whole of authentication: the account may
be disabled, locked or expired. A checker runs before credentials are
checked and again after, raising an
:class:~xtr_security_core.exception.AccountStatusError when the account itself
forbids proceeding.
check_pre_auth
async
¶
Check user's state before its credentials are verified.
Raises:
-
AccountStatusError–When the account may not authenticate.
check_post_auth
async
¶
Check user's state after authentication settled on token.
Raises:
-
AccountStatusError–When the account may not proceed.
UserInterface ¶
Bases: Protocol
The user a token carries: an identity and the roles it was granted.
A user is not a set of credentials. It is what authentication resolves to — an identifier that names it and the roles it holds — and what authorization reasons about. How it is stored, and whether it carries a password, is the concern of the provider that loads it, not of this contract.
get_roles ¶
Return the roles granted to this user.
Roles are opaque strings. Their meaning is decided by the voters that read them and by any role hierarchy configured over them.
get_user_identifier ¶
Return the non-empty string that names this user.
The value a provider loads a user by, and the sub a self-issued
token carries — a username, an email, a client id.
UserProviderInterface ¶
Bases: Protocol
Loads a user given the identifier authentication established.
Authentication proves who is calling — a username, a token's sub — and
then asks a provider to turn that identifier into a user object the rest of
the library reasons about. A provider works with one class of user;
:meth:supports_class says which, and :meth:refresh_user reloads a user
of that class held from an earlier unit of work.
A stateful firewall reloads the user its session kept on every request,
and what a provider is handed for it depends on what the session could
keep. A user implementing
:class:~xtr_security_core.user.session_serializable_user_interface.SessionSerializableUserInterface
is rebuilt as its own class and handed to :meth:refresh_user. Any other
user was kept as a snapshot — its identifier, its roles and a digest of
its password — and is reloaded through :meth:load_user_by_identifier
instead: the snapshot never reaches :meth:refresh_user. Either way the
user a session rebuilt is a snapshot of what the session held, not the
stored record, so it is reloaded — never persisted, and never merged into
what the provider stores as it is.
refresh_user
async
¶
Refresh user.
It is up to the implementation to decide whether the user data is reloaded entirely — from the database, say — or whether the user object can just be merged into an identity map it keeps. A user a session rebuilt is the exception: it carries what the session kept — a password digest where the hash was — so it is reloaded, never merged or persisted as it is.
Raises:
-
UnsupportedUserError–When the user is not of a class this provider supports.
-
UserNotFoundError–When the user is not found.
load_user_by_identifier
async
¶
supports_class ¶
Tell whether this provider loads users of user_class.