"""The file underneath the door: what it holds, and what it refuses to hold. uv run pytest auth/tests/test_store.py -q """ from __future__ import annotations import sqlite3 from contextlib import closing from datetime import UTC, datetime, timedelta from pathlib import Path from auth import AuthStore from auth.store import _GRACE, _MAX_LOCK, _lockout from auth.tests import PASSWORD def rows(store: AuthStore, sql: str) -> list[tuple]: # `closing`, not `with conn:` alone -- that only commits, and a connection # left open is a file Windows will not let a temp dir delete. with closing(sqlite3.connect(store.path)) as conn: return [tuple(r) for r in conn.execute(sql)] # ------------------------------------------------------------- what is stored def test_the_password_is_not_in_the_file(store: AuthStore): """The point of the whole exercise.""" store.set_password(PASSWORD) assert PASSWORD.encode() not in store.path.read_bytes() assert store.check_password(PASSWORD) is True def test_a_session_token_is_not_in_the_file_either(store: AuthStore): token = store.open_session("pytest", 30) assert token.encode() not in store.path.read_bytes() assert store.touch(token) is not None def test_the_salt_differs_per_set(store: AuthStore): """Setting the same password twice must not produce the same row, or the file answers "did it change?" to anyone holding an old copy.""" store.set_password(PASSWORD) first = rows(store, "SELECT salt, hash FROM auth_credential") store.set_password(PASSWORD) assert rows(store, "SELECT salt, hash FROM auth_credential") != first assert store.check_password(PASSWORD) is True def test_the_tables_are_namespaced(store: AuthStore): """They share a file with the app's own tables and the job queue's, so a plain `sessions` is a name this package is not entitled to take.""" named = {name for (name,) in rows( store, "SELECT name FROM sqlite_master WHERE type='table'")} assert {"auth_credential", "auth_sessions", "auth_passkeys", "auth_challenges", "auth_tokens"} <= named assert not {n for n in named if not n.startswith(("auth_", "sqlite_"))} def test_a_database_with_no_password_refuses_without_raising(store: AuthStore): """And it still costs a derivation, so "is there a password here at all" is not a question the door answers by being quick about it.""" assert store.has_password() is False assert store.check_password(PASSWORD) is False # -------------------------------------------------------------- the lockout def test_five_wrong_answers_are_free_and_the_sixth_is_not(store: AuthStore): store.set_password(PASSWORD) for _ in range(_GRACE - 1): assert store.check_password("wrong") is False assert store.locked_for() == 0, "the grace ran out early" assert store.check_password("wrong") is False assert store.locked_for() > 0 def test_the_right_password_clears_it(store: AuthStore): """A lockout is a delay on guessing, not a second thing to recover from.""" store.set_password(PASSWORD) for _ in range(_GRACE): store.check_password("wrong") assert store.locked_for() > 0 assert store.check_password(PASSWORD) is True assert store.locked_for() == 0 def test_the_lockout_is_read_before_the_check_not_after(store: AuthStore): """The order the whole thing turns on: `locked_for` is a question about the file as it stands, so a caller can be told to wait *instead of* having a guess counted. Were it read after, every press while locked out would extend the lockout -- which punishes the owner hammering the button far harder than the attacker who is not watching. """ store.set_password(PASSWORD) for _ in range(_GRACE): store.check_password("wrong") waiting = store.locked_for() assert waiting > 0 # Asking twice does not move it. Nothing in `locked_for` writes. assert store.locked_for() == waiting assert rows(store, "SELECT failures FROM auth_credential") == [(_GRACE,)] def test_the_delay_doubles_and_then_stops(store: AuthStore): """Capped at the exponent, not only at the delay it produces: `2 ** steps` goes on growing after the cap has stopped mattering, and sixty wrong answers used to overflow the `timedelta` and raise out of `check_password` -- a 500 on every login attempt, from an attacker who only ever sent wrong passwords.""" assert _lockout(_GRACE) == timedelta(seconds=30) assert _lockout(_GRACE + 1) == timedelta(seconds=60) assert _lockout(_GRACE + 200) == _MAX_LOCK store.set_password(PASSWORD) for _ in range(60): assert store.check_password("wrong") is False assert 0 < store.locked_for() <= _MAX_LOCK.total_seconds() assert store.check_password(PASSWORD) is True def test_wrong_guesses_in_parallel_are_each_counted(store: AuthStore): """`failures` was read, scrypt ran, and the read plus one was written, so forty wrong guesses at once recorded one failure and no lockout. The raise is one statement under the write lock now.""" from concurrent.futures import ThreadPoolExecutor store.set_password(PASSWORD) with ThreadPoolExecutor(max_workers=16) as pool: said = list(pool.map(lambda _: store.check_password("wrong"), range(40))) assert said == [False] * 40 assert rows(store, "SELECT failures FROM auth_credential") == [(40,)] assert store.locked_for() > 0 def test_parallel_claims_admit_the_grace_and_no_more(store: AuthStore): """What both doors do: claim, then derive. A claim reads the lockout and counts the attempt in one write transaction, so thirty claims at once admit `_GRACE` guesses and tell the rest to wait, where a read before the derivation and a write after it admitted all thirty.""" from concurrent.futures import ThreadPoolExecutor store.set_password(PASSWORD) def guess(_: int) -> str: if store.claim_attempt(): return "wait" return "right" if store.check_password("wrong", claimed=True) else "wrong" with ThreadPoolExecutor(max_workers=30) as pool: said = list(pool.map(guess, range(30))) assert said.count("wrong") == _GRACE and said.count("wait") == 30 - _GRACE assert rows(store, "SELECT failures FROM auth_credential") == [(_GRACE,)] def test_a_claimed_right_password_clears_the_count(store: AuthStore): """Counted up front, credited back: the fifth claim writes the lockout before the derivation, and a right answer then clears it.""" store.set_password(PASSWORD) for _ in range(_GRACE - 1): assert store.claim_attempt() == 0 assert store.check_password("wrong", claimed=True) is False assert store.claim_attempt() == 0 assert store.locked_for() > 0, "the fifth claim did not write the lockout" assert store.check_password(PASSWORD, claimed=True) is True assert store.locked_for() == 0 assert rows(store, "SELECT failures, locked_until FROM auth_credential") == [(0, "")] def test_a_claim_while_locked_counts_nothing(store: AuthStore): """Hammering while locked out does not extend the lockout.""" store.set_password(PASSWORD) for _ in range(_GRACE): assert store.claim_attempt() == 0 store.check_password("wrong", claimed=True) before = rows(store, "SELECT failures, locked_until FROM auth_credential") for _ in range(10): assert store.claim_attempt() > 0 assert rows(store, "SELECT failures, locked_until FROM auth_credential") == before def test_a_claim_on_a_database_with_no_password_is_granted(store: AuthStore): assert store.claim_attempt() == 0 assert store.check_password(PASSWORD, claimed=True) is False # -------------------------------------------------------------- the sessions def test_a_session_is_live_until_it_is_not(store: AuthStore): token = store.open_session("pytest", 30) session = store.touch(token) assert session is not None and session.current is True assert [s.label for s in store.sessions()] == ["pytest"] def test_an_expired_session_is_not_a_session(store: AuthStore): """Expiry is enforced in the `WHERE`, not by the sweep: a row that has run out stops working the moment it does, whether or not anything purged it.""" token = store.open_session("pytest", 30) with closing(sqlite3.connect(store.path)) as conn, conn: conn.execute("UPDATE auth_sessions SET expires_at='2000-01-01T00:00:00+00:00'") assert store.touch(token) is None assert store.sessions() == [] assert store.purge() == 1 assert rows(store, "SELECT id FROM auth_sessions") == [] def test_revoking_one_session_leaves_the_others(store: AuthStore): mine = store.open_session("mine", 30) theirs = store.open_session("phone", 30) (row,) = [s for s in store.sessions(mine) if not s.current] assert store.close_by_id(row.id) is True assert store.close_by_id(row.id) is False, "a second revoke invented a row" assert store.touch(theirs) is None assert store.touch(mine) is not None def test_close_all_can_spare_the_caller(store: AuthStore): """The whole reason sessions are rows rather than signed tokens.""" mine = store.open_session("mine", 30) store.open_session("phone", 30) store.open_session("laptop", 30) assert store.close_all(keep=mine) == 2 assert [s.label for s in store.sessions(mine)] == ["mine"] assert store.close_all() == 1 assert store.sessions() == [] def test_the_current_session_is_flagged_and_only_that_one(store: AuthStore): mine = store.open_session("mine", 30) store.open_session("phone", 30) assert sum(s.current for s in store.sessions(mine)) == 1 assert sum(s.current for s in store.sessions()) == 0 def test_last_seen_is_not_written_on_every_touch(store: AuthStore): """This runs on every request there is. A timestamp nobody reads more precisely than "today" is not worth SQLite's write lock.""" token = store.open_session("pytest", 30) first = rows(store, "SELECT last_seen_at FROM auth_sessions") store.touch(token) assert rows(store, "SELECT last_seen_at FROM auth_sessions") == first old = (datetime.now(UTC) - timedelta(hours=1)).isoformat() with closing(sqlite3.connect(store.path)) as conn, conn: conn.execute("UPDATE auth_sessions SET last_seen_at=?", (old,)) store.touch(token) assert rows(store, "SELECT last_seen_at FROM auth_sessions") != [(old,)] # ------------------------------------------------------ passkeys, as rows def test_a_passkey_is_kept_renamed_and_revoked(store: AuthStore): key_id = store.add_passkey(b"cred-id", b"public-key", 3, "usb,nfc", "YubiKey") (key,) = store.passkeys() assert (key.label, key.transports) == ("YubiKey", ["usb", "nfc"]) assert store.passkey_ids() == [b"cred-id"] assert store.passkey_for(b"cred-id") == (key_id, b"public-key", 3) assert store.passkey_for(b"never seen") is None assert store.rename_passkey(key_id, "The one on my keyring") is True assert store.passkeys()[0].label == "The one on my keyring" store.record_passkey_use(key_id, 4) assert store.passkey_for(b"cred-id")[2] == 4 assert store.passkeys()[0].last_used_at assert store.delete_passkey(key_id) is True assert store.delete_passkey(key_id) is False assert store.passkeys() == [] def test_a_challenge_is_single_use_and_knows_what_it_was_for(store: AuthStore): store.remember_challenge(b"one", "register") assert store.take_challenge(b"one", "login") is False, "purposes are not pooled" assert store.take_challenge(b"one", "register") is True assert store.take_challenge(b"one", "register") is False, "it was spent" def test_an_abandoned_challenge_is_swept_by_the_next_one(store: AuthStore): """The endpoint that hands these out needs no session, so a ceremony nobody finished must not sit in the table until a restart.""" store.remember_challenge(b"abandoned", "login", seconds=-1) store.remember_challenge(b"fresh", "login") assert rows(store, "SELECT challenge FROM auth_challenges") == [(b"fresh",)] def test_the_store_makes_its_own_folder(tmp_path: Path): """`data/app.db` on a fresh clone: the directory is not there yet, and the first thing that opens the file is whatever runs first.""" store = AuthStore(tmp_path / "nowhere" / "yet" / "app.db") assert store.path.exists() assert store.has_password() is False