ADR-002: Authentication and session strategy

Status: Accepted — ratified by product owner on 2026-11-21. Supersede only with a new ADR.

Date: 2026-11-21

Context

Today identity is Firebase anonymous auth (signInAnonymously); everyone shares one Firestore document (testbank/main). There is no user concept at all — no accounts, no roles, no ownership of questions. The app must become real accounts with roles (user, admin) and Google sign-in. Question authorship is the IP; full control of identity data is a requirement.

Options considered

| Option | What it buys | Cost/risk | Verdict |

|--------|--------------|-----------|---------|

| 1) Roll own — Argon2id + opaque server-side session in an HttpOnly cookie + oauth2 crate for Google | Zero vendor fee, full data ownership, portable across hosts, revocable sessions, standard OWASP-aligned params | You own password resets, email verification, account lockout; more code to maintain | Chosen |

| 2) Vendor — Clerk or Auth0 | Drop-in UI, MFA, SSO, org management, compliance certs | Vendor pricing to be confirmed (TODO(user)); identity data lives with the vendor; question authorship IP leaves your infra; another contract to manage | Rejected |

| 3) Keep Firebase Auth | Already integrated, free tier generous, Google sign-in built in | No server-side session revocation; anonymous auth cannot migrate to identified users cleanly; Firestore rules are the only authorization layer; vendor lock-in | Rejected |

Decision

Roll own authentication with the following precise mechanism:

Signup (email/password)

1. Client POST /api/auth/signup with { email, password }.

2. Server validates email format, password ≥ 12 chars, checks users table for existing email.

3. Hash password with Argon2id (argon2 crate, params: memory 19456 KiB, iterations 2, parallelism 1 — OWASP current baseline).

4. Insert users(id, email, password_hash, role='user', created_at, email_verified=false).

5. Return 201; client redirects to email verification flow (out of scope for v1).

Login (email/password)

1. Client POST /api/auth/login with { email, password }.

2. Server fetches user by email, verifies Argon2id hash (constant-time via argon2::verify_encoded).

3. On success: generate cryptographically random opaque session id (32 bytes, rand::rngs::OsRng).

4. Compute token_hash = sha256(session_id).

5. Insert sessions(token_hash, user_id, expires_at = now() + 30 days, idle_expires_at = now() + 7 days, created_at).

6. Set cookie: __Host-sid=<session_id>; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=2592000 (30 days).

7. Response body: { user: { id, email, role } } — no token in body.

Session validation (every request)

1. Axum extractor reads __Host-sid cookie.

2. Compute sha256(cookie_value), lookup sessions row where token_hash = $1 AND expires_at > now() AND idle_expires_at > now().

3. On hit: update idle_expires_at = now() + 7 days (sliding window), attach User to request extensions.

4. On miss: return 401, clear cookie.

Google OAuth (authorization-code flow with PKCE)

1. Client GET /api/auth/google/start → server generates code_verifier (PKCE, 43-128 chars) and state; stores the verifier itself (not a hash of it) plus state in an encrypted, HttpOnly cookie __Host-oauth_state (10 min, Secure, SameSite=Lax, AES-GCM encrypted with SESSION_SECRET); redirects to Google with code_challenge=S256(code_verifier) and state.

The verifier must be recoverable at the callback to complete the exchange; this is why it is encrypted-and-stored rather than hashed.

2. Google callback GET /api/auth/google/callback?code=...&state=... → server verifies state cookie, decrypts to recover code_verifier, exchanges code + code_verifier for tokens via oauth2 crate.

3. Fetch Google userinfo (email, verified_email, sub).

4. If verified_email true: upsert users by email, set google_id = sub if null.

5. Create session as in Login step 3–7.

Why JWT is NOT the session token: A self-contained JWT cannot be revoked before expiry without a server-side blocklist (defeating the purpose). An opaque session id + server-side sessions table allows immediate revocation (logout everywhere, admin ban, password change) and sliding idle expiry.

