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,148 @@
|
||||
"""Argon2id password hashing and TOTP (REVIEW SEC-009, TODO 3.0).
|
||||
|
||||
No database needed: these are pure functions.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from poorbird.passwords import (
|
||||
MIN_PASSWORD_LENGTH,
|
||||
WeakPassword,
|
||||
hash_password,
|
||||
needs_rehash,
|
||||
validate_password_strength,
|
||||
verify_password,
|
||||
)
|
||||
from poorbird.totp import DIGITS, new_secret, provisioning_uri, verify
|
||||
|
||||
GOOD = "a-perfectly-fine-passphrase"
|
||||
|
||||
|
||||
# --- hashing ----------------------------------------------------------------
|
||||
|
||||
|
||||
def test_a_password_verifies_against_its_own_hash():
|
||||
assert verify_password(GOOD, hash_password(GOOD)) is True
|
||||
|
||||
|
||||
def test_a_wrong_password_does_not_verify():
|
||||
assert verify_password("something else entirely", hash_password(GOOD)) is False
|
||||
|
||||
|
||||
def test_the_hash_is_argon2id_and_not_something_faster():
|
||||
"""SPEC 3.1 says Argon2id specifically.
|
||||
|
||||
A SHA-256 here would pass every other test in this file while leaving the
|
||||
passwords brute-forceable, so the algorithm is asserted directly.
|
||||
"""
|
||||
assert hash_password(GOOD).startswith("$argon2id$")
|
||||
|
||||
|
||||
def test_the_same_password_hashes_differently_every_time():
|
||||
"""Per-hash salt. Equal hashes would mean equal passwords are visible."""
|
||||
assert hash_password(GOOD) != hash_password(GOOD)
|
||||
|
||||
|
||||
def test_the_plaintext_never_appears_in_the_hash():
|
||||
assert GOOD not in hash_password(GOOD)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stored", [None, "", "not-a-hash", "$argon2id$truncated"])
|
||||
def test_an_unusable_stored_hash_is_a_no_not_a_crash(stored):
|
||||
"""A user row that has never had a password set must not be loggable-in.
|
||||
|
||||
It must also not take the login route down: NULL is the Phase 1 state of
|
||||
every seeded row, and a 500 on the login endpoint is worse than a 401.
|
||||
"""
|
||||
assert verify_password(GOOD, stored) is False
|
||||
|
||||
|
||||
def test_a_current_hash_does_not_need_rehashing():
|
||||
assert needs_rehash(hash_password(GOOD)) is False
|
||||
|
||||
|
||||
def test_a_weaker_hash_is_flagged_for_rehash():
|
||||
"""Login is the only moment the plaintext exists, so it is the only moment
|
||||
a hash can be upgraded. This is what makes raising the cost possible."""
|
||||
from argon2 import PasswordHasher
|
||||
|
||||
weak = PasswordHasher(time_cost=1, memory_cost=8, parallelism=1).hash(GOOD)
|
||||
assert needs_rehash(weak) is True
|
||||
# ...and it must still verify, or raising the cost would lock everyone out.
|
||||
assert verify_password(GOOD, weak) is True
|
||||
|
||||
|
||||
# --- strength floor ---------------------------------------------------------
|
||||
|
||||
|
||||
def test_a_long_enough_password_is_accepted():
|
||||
validate_password_strength("x" * MIN_PASSWORD_LENGTH)
|
||||
|
||||
|
||||
def test_a_short_password_is_rejected():
|
||||
with pytest.raises(WeakPassword, match="at least"):
|
||||
validate_password_strength("x" * (MIN_PASSWORD_LENGTH - 1))
|
||||
|
||||
|
||||
def test_whitespace_is_not_a_password():
|
||||
with pytest.raises(WeakPassword, match="whitespace"):
|
||||
validate_password_strength(" " * (MIN_PASSWORD_LENGTH + 4))
|
||||
|
||||
|
||||
def test_an_absurdly_long_password_is_rejected_rather_than_hashed():
|
||||
"""Argon2 is deliberately expensive; an unbounded body should not become a
|
||||
way to spend the server's CPU."""
|
||||
with pytest.raises(WeakPassword, match="at most"):
|
||||
validate_password_strength("x" * 5000)
|
||||
|
||||
|
||||
# --- totp -------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_a_generated_code_verifies():
|
||||
import pyotp
|
||||
|
||||
secret = new_secret()
|
||||
assert verify(secret, pyotp.TOTP(secret).now()) is True
|
||||
|
||||
|
||||
def test_a_code_for_a_different_secret_does_not_verify():
|
||||
import pyotp
|
||||
|
||||
assert verify(new_secret(), pyotp.TOTP(new_secret()).now()) is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("code", [None, "", "abcdef", "12345", "1234567", "12 34 56 78"])
|
||||
def test_a_malformed_code_is_rejected_without_raising(code):
|
||||
assert verify(new_secret(), code) is False
|
||||
|
||||
|
||||
def test_a_user_without_a_secret_can_never_pass_totp():
|
||||
"""The check has to fail closed. If a missing secret verified, enabling 2FA
|
||||
for one user would effectively disable it for everyone else."""
|
||||
import pyotp
|
||||
|
||||
assert verify(None, pyotp.TOTP(new_secret()).now()) is False
|
||||
|
||||
|
||||
def test_spaces_in_a_code_are_tolerated():
|
||||
"""Authenticator apps display "123 456"; people paste what they see."""
|
||||
import pyotp
|
||||
|
||||
secret = new_secret()
|
||||
code = pyotp.TOTP(secret).now()
|
||||
assert verify(secret, f"{code[:3]} {code[3:]}") is True
|
||||
|
||||
|
||||
def test_the_provisioning_uri_carries_the_issuer_and_account():
|
||||
uri = provisioning_uri(new_secret(), "alice")
|
||||
assert uri.startswith("otpauth://totp/")
|
||||
assert "issuer=poorBird" in uri
|
||||
assert "alice" in uri
|
||||
|
||||
|
||||
def test_codes_are_six_digits():
|
||||
"""Changing this silently would break every already-enrolled authenticator."""
|
||||
assert DIGITS == 6
|
||||
Reference in new issue
Block a user