diff --git a/server/pyproject.toml b/server/pyproject.toml index 64685f2..bbf6419 100644 --- a/server/pyproject.toml +++ b/server/pyproject.toml @@ -15,6 +15,13 @@ dependencies = [ # Thumbnails only, and only in the worker. The ingest path deliberately # does not decode images -- see poorbird/images.py. "pillow>=11.0", + # Argon2id for user passwords (SPEC 3.1). Device tokens stay on SHA-256 and + # deliberately so -- see api/deps.py.hash_credential for why the two differ. + "argon2-cffi>=23.1", + # TOTP. Hand-rolling RFC 6238 is 30 lines, and the two that matter -- the + # constant-time compare and the clock-skew window -- are the two easiest to + # get quietly wrong. + "pyotp>=2.9", ] [project.optional-dependencies] diff --git a/server/src/poorbird/cli.py b/server/src/poorbird/cli.py index 2b3b9b0..4c7dea2 100644 --- a/server/src/poorbird/cli.py +++ b/server/src/poorbird/cli.py @@ -73,6 +73,147 @@ def cmd_enqueue(args: argparse.Namespace) -> int: return 0 +# --- users ------------------------------------------------------------------ +# +# Accounts are created here, not over HTTP. There is no public registration and +# no "first run" web form: both are bootstrap paths that stay reachable forever +# and have to be defended forever. A CLI command needs shell access on the +# server, which is already the trust boundary. + + +def _read_new_password(from_stdin: bool) -> str: + """Prompt twice, or read one line from stdin. + + Never a command-line argument: that lands in shell history, in the process + table, and in any log that records commands. + """ + import getpass + + from .passwords import WeakPassword, validate_password_strength + + if from_stdin: + # Two line-ending hazards, both silent, both only discoverable by + # failing to log in with a password you know is right: + # + # rstrip("\r\n") rather than rstrip("\n"), or a CRLF pipe leaves the + # carriage return inside the password. + # + # lstrip("") because Windows PowerShell prepends a UTF-8 BOM + # when it pipes to a native executable. A BOM is never part of an + # intended password, and this cost a debugging session to find. + password = sys.stdin.readline().rstrip("\r\n").lstrip("") + else: + password = getpass.getpass("password: ") + if password != getpass.getpass("repeat: "): + raise SystemExit("passwords did not match") + + try: + validate_password_strength(password) + except WeakPassword as exc: + raise SystemExit(f"{exc}") from exc + return password + + +def cmd_user_add(args: argparse.Namespace) -> int: + from sqlalchemy import select + + from .db import SessionLocal + from .models import User + from .passwords import hash_password + from .totp import new_secret, provisioning_uri + + password = _read_new_password(args.password_stdin) + + # TODO 3.0: 2FA is enforced for admin. Enforcing that at login instead + # would mean the only admin could be locked out by their own account -- so + # it is enforced at creation, where the secret can still be handed over. + with_totp = args.totp + if with_totp is None: + with_totp = args.role == "admin" + if args.role == "admin" and not with_totp: + print("warning: creating an admin without TOTP, against the TODO 3.0 policy") + + with SessionLocal() as session: + if session.scalar(select(User).where(User.username == args.username)) is not None: + raise SystemExit(f"user {args.username!r} already exists") + + secret = new_secret() if with_totp else None + session.add( + User( + username=args.username, + email=args.email, + password_hash=hash_password(password), + role=args.role, + totp_secret=secret, + ) + ) + session.commit() + + print(f"created {args.role} {args.username!r}") + if secret is not None: + # Shown exactly once. It is stored so the server can verify codes, but + # printing it again later would turn a one-time handover into a + # standing way to mint a second authenticator. + print("\nScan this in an authenticator app now -- it is not shown again:") + print(f" {provisioning_uri(secret, args.username)}") + print(f"\n (manual entry key: {secret})") + return 0 + + +def cmd_user_list(_args: argparse.Namespace) -> int: + from sqlalchemy import select + + from .db import SessionLocal + from .models import User + + with SessionLocal() as session: + users = session.scalars(select(User).order_by(User.id)).all() + + if not users: + print("no users. Create one with: poorbird user add --role admin") + return 0 + + print(f"{'id':>4} {'username':<20} {'role':<8} {'2fa':<4} {'active':<7} last login") + for u in users: + last = u.last_login_at.strftime("%Y-%m-%d %H:%M") if u.last_login_at else "never" + print( + f"{u.id:>4} {u.username:<20} {u.role:<8} " + f"{'yes' if u.totp_secret else 'no':<4} " + f"{'yes' if u.is_active else 'NO':<7} {last}" + ) + return 0 + + +def cmd_user_passwd(args: argparse.Namespace) -> int: + from sqlalchemy import select + + from .db import SessionLocal + from .models import Session as UserSession + from .models import User + from .passwords import hash_password + + password = _read_new_password(args.password_stdin) + + with SessionLocal() as session: + user = session.scalar(select(User).where(User.username == args.username)) + if user is None: + raise SystemExit(f"no such user: {args.username!r}") + user.password_hash = hash_password(password) + + # A password change has to end existing sessions, or the old + # credential effectively still works through any browser that is + # already signed in -- which is the main reason people change it. + killed = ( + session.query(UserSession) + .filter(UserSession.user_id == user.id) + .delete(synchronize_session=False) + ) + session.commit() + + print(f"password updated for {args.username!r}; {killed} session(s) signed out") + return 0 + + def cmd_check(_args: argparse.Namespace) -> int: settings = get_settings() problems: list[str] = [] @@ -158,6 +299,34 @@ def main(argv: list[str] | None = None) -> int: p.add_argument("payload", nargs="?", help="JSON object") p.set_defaults(func=cmd_enqueue) + p = sub.add_parser("user", help="manage UI accounts (there is no web signup)") + usersub = p.add_subparsers(dest="user_command", required=True) + + q = usersub.add_parser("add", help="create an account") + q.add_argument("username") + q.add_argument("--role", choices=["admin", "editor", "viewer"], default="viewer") + q.add_argument("--email") + q.add_argument( + "--totp", + dest="totp", + action="store_true", + default=None, + help="enable TOTP (the default for --role admin)", + ) + q.add_argument("--no-totp", dest="totp", action="store_false", help="disable TOTP") + q.add_argument( + "--password-stdin", action="store_true", help="read the password from stdin, not a prompt" + ) + q.set_defaults(func=cmd_user_add) + + q = usersub.add_parser("list", help="list accounts") + q.set_defaults(func=cmd_user_list) + + q = usersub.add_parser("passwd", help="set a password and sign out that user's sessions") + q.add_argument("username") + q.add_argument("--password-stdin", action="store_true") + q.set_defaults(func=cmd_user_passwd) + args = parser.parse_args(argv) settings = get_settings() configure_logging(settings.log_level, settings.log_format) diff --git a/server/src/poorbird/passwords.py b/server/src/poorbird/passwords.py new file mode 100644 index 0000000..52190f9 --- /dev/null +++ b/server/src/poorbird/passwords.py @@ -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 diff --git a/server/src/poorbird/totp.py b/server/src/poorbird/totp.py new file mode 100644 index 0000000..c5ad0d0 --- /dev/null +++ b/server/src/poorbird/totp.py @@ -0,0 +1,65 @@ +"""TOTP second factor (TODO 3.0, SPEC Q14). + +Built now rather than later, on purpose. Retrofitting 2FA means reopening the +login flow, the session model, the user model and the audit log at once, and +``users.totp_secret`` was in the schema from Phase 1 for exactly this. + +Policy, from TODO 3.0: **enforced for ``admin``, opt-in for everyone else.** +Over Tailscale the network layer already demands an enrolled device, so UI 2FA +is belt-and-braces; the day this is served from a public domain it stops being +optional. A ``require_2fa`` server setting flips the whole thing. +""" + +from __future__ import annotations + +import pyotp + +# RFC 6238 defaults, which is also what every authenticator app assumes. +DIGITS = 6 +PERIOD_S = 30 + +# Accept the adjacent 30-second steps as well as the current one, so a phone +# clock a few seconds out still works. One step either side is the usual +# compromise: three windows is 90 seconds of exposure rather than 30, and +# anything wider starts to matter. +VALID_WINDOW = 1 + +ISSUER = "poorBird" + + +def new_secret() -> str: + """A fresh base32 secret for ``users.totp_secret``.""" + return pyotp.random_base32() + + +def provisioning_uri(secret: str, username: str) -> str: + """The ``otpauth://`` URI an authenticator app scans as a QR code.""" + return pyotp.TOTP(secret, digits=DIGITS, interval=PERIOD_S).provisioning_uri( + name=username, issuer_name=ISSUER + ) + + +def verify(secret: str | None, code: str | None) -> bool: + """True if ``code`` is currently valid for ``secret``. + + Returns False rather than raising for a missing secret, a missing code or a + malformed one. pyotp compares with ``hmac.compare_digest`` internally, so a + wrong code does not leak its position through timing. + + **Known limitation:** a code stays valid for its whole window, so it can be + replayed within ~90 seconds by someone who observed it. Preventing that + needs the last-accepted counter persisted per user, which is a column this + schema does not have yet. Worth adding if this is ever exposed publicly; + on a Tailscale-only LAN the observer has already had to get onto the + network. Not silently ignored -- just not paid for yet. + """ + if not secret or not code: + return False + + code = code.strip().replace(" ", "") + if not code.isdigit() or len(code) != DIGITS: + return False + + return pyotp.TOTP(secret, digits=DIGITS, interval=PERIOD_S).verify( + code, valid_window=VALID_WINDOW + ) diff --git a/server/tests/test_passwords.py b/server/tests/test_passwords.py new file mode 100644 index 0000000..c77afb7 --- /dev/null +++ b/server/tests/test_passwords.py @@ -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