Harden the API and the data layer after a security and performance audit

Security
- Every route now requires a login and refuses ids outside the caller's
  workspace with 404: plan, leave-wishes, day-overrides and vacation-days
  were fully anonymous; every other router trusted client-supplied
  workspace/child/parent ids. Scraper sessions are bound to their owner.
- Invitations can no longer be created for a foreign workspace, and a
  redeemer who is already a member (or a full workspace) is refused.
- Production refuses the default JWT secret; API docs are hidden in
  production; a failed migration aborts startup instead of serving.
- Login and register no longer reveal whether an email exists; inactive
  accounts are rejected; /auth/refresh is rate limited.
- The FK scraper writes debug artefacts only when explicitly enabled,
  logs no scraped values or page text, clears the BankID QR as soon as it
  is scanned and purges finished sessions after five minutes.
- Real FK page captures are removed from the tree (history rewrite
  follows); the parser tests use a synthetic fixture.

Performance and correctness
- Plan apply/sync run inside one locked transaction with batched writes
  instead of one commit per row, so a failure mid-batch leaves nothing
  half-applied and concurrent syncs no longer corrupt each other.
- SQLite runs in WAL mode with a busy timeout; 14 indexes cover the
  filters that were full scans; argon2 hashing runs off the event loop;
  responses are gzipped.
- Frontend: a 401 now refreshes the token once and retries, so sessions
  no longer die silently after 15 minutes; every data hook discards
  stale responses; logout clears state even when the server call fails.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CsXCCcDfmV4Sps4ZQSvNEY
This commit is contained in:
2026-09-18 07:54:21 +02:00
parent ae16d71970
commit 02db5430eb
81 changed files with 3616 additions and 600 deletions
+32 -5
View File
@@ -13,9 +13,13 @@ the common-case figures — children born before 2014, multiples, and single
custody differ and should become explicit config when tackled.
"""
from pydantic import BaseModel, ConfigDict
from typing import Literal
from pydantic import BaseModel, ConfigDict, model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
_DEV_JWT_SECRET = "dev-secret-change-in-production-min-32-chars"
class LeaveRules(BaseModel):
"""Frozen Swedish föräldrapenning rule defaults (single source of truth)."""
@@ -95,6 +99,11 @@ class Settings(BaseSettings):
extra="ignore",
)
# Deployment environment. Gates production-only hardening (see the
# model_validator below and main.py's docs_url handling). Never set to
# "production" in tests/dev — the validator below will refuse to start.
app_env: Literal["development", "test", "production"] = "development"
# 'sqlite' for local dev, 'postgres' for production (swap repository impls).
database_type: str = "sqlite"
sqlite_path: str = "./foraldraledig.db"
@@ -103,12 +112,12 @@ class Settings(BaseSettings):
cors_origins: list[str] = ["http://localhost:5173"]
# Auth — change jwt_secret in production (min 32 chars).
jwt_secret: str = "dev-secret-change-in-production-min-32-chars"
jwt_secret: str = _DEV_JWT_SECRET
jwt_algorithm: str = "HS256"
jwt_access_token_expire_minutes: int = 15
jwt_refresh_token_expire_days: int = 7
log_level: str = "DEBUG"
log_level: str = "INFO"
# FK scraper — legal/ToS review completed (2026-06); cleared for use.
# Default is True. Set APP_SCRAPER_ENABLED=false to disable (e.g. an
@@ -117,10 +126,28 @@ class Settings(BaseSettings):
scraper_enabled: bool = True
scraper_headless: bool = True
scraper_session_ttl_seconds: int = 180 # auto-cancel awaiting_scan/authenticating sessions
# Set to None to disable debug artifact saving. Files may contain personal data.
scraper_debug_dir: str | None = "./debug/scraper"
# Debug artifacts (HTML + full-page screenshot of the logged-in FK page)
# are OFF by default — they contain personal data (name, balances,
# payout amounts). Both fields below must be set to enable them; this is
# a deliberate opt-in for local debugging only, never for production.
scraper_debug_dir: str | None = None
scraper_debug_enabled: bool = False
# How long a terminal (done/error/cancelled) session's QR/result stays in
# RAM before `_ttl_watchdog`/`poll` purge it from `_sessions`.
scraper_result_retention_seconds: int = 300
rules: LeaveRules = LeaveRules()
@model_validator(mode="after")
def _require_strong_jwt_secret_in_production(self) -> "Settings":
if self.app_env == "production" and (
self.jwt_secret == _DEV_JWT_SECRET or len(self.jwt_secret) < 32
):
raise ValueError(
"APP_JWT_SECRET must be set to a random value of at least 32 characters "
"when APP_ENV=production"
)
return self
settings = Settings()