Cookie and CSRF rules

  • __Host- prefix (requires Secure, Path=/, no Domain attribute) — prevents subdomain cookie injection. This applies to __Host-csrf as well as __Host-sid: the CSRF cookie is Secure; Path=/; SameSite=Strict and carries no Domain attribute, or browsers reject it outright.
  • HttpOnly — inaccessible to JavaScript (XSS cannot steal session).
  • Secure — only sent over HTTPS.
  • SameSite=Lax — CSRF protection for navigational requests; Strict breaks magic links.
  • CSRF double-submit token required on all non-GET endpoints:
  • - Issue csrf_token (32-byte random) in a separate cookie __Host-csrf (SameSite=Strict) on login.
  • - Client reads cookie (via document.cookie — not HttpOnly) and sends header X-CSRF-Token: <value> on every mutating request.
  • - Server validates header matches cookie value.
  • When the CSRF token is issued. Not only at login: any response that establishes or refreshes a session also (re)issues __Host-csrf, and the server accepts a request whose X-CSRF-Token matches the cookie value. If a client with a valid session presents no CSRF cookie, it gets a 403 with a body telling it to reload; a full page load always reissues the token. This prevents the "logged in but every POST fails" state after a cookie is cleared.
  • The CSRF cookie is deliberately NOT HttpOnly — the browser must read it to echo the token in X-CSRF-Token. The session cookie __Host-sid stays HttpOnly. Adding HttpOnly to the CSRF cookie breaks the flow silently.
  • Session rotation on privilege change: on role upgrade/downgrade, delete old session row, issue new session id + cookie.
  • Absolute + idle expiry: 30 days absolute (expires_at), 7 days idle (idle_expires_at sliding).
  • Account enumeration

    Signup and login must not reveal whether an email is registered.

  • POST /auth/signup with an existing email returns the same 201 and the same body as a new signup (the
  • user is emailed "you already have an account", not told in the response).

  • POST /auth/login with an unknown email still performs one Argon2id verification against a fixed dummy
  • hash, so response time does not distinguish "no such user" from "wrong password", and returns the same

    401 message in both cases. The existence check on signup must also be a single indexed lookup whose timing does not differ from the insert path; do not branch on "found" before hashing.

  • Password reset always returns 202 regardless of whether the address exists.
  • This costs a constant-time dummy verify per failed login; that is accepted.

    Roles

    Two roles only, stored as role TEXT NOT NULL DEFAULT 'user' CHECK (role IN ('user','admin')) on users:

  • user — can create private questions, take tests, view own history.
  • admin — full access to curated pool, user management, analytics, settings.
  • Authorization via two Axum extractors:

  • require_auth — validates session, returns User, 401 if missing/invalid.
  • require_admin — chains require_auth and returns 403 if user.role != 'admin'.
  • Consequences

    Positive

  • Zero vendor fee; no per-MAU pricing.
  • Full control of identity data — question authorship (the IP) never leaves your database.
  • Portable: works on Fly.io, Railway, bare metal, any container host.
  • Standard OWASP-aligned Argon2id params; revocable sessions; sliding idle expiry.
  • Negative

  • You own password resets, email verification, account lockout, breach notification.
  • No built-in MFA, SSO/SAML, device fingerprinting, or risk-based auth in v1.
  • More code to audit and maintain (auth module plus migrations; size to be established during Phase 1).
  • What we explicitly do NOT build (v1)

  • SSO / SAML / OIDC federation (follow-up).
  • MFA (TOTP, WebAuthn, SMS) — listed as follow-up.
  • User-facing session management UI (view/revoke other sessions).
  • Account recovery without email verification (email verification is a prerequisite for any recovery flow).
  • Password history / rotation policies.
  • Open questions

    1. Email delivery provider for verification/reset — SendGrid, Resend, Postmark, or self-hosted? (TODO(user): pick one and add env var).

    2. Whether to add a password_changed_at column to force re-login on credential change (recommended, 5 min to add).

    3. Rate limiting on /api/auth/* — governor crate vs Cloudflare WAF rule vs both?