Add Argon2id passwords, TOTP and account creation (REVIEW SEC-009)
The foundation the rest of Phase 3 auth stands on, and the part that has to be
right before anything can be logged into.
passwords.py and totp.py sit at the package root, not under api/, because the
CLI creates the first account before any HTTP request exists and a CLI importing
from api would be the wrong way round - the same reason images.py lives there.
Argon2id, with argon2-cffi's own defaults rather than numbers pinned here, so
the cost tracks the library's guidance instead of this commit's. Note the
deliberate contrast with api/deps.py: device tokens are 256 bits of CSPRNG
output and stay on SHA-256, because there is no dictionary to attack and a
per-request Argon2 would cost every heartbeat. A password is human-chosen from
a tiny space, so its hash has to be slow. Same word, opposite requirements, and
the docstrings on both sides now say so.
verify_password never raises. A NULL password_hash is the Phase 1 state of every
seeded row, and a corrupt one means something wrote that column by hand; both
have to mean "no" rather than a 500 on the login route. needs_rehash is there so
raising the cost later is possible at all - login is the only moment the
plaintext exists, so it is the only moment a hash can be upgraded.
2FA is enforced at *creation*, not at login. "Enforced for admin" implemented as
a login-time check means the only admin can be locked out by their own account,
so instead `user add --role admin` enables TOTP by default and prints the
provisioning URI once. --no-totp still works and says loudly that it is against
the TODO 3.0 policy.
TOTP uses pyotp rather than 30 hand-rolled lines, because the two parts that
matter - the constant-time compare and the clock-skew window - are the two
easiest to get quietly wrong. The replay window is documented rather than
pretended away: a code stays valid about 90 seconds, and closing that needs a
last-accepted-counter column this schema does not have.
Accounts are created by CLI, never over HTTP. Public registration and a
"first run" web form are both bootstrap paths that stay reachable forever and
have to be defended forever; shell access on the server is already the trust
boundary. `user passwd` also deletes that user's sessions, since otherwise the
old password keeps working through any browser already signed in, which is the
main reason people change it.
One real bug found while exercising it: reading the password with
rstrip("\n") left the carriage return from a CRLF pipe inside the password, and
Windows PowerShell additionally prepends a UTF-8 BOM when piping to a native
exe. Either one silently creates an account whose password nobody can type,
discoverable only by failing to log in. Both are stripped, with a comment
saying why, because the next person will pipe a password on Windows too.
Mutation-tested the two fail-closed guards: making a missing password hash
verify, and letting a user with no TOTP secret pass the check, each failed
exactly the tests written for them.
Tests: 194 -> 221.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
89ebe99bed
commit
9c44ab6b2a
5 files changed
+486
No files matched your search
@@ -0,0 +1,97 @@
|
||||
"""User password hashing (SPEC 3.1, REVIEW SEC-009).
|
||||
|
||||
Argon2id, via ``argon2-cffi``. Lives at the package root rather than under
|
||||
``api/`` because the CLI creates the first user before any HTTP request exists,
|
||||
and a CLI importing from ``api`` would be the wrong way round -- the same reason
|
||||
``images.py`` sits here.
|
||||
|
||||
**Why not the SHA-256 in api/deps.py.** That one hashes device tokens, which are
|
||||
256 bits of CSPRNG output: there is no dictionary to attack, and a per-request
|
||||
Argon2 would cost every heartbeat. A password is a human-chosen secret from a
|
||||
very small space, so the hash has to be deliberately slow. Same word, opposite
|
||||
requirements.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# argon2-cffi's defaults track the RFC 9106 guidance and move with the library,
|
||||
# which is the point of not pinning our own numbers here. At the time of writing
|
||||
# that is time_cost=3, memory_cost=64 MiB, parallelism=4 -- tens of milliseconds
|
||||
# on this hardware, which is the intended cost.
|
||||
_hasher = PasswordHasher()
|
||||
|
||||
# A floor, not a policy engine. Length is the only property that reliably
|
||||
# correlates with strength; composition rules mostly produce "Passw0rd!".
|
||||
MIN_PASSWORD_LENGTH = 12
|
||||
|
||||
# Argon2 reads at most this much, and a huge body should not become a CPU cost.
|
||||
# 1 KiB is far past any real passphrase.
|
||||
MAX_PASSWORD_LENGTH = 1024
|
||||
|
||||
|
||||
class WeakPassword(ValueError):
|
||||
"""Raised by :func:`validate_password_strength`."""
|
||||
|
||||
|
||||
def validate_password_strength(password: str) -> None:
|
||||
"""Raise :class:`WeakPassword` if the password is unusable.
|
||||
|
||||
Deliberately minimal: a length floor and a check that it is not entirely
|
||||
whitespace. Anything more opinionated belongs in the UI, where it can give
|
||||
feedback as the user types instead of rejecting after the fact.
|
||||
"""
|
||||
if len(password) < MIN_PASSWORD_LENGTH:
|
||||
raise WeakPassword(f"password must be at least {MIN_PASSWORD_LENGTH} characters")
|
||||
if len(password) > MAX_PASSWORD_LENGTH:
|
||||
raise WeakPassword(f"password must be at most {MAX_PASSWORD_LENGTH} characters")
|
||||
if not password.strip():
|
||||
raise WeakPassword("password must not be only whitespace")
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
"""Hash a password for storage in ``users.password_hash``.
|
||||
|
||||
The result carries its own parameters, so raising the cost later does not
|
||||
invalidate existing hashes -- see :func:`needs_rehash`.
|
||||
"""
|
||||
return _hasher.hash(password)
|
||||
|
||||
|
||||
def verify_password(password: str, stored_hash: str | None) -> bool:
|
||||
"""True if ``password`` matches ``stored_hash``.
|
||||
|
||||
Never raises for an ordinary wrong password, a NULL hash or a corrupt one:
|
||||
all three are simply "no". A user row with ``password_hash IS NULL`` is one
|
||||
that has never had a password set, and it must not be loggable-in rather
|
||||
than crashing the login route.
|
||||
"""
|
||||
if not stored_hash:
|
||||
return False
|
||||
try:
|
||||
return _hasher.verify(stored_hash, password)
|
||||
except (VerifyMismatchError, VerificationError):
|
||||
return False
|
||||
except InvalidHashError:
|
||||
# The stored value is not an Argon2 hash at all. Worth saying out loud,
|
||||
# because it means something wrote that column by hand.
|
||||
log.error("stored password hash is not a valid Argon2 hash")
|
||||
return False
|
||||
|
||||
|
||||
def needs_rehash(stored_hash: str) -> bool:
|
||||
"""True if this hash was made with weaker parameters than current defaults.
|
||||
|
||||
Login is the only moment the plaintext is available, so it is the only
|
||||
moment a hash can be upgraded. Call this after a successful verify.
|
||||
"""
|
||||
try:
|
||||
return _hasher.check_needs_rehash(stored_hash)
|
||||
except InvalidHashError:
|
||||
return False
|
||||
Reference in new issue
Block a user