Files
coremarket/app/auth.py
T
davidandClaude Opus 5.5 1bb2a299c7 Add Coremarket: Federated Core VM sizing and cloud pricing app
Dockerised FastAPI web app that sizes a VM for a selection of Federated
Computer apps (Base/Good/Better/Best tiers or custom) and prices it across
14 cloud providers and ~250 regions, grouped by continent.

- Sizing model per app with shared databases, headroom and disk growth
- Live pricing from Vultr, Akamai/Linode and Azure (DigitalOcean and
  Hetzner with tokens); dated catalog for the rest
- Hand-maintained Contabo price sheet with editor and table paste,
  including the one-time setup fee
- HIPAA/SOC2/PCI DSS/GDPR status, SMTP port 25, IPv4 and egress notes
- Estimated latency to 40 cities, real RTT via Globalping probes
- Versioned REST API (/api/v1) with OpenAPI docs and CSV export
- Accounts with admin/user roles, first admin from ADMIN_USERNAME /
  ADMIN_PASSWORD, per-account API keys, SQLite storage

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 21:36:51 -07:00

372 lines
15 KiB
Python

"""Accounts, API keys and sessions (SQLite in $DATA_DIR/coremarket.db, stdlib only).
- Passwords: scrypt with a per-user salt.
- API keys: "cmk_<8-char prefix>_<secret>"; only a SHA-256 hash is stored, the key is shown once.
- Sessions: random token in an HttpOnly cookie; only its SHA-256 hash is stored.
"""
from __future__ import annotations
import hashlib
import hmac
import logging
import os
import secrets
import sqlite3
import threading
import time
from contextlib import contextmanager
from pathlib import Path
from fastapi import Depends, HTTPException, Request
from fastapi.security import APIKeyHeader, HTTPAuthorizationCredentials, HTTPBearer
log = logging.getLogger("coremarket.auth")
DATA_DIR = Path(os.environ.get("DATA_DIR", "/data"))
DB_PATH = DATA_DIR / "coremarket.db"
SESSION_COOKIE = "cm_session"
SESSION_HOURS = float(os.environ.get("SESSION_HOURS", "12"))
COOKIE_SECURE = os.environ.get("COOKIE_SECURE", "0") == "1"
MIN_PASSWORD = 10
ROLES = ("admin", "user")
CSRF_HEADER = "x-coremarket" # required on cookie-authenticated writes (blocks cross-site form posts)
_lock = threading.Lock()
# ------------------------------------------------------------------ database
@contextmanager
def db():
with _lock:
con = sqlite3.connect(DB_PATH)
con.row_factory = sqlite3.Row
con.execute("PRAGMA foreign_keys = ON")
try:
yield con
con.commit()
finally:
con.close()
SCHEMA = """
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
username TEXT NOT NULL UNIQUE COLLATE NOCASE,
password_hash TEXT NOT NULL,
role TEXT NOT NULL CHECK (role IN ('admin','user')),
disabled INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL,
last_login INTEGER
);
CREATE TABLE IF NOT EXISTS api_keys (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
name TEXT NOT NULL,
prefix TEXT NOT NULL UNIQUE,
key_hash TEXT NOT NULL,
created_at INTEGER NOT NULL,
expires_at INTEGER,
last_used INTEGER
);
CREATE TABLE IF NOT EXISTS sessions (
token_hash TEXT PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL
);
"""
def init():
"""Create tables; on first run create the admin from ADMIN_USERNAME / ADMIN_PASSWORD."""
DATA_DIR.mkdir(parents=True, exist_ok=True)
with db() as con:
con.execute("PRAGMA journal_mode = WAL")
con.executescript(SCHEMA)
n = con.execute("SELECT COUNT(*) FROM users").fetchone()[0]
con.execute("DELETE FROM sessions WHERE expires_at < ?", (int(time.time()),))
if n:
if os.environ.get("ADMIN_PASSWORD"):
log.info("accounts already exist; ADMIN_USERNAME/ADMIN_PASSWORD are ignored (only used on first run)")
return
user, pw = os.environ.get("ADMIN_USERNAME", "").strip(), os.environ.get("ADMIN_PASSWORD", "")
if not user or not pw:
raise RuntimeError(
"First run: no accounts exist. Set ADMIN_USERNAME and ADMIN_PASSWORD (e.g. in .env next to "
"docker-compose.yml) to create the admin account, then start again.")
try:
create_user(user, pw, "admin")
except HTTPException as e:
raise RuntimeError(f"Cannot create the admin account from ADMIN_USERNAME/ADMIN_PASSWORD: {e.detail}") from None
log.warning("created admin account '%s' from ADMIN_USERNAME/ADMIN_PASSWORD", user)
# ------------------------------------------------------------------ hashing
def hash_password(pw: str) -> str:
salt = secrets.token_bytes(16)
h = hashlib.scrypt(pw.encode(), salt=salt, n=2**14, r=8, p=1, dklen=32)
return f"scrypt$16384$8$1${salt.hex()}${h.hex()}"
def verify_password(pw: str, stored: str) -> bool:
try:
_, n, r, p, salt, h = stored.split("$")
calc = hashlib.scrypt(pw.encode(), salt=bytes.fromhex(salt), n=int(n), r=int(r), p=int(p), dklen=len(h) // 2)
return hmac.compare_digest(calc.hex(), h)
except (ValueError, TypeError):
return False
_DUMMY_HASH = hash_password(secrets.token_hex(8)) # equalise timing for unknown usernames
def _sha(s: str) -> str:
return hashlib.sha256(s.encode()).hexdigest()
def check_password(pw: str):
if len(pw) < MIN_PASSWORD:
raise HTTPException(422, f"password must be at least {MIN_PASSWORD} characters")
def check_username(u: str):
if not (2 <= len(u) <= 64) or not all(c.isalnum() or c in "._-@" for c in u):
raise HTTPException(422, "username must be 2-64 characters: letters, digits, . _ - @")
# ------------------------------------------------------------------ users
def _user_out(row) -> dict:
return dict(id=row["id"], username=row["username"], role=row["role"], disabled=bool(row["disabled"]),
created_at=row["created_at"], last_login=row["last_login"])
def create_user(username: str, password: str, role: str) -> dict:
check_username(username)
check_password(password)
if role not in ROLES:
raise HTTPException(422, f"role must be one of {ROLES}")
try:
with db() as con:
cur = con.execute("INSERT INTO users (username, password_hash, role, created_at) VALUES (?,?,?,?)",
(username, hash_password(password), role, int(time.time())))
row = con.execute("SELECT * FROM users WHERE id=?", (cur.lastrowid,)).fetchone()
except sqlite3.IntegrityError:
raise HTTPException(409, f"username '{username}' already exists")
return _user_out(row)
def list_users() -> list[dict]:
with db() as con:
rows = con.execute("SELECT * FROM users ORDER BY id").fetchall()
counts = dict(con.execute("SELECT user_id, COUNT(*) FROM api_keys GROUP BY user_id").fetchall())
return [_user_out(r) | {"api_keys": counts.get(r["id"], 0)} for r in rows]
def get_user(uid: int) -> dict:
with db() as con:
row = con.execute("SELECT * FROM users WHERE id=?", (uid,)).fetchone()
if not row:
raise HTTPException(404, "user not found")
return _user_out(row)
def _active_admins(con, excluding: int) -> int:
return con.execute("SELECT COUNT(*) FROM users WHERE role='admin' AND disabled=0 AND id<>?", (excluding,)).fetchone()[0]
def update_user(uid: int, actor: dict, role: str | None = None, disabled: bool | None = None,
password: str | None = None) -> dict:
target = get_user(uid)
with db() as con:
removing_admin = target["role"] == "admin" and not target["disabled"] and (
(role is not None and role != "admin") or disabled is True)
if removing_admin and _active_admins(con, uid) == 0:
raise HTTPException(409, "cannot demote or disable the last active admin")
if uid == actor["id"] and (disabled is True or (role is not None and role != actor["role"])):
raise HTTPException(409, "you cannot disable yourself or change your own role")
if role is not None:
if role not in ROLES:
raise HTTPException(422, f"role must be one of {ROLES}")
con.execute("UPDATE users SET role=? WHERE id=?", (role, uid))
if disabled is not None:
con.execute("UPDATE users SET disabled=? WHERE id=?", (int(disabled), uid))
if disabled:
con.execute("DELETE FROM sessions WHERE user_id=?", (uid,))
if password is not None:
check_password(password)
con.execute("UPDATE users SET password_hash=? WHERE id=?", (hash_password(password), uid))
con.execute("DELETE FROM sessions WHERE user_id=?", (uid,))
return get_user(uid)
def delete_user(uid: int, actor: dict):
target = get_user(uid)
if uid == actor["id"]:
raise HTTPException(409, "you cannot delete your own account")
with db() as con:
if target["role"] == "admin" and _active_admins(con, uid) == 0:
raise HTTPException(409, "cannot delete the last active admin")
con.execute("DELETE FROM users WHERE id=?", (uid,))
def change_own_password(user: dict, current: str, new: str, keep_token_hash: str | None):
with db() as con:
row = con.execute("SELECT password_hash FROM users WHERE id=?", (user["id"],)).fetchone()
if not verify_password(current, row["password_hash"]):
raise HTTPException(403, "current password is incorrect")
check_password(new)
with db() as con:
con.execute("UPDATE users SET password_hash=? WHERE id=?", (hash_password(new), user["id"]))
# sign out other sessions, keep this one
con.execute("DELETE FROM sessions WHERE user_id=? AND token_hash<>?", (user["id"], keep_token_hash or ""))
# ------------------------------------------------------------------ login throttling
_fails: dict[str, list[float]] = {}
MAX_FAILS, WINDOW = 5, 300
def _throttle_key(username: str, ip: str) -> str:
return f"{username.lower()}|{ip}"
def check_throttle(username: str, ip: str):
now = time.time()
hits = [t for t in _fails.get(_throttle_key(username, ip), []) if now - t < WINDOW]
_fails[_throttle_key(username, ip)] = hits
if len(hits) >= MAX_FAILS:
raise HTTPException(429, f"too many failed sign-in attempts; try again in {int(WINDOW - (now - hits[0])) + 1} s")
def record_fail(username: str, ip: str):
_fails.setdefault(_throttle_key(username, ip), []).append(time.time())
# ------------------------------------------------------------------ sessions
def login(username: str, password: str, ip: str) -> tuple[str, dict]:
check_throttle(username, ip)
with db() as con:
row = con.execute("SELECT * FROM users WHERE username=?", (username,)).fetchone()
ok = verify_password(password, row["password_hash"] if row else _DUMMY_HASH)
if not row or not ok or row["disabled"]:
record_fail(username, ip)
raise HTTPException(401, "invalid username or password")
_fails.pop(_throttle_key(username, ip), None)
token = secrets.token_urlsafe(32)
now = int(time.time())
with db() as con:
con.execute("INSERT INTO sessions VALUES (?,?,?,?)", (_sha(token), row["id"], now, now + int(SESSION_HOURS * 3600)))
con.execute("UPDATE users SET last_login=? WHERE id=?", (now, row["id"]))
return token, _user_out(row)
def logout(token: str | None):
if token:
with db() as con:
con.execute("DELETE FROM sessions WHERE token_hash=?", (_sha(token),))
def _session_user(token: str) -> dict | None:
with db() as con:
row = con.execute(
"SELECT u.* FROM sessions s JOIN users u ON u.id=s.user_id WHERE s.token_hash=? AND s.expires_at>? AND u.disabled=0",
(_sha(token), int(time.time()))).fetchone()
return _user_out(row) if row else None
# ------------------------------------------------------------------ API keys
def _key_out(row, owner: str | None = None) -> dict:
d = dict(id=row["id"], user_id=row["user_id"], name=row["name"], prefix=f"cmk_{row['prefix']}_…",
created_at=row["created_at"], expires_at=row["expires_at"], last_used=row["last_used"],
expired=bool(row["expires_at"] and row["expires_at"] < time.time()))
if owner is not None:
d["username"] = owner
return d
def create_key(user_id: int, name: str, expires_days: int | None) -> tuple[str, dict]:
name = (name or "").strip()[:100] or "API key"
get_user(user_id)
prefix = secrets.token_hex(4)
secret = secrets.token_urlsafe(32)
key = f"cmk_{prefix}_{secret}"
now = int(time.time())
exp = now + expires_days * 86400 if expires_days else None
with db() as con:
cur = con.execute("INSERT INTO api_keys (user_id, name, prefix, key_hash, created_at, expires_at) VALUES (?,?,?,?,?,?)",
(user_id, name, prefix, _sha(key), now, exp))
row = con.execute("SELECT * FROM api_keys WHERE id=?", (cur.lastrowid,)).fetchone()
return key, _key_out(row)
def list_keys(user_id: int | None = None) -> list[dict]:
q = "SELECT k.*, u.username FROM api_keys k JOIN users u ON u.id=k.user_id"
args: tuple = ()
if user_id is not None:
q += " WHERE k.user_id=?"
args = (user_id,)
with db() as con:
rows = con.execute(q + " ORDER BY k.id", args).fetchall()
return [_key_out(r, r["username"]) for r in rows]
def delete_key(key_id: int, actor: dict):
with db() as con:
row = con.execute("SELECT user_id FROM api_keys WHERE id=?", (key_id,)).fetchone()
if not row or (actor["role"] != "admin" and row["user_id"] != actor["id"]):
raise HTTPException(404, "API key not found")
con.execute("DELETE FROM api_keys WHERE id=?", (key_id,))
def _key_user(key: str) -> dict | None:
parts = key.split("_")
if len(parts) < 3 or parts[0] != "cmk":
return None
now = int(time.time())
with db() as con:
row = con.execute(
"SELECT k.id AS kid, k.key_hash, k.expires_at, u.* FROM api_keys k JOIN users u ON u.id=k.user_id "
"WHERE k.prefix=? AND u.disabled=0", (parts[1],)).fetchone()
if not row or not hmac.compare_digest(row["key_hash"], _sha(key)) or (row["expires_at"] and row["expires_at"] < now):
return None
con.execute("UPDATE api_keys SET last_used=? WHERE id=?", (now, row["kid"]))
return _user_out(row)
# ------------------------------------------------------------------ FastAPI dependencies
_key_header = APIKeyHeader(name="X-API-Key", auto_error=False, description="API key created under Account → API keys")
_bearer = HTTPBearer(auto_error=False, description="Same API key, sent as Authorization: Bearer <key>")
def current_user(request: Request, x_api_key: str | None = Depends(_key_header),
bearer: HTTPAuthorizationCredentials | None = Depends(_bearer)) -> dict:
key = x_api_key or (bearer.credentials.strip() if bearer else None)
if key:
user = _key_user(key)
if not user:
raise HTTPException(401, "invalid, expired or revoked API key", headers={"WWW-Authenticate": "Bearer"})
user["auth"] = "api_key"
return user
token = request.cookies.get(SESSION_COOKIE)
user = _session_user(token) if token else None
if not user:
raise HTTPException(401, "sign in or send an API key (header X-API-Key)", headers={"WWW-Authenticate": "Bearer"})
if request.method not in ("GET", "HEAD", "OPTIONS") and request.headers.get(CSRF_HEADER) != "1":
raise HTTPException(403, f"missing {CSRF_HEADER} header on a browser-session request")
user["auth"] = "session"
user["token_hash"] = _sha(token)
return user
def require_admin(user: dict = Depends(current_user)) -> dict:
if user["role"] != "admin":
raise HTTPException(403, "admin role required")
return user