feat(api): implement per-user edit token for settings mutations

This commit is contained in:
shay
2026-04-19 09:34:26 -04:00
parent 3ecb6ad67b
commit 016583c9f3
16 changed files with 774 additions and 116 deletions
+55 -8
View File
@@ -4,8 +4,10 @@ All access goes through this module so a future Postgres swap is local to here.
Both DBs are opened with WAL mode.
"""
import hashlib
import hmac as _hmac
import json
import os
import secrets
import sqlite3
from contextlib import contextmanager
from datetime import datetime, timedelta
@@ -24,7 +26,8 @@ CREATE TABLE IF NOT EXISTS users (
enrolled_at TEXT NOT NULL,
last_fetcher_payload_hash TEXT,
manual_refresh_used INTEGER DEFAULT 0,
last_requested_at TEXT NOT NULL
last_requested_at TEXT NOT NULL,
edit_token_hash TEXT
);
CREATE TABLE IF NOT EXISTS enrollments_daily (
day TEXT PRIMARY KEY,
@@ -109,12 +112,33 @@ def _widgets_conn():
def init_dbs() -> None:
with _settings_conn() as c:
c.executescript(_SETTINGS_SCHEMA)
# Additive migration for DBs created before the auth rollout.
cols = {r["name"] for r in c.execute("PRAGMA table_info(users)").fetchall()}
if "edit_token_hash" not in cols:
c.execute("ALTER TABLE users ADD COLUMN edit_token_hash TEXT")
c.commit()
with _widgets_conn() as c:
c.executescript(_WIDGETS_SCHEMA)
c.commit()
def _hash_edit_token(token: str) -> str:
return hashlib.sha256(token.encode("utf-8")).hexdigest()
def verify_edit_token(username: str, presented: str) -> bool:
"""Constant-time check of the caller's edit token against the stored hash."""
if not username or not presented:
return False
with _settings_conn() as c:
row = c.execute(
"SELECT edit_token_hash FROM users WHERE username=?", (username,)
).fetchone()
if row is None or not row["edit_token_hash"]:
return False
return _hmac.compare_digest(row["edit_token_hash"], _hash_edit_token(presented))
def settings_hash(settings: dict) -> str:
canonical = json.dumps(settings, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
@@ -122,17 +146,29 @@ def settings_hash(settings: dict) -> str:
# ---- settings / enrollment ----
def enroll(username: str, defaults: dict) -> int:
"""Insert a settings row + increment daily counter + enqueue build. Returns job_id."""
def enroll(username: str, defaults: dict) -> dict:
"""Insert a settings row + increment daily counter + enqueue build.
Returns {"job_id", "edit_token"}. The edit_token is the bearer token the
caller must present on future settings mutations for this user. We only
store its SHA-256 hash, so the plaintext here is the one and only chance
to surface it to the client. Subsequent enroll() calls for an existing
user return `edit_token=None` to avoid leaking tokens issued to earlier
registrants — settings cannot be taken over by re-enrolling.
"""
sh = settings_hash(defaults)
now = _now()
token = secrets.token_urlsafe(32)
token_hash = _hash_edit_token(token)
with _settings_conn() as c:
c.execute(
"""INSERT INTO users(username, settings_json, settings_hash, enrolled_at, last_requested_at)
VALUES (?, ?, ?, ?, ?)
cur_ins = c.execute(
"""INSERT INTO users(username, settings_json, settings_hash, enrolled_at,
last_requested_at, edit_token_hash)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(username) DO NOTHING""",
(username, json.dumps(defaults), sh, now, now),
(username, json.dumps(defaults), sh, now, now, token_hash),
)
inserted = cur_ins.rowcount == 1
c.execute(
"""INSERT INTO enrollments_daily(day, count) VALUES (?, 1)
ON CONFLICT(day) DO UPDATE SET count = count + 1""",
@@ -144,7 +180,10 @@ def enroll(username: str, defaults: dict) -> int:
(username, now, now),
)
c.commit()
return cur.lastrowid
return {
"job_id": cur.lastrowid,
"edit_token": token if inserted else None,
}
def enrollments_today() -> int:
@@ -239,6 +278,14 @@ def enqueue_build(username: str) -> int:
return cur.lastrowid
def pending_job_count() -> int:
"""Depth of the build queue. Used as backpressure so bursts of
enroll/PATCH don't blow up SQLite when the worker is behind."""
with _settings_conn() as c:
row = c.execute("SELECT COUNT(*) AS n FROM jobs WHERE status='pending'").fetchone()
return int(row["n"]) if row else 0
def claim_next_job() -> Optional[dict]:
now = _now()
with _settings_conn() as c: