xtr_password_hasher ¶
Password hashing behind one interface.
argon2id by default, legacy hashes verified and upgraded.
MAX_PASSWORD_LENGTH
module-attribute
¶
The greatest input length, in UTF-8 bytes, any hasher processes.
A longer input is refused by :meth:PasswordHasherInterface.hash — an
unbounded input would let a caller spend a hasher's whole cost on one call —
and rejected by :meth:PasswordHasherInterface.verify as a non-match. The
bound is on the encoded byte length, since that is the work a hasher reads: a
multi-byte character costs its bytes. It is a denial-of-service guard, not a
rule on how long a password may be.
InvalidArgumentError ¶
Bases: PasswordHasherError, ValueError
A hasher or a config was configured with a value it cannot use.
Raised where the value is given — a bcrypt cost outside 4 to 31, a PBKDF2 iteration count below a safe floor, a hash algorithm the platform does not provide, an algorithm no hasher implements, rather than on the first hash.
Also a :class:ValueError, so code that already guards its configuration
with except ValueError keeps working without learning a new exception.
Attributes:
-
reason(str) –What is wrong with the argument.
Record what is wrong with the argument.
InvalidPasswordError ¶
Bases: PasswordHasherError, ValueError
A plaintext password exceeded the length a hasher accepts.
Raised by :meth:hash when the input is longer than
MAX_PASSWORD_LENGTH. Refusing an unbounded input keeps a hasher from
spending unbounded work on it — a denial-of-service guard, not a policy on
how long a password may be. Verifying an over-long input never raises: it
simply cannot match a hash made from a bounded one, so :meth:verify
returns False.
Also a :class:ValueError, so code that already guards its input with
except ValueError keeps working without learning a new exception.
Attributes:
-
length(int) –The UTF-8 byte length of the input that was refused.
-
max_length(int) –The greatest UTF-8 byte length a hasher accepts.
Record the refused UTF-8 byte length and the limit it crossed.
PasswordHasherError ¶
Bases: Exception
Base class for every error raised by this library.
Catch this to handle anything hashing 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.
UnknownPasswordHasherError ¶
Bases: PasswordHasherError, LookupError
The factory holds no hasher for the user, class or name asked for.
Raised by
:meth:~xtr_password_hasher.PasswordHasherFactoryInterface.get_password_hasher
when nothing in its mapping matches — no entry for the class or any of its
bases, no entry for the name the user declares, and no entry for the string
key given. The message names what was looked up so the fix is to add that
key to the factory's mapping.
Also a :class:LookupError, so a caller may catch either this type or the
built-in.
Attributes:
-
looked_up(str) –What was searched for — a class's qualified name, or the string key given.
Record what had no hasher, and how to fix it.
MigratingPasswordHasher ¶
Bases: PasswordHasherInterface
Hashes with one preferred hasher, verifies with it and older ones behind it.
A deployment holding hashes from several eras keeps this in front: new
passwords are hashed with best, and a stored hash best does not
recognise is offered to each of extras in turn. A hash best already
owns never reaches the extras, so the common path pays for one verify.
A salt given to :meth:hash or :meth:verify is passed on to each hasher
that takes one — a
:class:~xtr_password_hasher.LegacyPasswordHasherInterface, or another
migrating hasher — and left out for the self-salting ones, so a legacy
salted hash verifies behind an argon2id front.
Paired with :meth:needs_rehash — which delegates to best — a login
verified against a legacy hash is the moment to rehash and upgrade it.
Never put a :class:~xtr_password_hasher.PlaintextPasswordHasher among the
extras: a leaked hash would then be a working password.
Hash with best; fall back to extras only for hashes it disowns.
Raises:
-
InvalidArgumentError–When an extra is a :class:
~xtr_password_hasher.PlaintextPasswordHasher; it "verifies" any string equal to the stored one, so behind a migrating hasher a leaked hash would be a working password.
hash ¶
Hash plain_password with the preferred hasher.
Raises:
-
InvalidPasswordError–When
plain_passwordis too long.
verify ¶
Return whether plain_password made hashed_password, best hasher first.
When best recognises hashed_password — it does not need
rehashing to the best format — only best verifies it. Otherwise each
extra is tried, then best once more as a last resort.
needs_rehash ¶
Return whether hashed_password should be replaced, as the best hasher sees it.
NativePasswordHasher ¶
NativePasswordHasher(algorithm: Algorithm = 'argon2id', *, time_cost: int = 3, memory_cost: int = 65536, parallelism: int = 4, cost: int = 12)
Bases: PasswordHasherInterface
Hashes with argon2id or bcrypt, and verifies either when its backend is installed.
Argon2id is the default: memory-hard, so a stolen hash is dear to attack on
commodity hardware. bcrypt is available for interoperability — it needs the
bcrypt extra — and, because bcrypt reads at most 72 bytes, a longer
input is folded to a fixed length first (the base64 of its SHA-512 digest,
truncated to what bcrypt reads) on both hashing and verifying, so a long
password stays stable across the two.
Whichever algorithm it hashes with, it verifies a hash of either as long as
that algorithm's backend is present, so hashes minted by another stack —
$argon2id$… or $2a$/$2b$/$2y$ — migrate in place.
:meth:needs_rehash asks for a fresh hash whenever a stored one is of the
other algorithm, or of weaker parameters.
Configure the active algorithm and every backend that is installed.
The active algorithm decides how :meth:hash writes; both backends
are prepared for verifying when their libraries are present, so a
migrating deployment reads legacy hashes of either.
Raises:
-
InvalidArgumentError–When
algorithmis neither"argon2id"nor"bcrypt", an argon2 cost is not positive, the bcrypt cost is outside 4 to 31, oralgorithm="bcrypt"is asked for without thebcryptextra installed.
hash ¶
Hash plain_password with the active algorithm.
Raises:
-
InvalidPasswordError–When
plain_passwordis too long.
verify ¶
Return whether plain_password made hashed_password, by the backend owning it.
needs_rehash ¶
Return whether hashed_password should be replaced by a fresh hash.
True when hashed_password belongs to the other algorithm, is
unrecognised, or was made with weaker parameters than the active
backend now uses.
PasswordHasherAwareInterface ¶
Bases: Protocol
A user that chooses its hasher by name rather than by its class.
The factory asks this first: a user that answers with a name is hashed by
the entry mapped to that name, whatever its class. A None answer means
"decide by my class instead", the usual case.
get_password_hasher_name ¶
Return the name of the hasher to use, or None to decide by class.
PasswordHasherFactory ¶
Bases: PasswordHasherFactoryInterface
Hands out a hasher per user, chosen from a mapping keyed by class or name.
A key is a user class, a "module:Class" string, or a name a user
declares through
:class:~xtr_password_hasher.PasswordHasherAwareInterface. Resolution, in
order:
- a user that declares a hasher name is looked up by that name;
- otherwise the user's class — the class itself, or
type(user)— is walked up its__mro__, matching a class key or the matching"module:Class"string at each step; - a bare name or
"module:Class"string passed in is looked up as it is.
A mapping value is a ready hasher. Turning inert configuration into a live hasher — argon2 costs, migrating chains, a hasher a container provides — is the caller's job, so the factory carries no configuration vocabulary and hashes standalone from the same instances a bundle would build.
Resolve users against password_hashers, keyed by class or name.
get_password_hasher ¶
PasswordHasherFactoryInterface ¶
Bases: Protocol
Resolves which hasher a user, a class or a name is hashed by.
One application may hash different users differently — a slow argon2 for people, a cheap one for machine accounts — so the hasher is chosen per user, not fixed once.
get_password_hasher ¶
get_password_hasher(user: str | type | PasswordAuthenticatedUserInterface | PasswordHasherAwareInterface) -> PasswordHasherInterface
Return the hasher for user.
Parameters:
-
user(str | type | PasswordAuthenticatedUserInterface | PasswordHasherAwareInterface) –A user, a user class, a
"module:Class"string, or the name of a configured hasher.
Raises:
-
UnknownPasswordHasherError–When nothing is configured for it.
Pbkdf2PasswordHasher ¶
Pbkdf2PasswordHasher(algorithm: str = 'sha512', encode_hash_as_base64: bool = True, iterations: int = 1000, length: int = 40)
Bases: LegacyPasswordHasherInterface
Derives a key with PBKDF2-HMAC and stores only the encoded key.
For verification of legacy hashes only: new passwords belong on a
memory-hard hasher. The hash is the derived key alone — base64, or hex — so
the salt lives beside it and the algorithm, the work factor and the key
length live in this hasher's configuration. That is the shape of hashes
many older applications stored; this hasher exists to verify them, and its
defaults are the ones those hashes were typically made with. A None
salt hashes with an empty one.
Since the hash carries no parameters, :meth:needs_rehash cannot tell a
weak hash from a strong one and always answers False; put this hasher
behind a self-salting one in a
:class:~xtr_password_hasher.MigratingPasswordHasher to upgrade what it
verifies.
Configure the digest, the encoding, the work factor and the derived-key length.
Parameters:
-
algorithm(str, default:'sha512') –The digest PBKDF2 runs HMAC over.
-
encode_hash_as_base64(bool, default:True) –Encode the derived key as base64; as hex when
False. -
iterations(int, default:1000) –How many times the digest is applied.
-
length(int, default:40) –The derived key's length, in bytes.
Raises:
-
InvalidArgumentError–When PBKDF2 cannot run
algorithmon this platform, or the iteration count or key length is not positive.
hash ¶
Derive a key from plain_password under salt and encode it.
Raises:
-
InvalidPasswordError–When
plain_passwordis too long.
verify ¶
Return whether plain_password under salt derives to hashed_password.
A hash of the wrong length, or one in a $-delimited format, is
rejected before any key is derived.
needs_rehash ¶
Return False: the hash carries no parameters to compare.
PlaintextPasswordHasher ¶
Bases: LegacyPasswordHasherInterface
Stores the password as it is; verifies by constant-time comparison.
For tests and fixtures, never production: the "hash" is the plaintext,
followed by {salt} when a salt is given. It exists so a test suite can
run without paying argon2's cost. Never put it among a migrating hasher's
extras: a leaked hash would then be a working password.
Compare passwords case-insensitively when ignore_password_case is set.
hash ¶
Return plain_password, merged with salt, after the shared length guard.
Raises:
-
InvalidPasswordError–When
plain_passwordis too long. -
InvalidArgumentError–When
saltholds{or}.
verify ¶
Return whether plain_password under salt equals hashed_password.
Raises:
-
InvalidArgumentError–When
saltholds{or}.
needs_rehash ¶
Return False: a plaintext store has nothing to upgrade to.
UserPasswordHasher ¶
Bases: UserPasswordHasherInterface
Hashes and checks a password for a user, using the hasher its factory chooses.
Every call resolves the user's hasher through the factory, so one
application can hash different users differently while callers only ever
hand over the user and the plaintext. A
:class:~xtr_password_hasher.LegacyPasswordAuthenticatedUserInterface
user's salt goes to the hasher with the password.
Resolve each user's hasher through factory.
hash_password ¶
Hash plain_password with the hasher chosen for user.
Raises:
-
InvalidPasswordError–When
plain_passwordis too long. -
UnknownPasswordHasherError–When no hasher is configured for the user.
is_password_valid ¶
Return whether plain_password matches user's stored password.
A user whose stored password is None returns False at once,
without hashing plain_password. The early return is observable in
time, so the timing guard is not this hasher's to keep: the caller
that must not reveal which accounts have a password owns it, and the
credentials listener is the caller that charges one — burning a
dummy verify for the passwordless user.
Raises:
-
UnknownPasswordHasherError–When no hasher is configured for the user.
needs_rehash ¶
Return whether user's stored password should be rehashed.
Raises:
-
UnknownPasswordHasherError–When no hasher is configured for the user.
UserPasswordHasherInterface ¶
Bases: Protocol
Hashes and verifies a password for a user, choosing the hasher by the user.
A thin seam over the factory: it picks the right hasher for the user's class or declared name, so callers hand it the user and the plaintext and never touch a hasher directly.
hash_password ¶
Hash plain_password with the hasher chosen for user.
Raises:
-
InvalidPasswordError–When
plain_passwordis too long. -
UnknownPasswordHasherError–When no hasher is configured for the user.
is_password_valid ¶
Return whether plain_password matches user's stored password.
False when the user carries no password, so there is nothing to
match against.
Raises:
-
UnknownPasswordHasherError–When no hasher is configured for the user.
needs_rehash ¶
Return whether user's stored password should be rehashed.
False when the user carries no password.
Raises:
-
UnknownPasswordHasherError–When no hasher is configured for the user.
LegacyPasswordAuthenticatedUserInterface ¶
Bases: PasswordAuthenticatedUserInterface, Protocol
A user whose password was hashed under a salt it keeps separately.
The user password hasher hands the salt to a
:class:~xtr_password_hasher.LegacyPasswordHasherInterface. Once every
stored hash has been upgraded to a self-salting algorithm, implement
:class:~xtr_password_hasher.PasswordAuthenticatedUserInterface instead.
get_salt ¶
Return the salt the password was originally hashed with, or None.
LegacyPasswordHasherInterface ¶
Bases: PasswordHasherInterface, Protocol
A hasher that takes its salt from the caller rather than minting one.
Older schemes store the salt in a column of its own and the bare digest in
another; the hash alone cannot be verified. Such a hasher is kept to read
those hashes and upgrade them — new passwords belong to a self-salting
hasher. A None salt means no salt at all.
Every method name matches :class:PasswordHasherInterface, so an
isinstance check cannot tell the two apart; ask
:func:is_legacy_password_hasher instead.
hash ¶
Hash plain_password under salt.
Raises:
-
InvalidPasswordError–When
plain_passwordis longer than :data:~xtr_password_hasher.MAX_PASSWORD_LENGTH.
verify ¶
Return whether plain_password under salt made hashed_password.
PasswordAuthenticatedUserInterface ¶
Bases: Protocol
A user whose identity can be proven by a password.
The hasher factory keys on this: a user that carries a password is hashed
and verified by whichever hasher its class is mapped to. The password is
the stored hash, not the plaintext — None when the user has no password
and so cannot authenticate by one.
get_password ¶
Return the stored password hash, or None when there is none.
PasswordHasherInterface ¶
Bases: Protocol
Turns a plaintext password into a hash, and checks one against it.
A hash is opaque: it names its own algorithm, parameters and salt, so the
same hasher — or one built from a later, stronger configuration — reads
them back to verify and to decide whether the hash should be replaced. A
hasher whose salt is stored beside the hash instead is a
:class:~xtr_password_hasher.LegacyPasswordHasherInterface.
hash ¶
Hash plain_password and return the hash to store.
Parameters:
-
plain_password(str) –The plaintext password.
Raises:
-
InvalidPasswordError–When
plain_passwordis longer than :data:MAX_PASSWORD_LENGTH.
verify ¶
Return whether plain_password is the password hashed_password was made from.
Never raises for an over-long plain_password: it cannot match a hash
of a bounded input, so the answer is False. The comparison is
constant-time.
needs_rehash ¶
Return whether hashed_password should be replaced by a fresh hash.
True when hashed_password was made by a weaker algorithm or with weaker
parameters than this hasher now uses — the moment to rehash the
plaintext, which is only in hand right after a successful verify.
bcrypt_available ¶
Return whether the bcrypt backend can actually be loaded.
pwdlib ships the pwdlib.hashers.bcrypt module whether or not the
bcrypt library behind it is installed, so merely finding the module
answers True for a missing backend. An import probe — importing it, the
way the native hasher builds its backend — is the reliable check: it raises
when bcrypt is absent.
create_auto_password_hasher ¶
Build argon2id with bcrypt (when installed) and PBKDF2 verifying behind it.
is_legacy_password_hasher ¶
is_legacy_password_hasher(hasher: PasswordHasherInterface) -> TypeGuard[LegacyPasswordHasherInterface]
Return whether hasher declares :class:LegacyPasswordHasherInterface.
The check is by inheritance, not by shape: a structural match would accept
every hasher, since the two interfaces share their method names and differ
only in the salt parameter.