Take auth/ whole from boilerplate 09e144d: the lockout claimed before the scrypt, APP_PASSWORD recovery closing every session, Starlette's cookie parser, the rightmost forwarded hop in the log, revoke_all on a password change, a 421 for a non-loopback Host on an open app, API tokens in auth_tokens behind Authorization: Bearer, and sockets closed with their credential

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
WolfandClaude Fable 5.1 committed 2026-10-27 11:51:21 +01:00
1 parent 83e965dfeb
commit 244e57ac29
19 files changed
+2288 -214

No files matched your search

+207 -26
View File
@@ -1,6 +1,7 @@
"""One password, and the sessions it opens. Nothing else knows a hash.
"""One password, the sessions it opens, and the tokens that stand in for it
from a script. Nothing else knows a hash.
Four tables in whatever SQLite file it is given — the app's own, normally, so
Five tables in whatever SQLite file it is given — the app's own, normally, so
there is one file to back up and SQLite's writer lock keeps auth honest with
everything else in it. Every name starts `auth_`, because the file is shared:
a `sessions` table is a name an app is entitled to want for itself.
@@ -54,7 +55,7 @@ from contextlib import closing
from datetime import UTC, datetime, timedelta
from pathlib import Path
from auth.models import Passkey, SessionInfo
from auth.models import ApiToken, Passkey, SessionInfo
#: scrypt cost. `n` is the work factor, and 2**14 with `r=8` is the widely
#: recommended interactive setting: about 16 MB and ~50 ms per guess, which is
@@ -86,6 +87,12 @@ _MAX_LOCK = timedelta(minutes=15)
#: the ceiling. See `_lockout` for what goes wrong without it.
_MAX_STEPS = math.ceil(math.log2(_MAX_LOCK / _FIRST_LOCK))
#: How much of a token the account screen is shown, so the owner can tell
#: which environment variable holds which row. Eight of forty-three characters
#: from `token_urlsafe(32)` leaves 210 bits unknown, which is still past
#: anybody's ability to guess.
HINT = 8
#: How stale `last_seen_at` may get before a request bothers to update it.
#: Without this, every single request — every socket frame's sibling fetch,
#: every poll of a page left open — takes SQLite's write lock to move a
@@ -96,7 +103,7 @@ _SEEN_EVERY = timedelta(minutes=5)
#: The tables. Created on construction rather than by a migration step, because
#: the only schema change this has ever had is "it did not exist yet", and a
#: migration runner for four `CREATE TABLE IF NOT EXISTS` is a thing to
#: migration runner for five `CREATE TABLE IF NOT EXISTS` is a thing to
#: maintain in exchange for nothing.
SCHEMA = """
CREATE TABLE IF NOT EXISTS auth_credential (
@@ -130,6 +137,15 @@ CREATE TABLE IF NOT EXISTS auth_challenges (
purpose TEXT NOT NULL,
expires_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS auth_tokens (
id INTEGER PRIMARY KEY,
token_hash TEXT NOT NULL UNIQUE,
hint TEXT NOT NULL DEFAULT '',
label TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL,
last_used_at TEXT NOT NULL DEFAULT '',
expires_at TEXT NOT NULL DEFAULT ''
);
"""
@@ -151,7 +167,7 @@ def _derive(password: str, salt: bytes) -> bytes:
class AuthStore:
"""The four `auth_*` tables, opened on the path it is handed.
"""The five `auth_*` tables, opened on the path it is handed.
store = AuthStore("data/app.db")
@@ -207,13 +223,8 @@ class AuthStore:
)
def locked_for(self) -> int:
"""Seconds until the next attempt will be looked at, or 0.
Read before checking rather than after, so a locked-out caller is told
to wait instead of having a guess counted — otherwise a fast enough
attacker extends their own lockout forever and never notices, and, more
to the point, an honest person hammering the button digs a deeper hole
with every press.
"""Seconds until the next attempt will be looked at, or 0. Reads only;
the doors ask `claim_attempt`, which decides and counts in one step.
"""
with closing(self._connect()) as conn:
row = conn.execute(
@@ -223,9 +234,61 @@ class AuthStore:
remaining = datetime.fromisoformat(row["locked_until"]) - _now()
return max(0, int(remaining.total_seconds() + 0.999))
def check_password(self, password: str) -> bool:
def claim_attempt(self) -> int:
"""Claim one guess at the password before it is derived: 0 when the
guess may go ahead, else the seconds until one may.
Inside one `BEGIN IMMEDIATE`, `locked_until` is read and, when it has
passed, the attempt is counted as a failure up front and the lockout
it would earn is written; `check_password(..., claimed=True)` then
clears both when the guess was right. Read before scrypt and written
after it, thirty wrong guesses in parallel each found the door open
and each got a 401, so a window admitted a threadpool of guesses
rather than `_GRACE`. Now the sixth concurrent claim finds the lockout
the fifth wrote.
A refused claim writes nothing, so a caller locked out is told to wait
instead of having a guess counted: otherwise a fast enough attacker
extends their own lockout forever and never notices, and an honest
person hammering the button digs a deeper hole with every press. On a
database with no password there is nothing to count and nothing to
lock, and the claim is granted.
"""
with closing(self._connect()) as conn:
conn.execute("BEGIN IMMEDIATE")
try:
row = conn.execute(
"SELECT failures, locked_until FROM auth_credential WHERE id=1"
).fetchone()
wait = 0
if row is not None:
now = _now()
if row["locked_until"]:
remaining = datetime.fromisoformat(row["locked_until"]) - now
wait = max(0, int(remaining.total_seconds() + 0.999))
if not wait:
failures = int(row["failures"]) + 1
conn.execute(
"UPDATE auth_credential SET failures=?, locked_until=? WHERE id=1",
(failures, _stamp(now + _lockout(failures))
if failures >= _GRACE else ""))
conn.commit()
except BaseException:
conn.rollback()
raise
return wait
def check_password(self, password: str, *, claimed: bool = False) -> bool:
"""Right or wrong, and record which.
`claimed` says the caller counted this guess with `claim_attempt`
already, which is what both doors do: a wrong answer then writes
nothing more and a right one clears the count. Without it a wrong
answer is counted here, after the derivation, which is what a caller
that is not a door wants: `auth.bootstrap` compares the pinned
password, and its comparison cannot lock anyone out because it is
followed by `set_password`, which clears the count.
`hmac.compare_digest` rather than `==`, so the comparison takes the same
time whatever the first wrong byte is. That is close to superstition at
this scale — the network jitter in front of it is larger than the signal
@@ -247,29 +310,42 @@ class AuthStore:
owner still gets locked out by their own typos: strictly worse than
this, and it would look like protection. So the address is written to
the log instead, at WARNING, where fail2ban can act on it at the layer
that actually knows who connected — see `_warn` in `auth/router.py`.
that actually knows who connected — see `warn` in `auth/middleware.py`.
What is left for this counter to do is make guessing pointless, which it
does whoever is guessing.
"""
with closing(self._connect()) as conn:
row = conn.execute(
"SELECT salt, hash, failures FROM auth_credential WHERE id=1"
).fetchone()
if row is None:
# `fetchall`, so no read is left open on this connection when it
# asks for the write lock below.
rows = conn.execute(
"SELECT salt, hash FROM auth_credential WHERE id=1").fetchall()
if not rows:
_derive(password, b"no password here")
return False
ok = hmac.compare_digest(_derive(password, row["salt"]), row["hash"])
with conn:
ok = hmac.compare_digest(_derive(password, rows[0]["salt"]), rows[0]["hash"])
if claimed and not ok:
return False
# The count is raised in the database under the write lock, and
# the lockout is decided from what that raise returned. Read
# before scrypt and written after it, forty guesses in parallel
# each wrote "one more than before" and recorded one failure.
conn.execute("BEGIN IMMEDIATE")
try:
if ok:
conn.execute(
"UPDATE auth_credential SET failures=0, locked_until='' WHERE id=1")
else:
failures = int(row["failures"]) + 1
elif counted := conn.execute(
"UPDATE auth_credential SET failures = failures + 1 WHERE id=1 "
"RETURNING failures").fetchall():
failures = int(counted[0][0])
conn.execute(
"UPDATE auth_credential SET failures=?, locked_until=? WHERE id=1",
(failures, _stamp(_now() + _lockout(failures))
if failures >= _GRACE else ""),
)
"UPDATE auth_credential SET locked_until=? WHERE id=1",
(_stamp(_now() + _lockout(failures))
if failures >= _GRACE else "",))
conn.commit()
except BaseException:
conn.rollback()
raise
return ok
def changed_at(self) -> str:
@@ -368,6 +444,104 @@ class AuthStore:
cur = conn.execute("DELETE FROM auth_sessions")
return cur.rowcount
def revoke_credentials(self) -> tuple[int, int]:
"""Delete every API token and every passkey in one transaction, for a
password change made because the account may be in someone else's
hands. Returns `(tokens, passkeys)` deleted. The password stays, so
this cannot lock the owner out."""
with closing(self._connect()) as conn, conn:
tokens = conn.execute("DELETE FROM auth_tokens").rowcount
keys = conn.execute("DELETE FROM auth_passkeys").rowcount
return tokens, keys
def counts(self) -> tuple[int, int]:
"""`(tokens, passkeys)` registered, expired tokens included, for a
caller that reports what is left after a password change."""
with closing(self._connect()) as conn:
tokens = conn.execute("SELECT COUNT(*) FROM auth_tokens").fetchone()[0]
keys = conn.execute("SELECT COUNT(*) FROM auth_passkeys").fetchone()[0]
return int(tokens), int(keys)
# ---------------------------------------------------------------- tokens
#
# A token is a session for a script: the same 32 random bytes, the same
# SHA-256 in the file, carried as `Authorization: Bearer` instead of a
# cookie. It differs from a session in what it is for. A session is a
# browser that typed the password once and is signed out by a password
# change; a token is minted on purpose, named, optionally dated, and
# survives a password change the way a passkey does, because the cron job
# holding it is not the thing the password was changed against. It is
# revoked by its row, from the account screen, which a token cannot reach
# (`auth.middleware.ACCOUNT`).
def create_token(self, label: str, days: int | None) -> tuple[int, str]:
"""Mint one. Returns `(row id, token)`; the token exists only in that
return value, so the caller shows it once and never again.
`days` of None is a token that does not expire: the cron job that
holds it is not going to type a new one, and the row's last-used
stamp is what tells an abandoned one from one in use.
"""
token = secrets.token_urlsafe(32)
made = _now()
expires = _stamp(made + timedelta(days=days)) if days else ""
with closing(self._connect()) as conn, conn:
cur = conn.execute(
"""INSERT INTO auth_tokens
(token_hash, hint, label, created_at, last_used_at, expires_at)
VALUES (?,?,?,?,'',?)""",
(_token_hash(token), token[:HINT], label[:100], _stamp(made), expires),
)
return int(cur.lastrowid or 0), token
def touch_token(self, token: str) -> ApiToken | None:
"""The token this bearer value names, if it is live, marking it used.
Expiry is in the `WHERE` as it is for a session; a blank `expires_at`
is a token that does not. `last_used_at` is written at most once every
`_SEEN_EVERY`, for the reason `touch` gives.
"""
digest = _token_hash(token)
now = _now()
stamp = _stamp(now)
with closing(self._connect()) as conn:
row = conn.execute(
"SELECT * FROM auth_tokens WHERE token_hash=? "
"AND (expires_at = '' OR expires_at > ?)",
(digest, stamp),
).fetchone()
if row is None:
return None
used = row["last_used_at"]
if not used or now - datetime.fromisoformat(used) >= _SEEN_EVERY:
with conn:
conn.execute(
"UPDATE auth_tokens SET last_used_at=? WHERE token_hash=?",
(stamp, digest))
used = stamp
return _api_token(row, used)
def tokens(self) -> list[ApiToken]:
"""Every token, newest first, the expired ones included: a row that
ran out is still the owner's to recognise and remove. No hash."""
with closing(self._connect()) as conn:
rows = conn.execute(
"SELECT * FROM auth_tokens ORDER BY created_at DESC, id DESC").fetchall()
return [_api_token(r, r["last_used_at"]) for r in rows]
def rename_token(self, token_id: int, label: str) -> bool:
with closing(self._connect()) as conn, conn:
cur = conn.execute("UPDATE auth_tokens SET label=? WHERE id=?",
(label[:100], token_id))
return cur.rowcount > 0
def delete_token(self, token_id: int) -> bool:
"""Revoke one. By row id, as a session is: the screen has never seen
the token after the moment it was minted."""
with closing(self._connect()) as conn, conn:
cur = conn.execute("DELETE FROM auth_tokens WHERE id=?", (token_id,))
return cur.rowcount > 0
# -------------------------------------------------------------- passkeys
def add_passkey(self, credential_id: bytes, public_key: bytes,
@@ -503,3 +677,10 @@ def _session(row: sqlite3.Row, last_seen: str, current: bool) -> SessionInfo:
id=row["id"], label=row["label"], created_at=row["created_at"],
last_seen_at=last_seen, expires_at=row["expires_at"], current=current,
)
def _api_token(row: sqlite3.Row, last_used: str) -> ApiToken:
return ApiToken(
id=row["id"], label=row["label"], hint=row["hint"], created_at=row["created_at"],
last_used_at=last_used, expires_at=row["expires_at"],
)