docs(milestone): complete v0.4-operator-tier — v0.1.9 tagged, milestone release, merged to main

v0.4 (Operator Tier — Cohort Dashboard + Auth + Postgres) milestone complete.

Phases:
  ✓ P0  pre-execution (planning)        → v0.1.6
  ✓ P1  operator foundation (Postgres+auth+VC migration) → v0.1.7
  ✓ P2  cohort dashboard + aggregation   → v0.1.8
  ✓ P3  final review + ship              → v0.1.9 (= v0.4 milestone release)

Requirements covered (8/8):
  REQ-MT-01 (Postgres store), REQ-MT-02 (aggregation pipeline),
  REQ-AUTH-01 (operator auth), REQ-DASH-01 (cohort dashboard),
  REQ-NFR-AUTH-01 (auth NFRs), REQ-NFR-MT-01 (Postgres-in-LXC),
  REQ-NFR-DASH-01 (k-anonymity ≥10), REQ-NFR-DASH-02 (freshness ≤24h)

Grill MUSTs honored (6/6): G-008, G-011, G-027, G-031, G-038, G-041

Tests: 317 pytest pass, 36 skip (Postgres-requiring), 0 fail; 17/17 vitest pass
Review: APPROVE_WITH_NOTES (6/6 personas, 0 P0, 8 P1+ carry-forward)
Audit: HEALTHY (reconstruction PASS, 8/8 REQ, 6/6 grill)

---ci---
project: praxis
phase: 3
milestone: v0.4
status: complete
phase_role: final
milestone_complete: true
milestone_merged_to_main: true
tag: v0.1.9
requirements:
  covered: [REQ-MT-01, REQ-MT-02, REQ-AUTH-01, REQ-DASH-01, REQ-NFR-AUTH-01, REQ-NFR-MT-01, REQ-NFR-DASH-01, REQ-NFR-DASH-02]
  partial: []
---/ci---
This commit is contained in:
Praxis CI
2026-08-04 11:58:44 +00:00
parent d0f37e151e
commit f2a12f9fed
76 changed files with 12504 additions and 578 deletions
View File
+68
View File
@@ -0,0 +1,68 @@
"""Signed cookie configuration (TASK-03-02, D-041, D-056, R-AUTH-01, G-031).
Returns kwargs for Starlette SessionMiddleware (itsdangerous HMAC-SHA256
signed cookies — D-056, stateless, no sessions table). The cookie name is
`praxis_op` (distinct from any future learner cookie).
R-AUTH-01 / G-031 reframe: the PRIMARY mitigation for a sniffed operator
cookie is the k-anonymity defense-in-depth — the cohort dashboard reads
only k-anonymized aggregates, so a sniffed cookie leaks NO learner PII.
The `PRAXIS_COOKIE_SECURE` flag is the SECONDARY mitigation (operational
convenience for when TLS arrives). It defaults to true; the HTTP pilot
(LXC, no TLS — D-030) sets it to false with a logged WARNING.
"""
from __future__ import annotations
import os
import secrets
from loguru import logger
_COOKIE_MAX_AGE_S = 28800 # 8h (D-041)
def _env_bool(key: str, default: bool) -> bool:
raw = os.environ.get(key, "").strip().lower()
if raw in ("true", "1", "yes", "on"):
return True
if raw in ("false", "0", "no", "off"):
return False
return default
def get_session_middleware_kwargs() -> dict:
"""Return kwargs for Starlette SessionMiddleware.
If PRAXIS_COOKIE_SECRET is unset, generate an ephemeral random secret
and log a WARNING (dev only — sessions won't survive a restart and this
MUST NOT be used in pilot/production).
"""
secret = os.environ.get("PRAXIS_COOKIE_SECRET", "").strip()
if not secret:
secret = secrets.token_urlsafe(48)
logger.warning(
"PRAXIS_COOKIE_SECRET not set — generated an ephemeral random secret. "
"Sessions will NOT survive a server restart. This is dev-only; set "
"PRAXIS_COOKIE_SECRET (>=32 bytes) for pilot/production."
)
secure = _env_bool("PRAXIS_COOKIE_SECURE", True)
if not secure:
logger.warning(
"Cookie Secure flag disabled (PRAXIS_COOKIE_SECURE=false) — HTTP pilot "
"mode (R-AUTH-01). Do not use in production. NOTE (G-031): the primary "
"R-AUTH-01 mitigation is k-anon defense-in-depth (cohort dashboard reads "
"only k-anonymized aggregates → sniffed cookie leaks no PII); this flag "
"is the secondary mitigation."
)
return {
"secret_key": secret,
"session_cookie": "praxis_op",
"max_age": _COOKIE_MAX_AGE_S,
"https_only": secure,
"same_site": "strict",
"path": "/",
}
__all__ = ["get_session_middleware_kwargs"]
+56
View File
@@ -0,0 +1,56 @@
"""current_operator dependency (TASK-03-04, D-057).
Server-side auth enforcement: every `/api/operator/*` protected route uses
`Depends(current_operator)`. The dependency NEVER trusts the client (D-057)
— it reads the signed-cookie session, fetches the operator from Postgres,
and 401s on any gap (missing/invalid/expired cookie, unknown id, inactive
operator). The cookie is the authz *token*; the Postgres lookup is the
authz *decision*.
"""
from __future__ import annotations
from fastapi import HTTPException, Request, status
from server.auth.models import Operator
async def current_operator(request: Request) -> Operator:
"""Resolve the authenticated operator from the signed-cookie session.
Raises 401 on: missing session, missing operator_id, no Postgres store
(503 actually — operator tier unavailable), unknown operator id, or an
inactive operator (session is cleared in the latter case so the client
cookie is invalidated).
"""
pg_store = getattr(request.app.state, "pg_store", None)
if pg_store is None:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="operator tier unavailable (no Postgres)",
)
session = request.session
op_id = session.get("operator_id") if session else None
if not op_id:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="not authenticated",
)
row = await pg_store.get_operator_by_id(op_id)
if row is None or not row.get("is_active"):
# Inactive/unknown → clear the session so the cookie is invalidated.
if session:
session.clear()
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="not authenticated",
)
return Operator(
id=str(row["id"]),
username=row["username"],
display_name=row.get("display_name"),
role=row.get("role", "operator"),
)
__all__ = ["current_operator"]
+18
View File
@@ -0,0 +1,18 @@
"""Auth data models (TASK-03-04)."""
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class Operator:
"""The authenticated operator injected into protected routes (D-057)."""
id: str
username: str
display_name: str | None
role: str
__all__ = ["Operator"]
+44
View File
@@ -0,0 +1,44 @@
"""Argon2id password hashing (TASK-03-01, D-041, REQ-NFR-AUTH-01).
Uses argon2-cffi PasswordHasher with defaults that exceed OWASP minimums
(time_cost=3, memory_cost=64MiB, parallelism=4 — RESEARCH-v0.4 §2.1).
Single operator, low-frequency logins → hashing latency < 1s is
acceptable (R-AUTH-02).
"""
from __future__ import annotations
from argon2 import PasswordHasher
from argon2.exceptions import VerifyMismatchError
_ph = PasswordHasher()
def hash_password(plain: str) -> str:
"""Hash a plaintext password with argon2id. Returns the encoded hash string."""
return _ph.hash(plain)
def verify_password(stored_hash: str, plain: str) -> bool:
"""Verify a plaintext password against a stored argon2id hash.
Returns False on mismatch (no exception) so the login flow can apply a
uniform 401 + rate-limit-increment path on any auth failure.
"""
try:
_ph.verify(stored_hash, plain)
return True
except VerifyMismatchError:
return False
except Exception:
return False
def needs_rehash(stored_hash: str) -> bool:
"""True if the stored hash was produced with weaker params than the
current PasswordHasher defaults. The login flow rehashes + updates the
store when this returns True (param upgrades without forcing a reset)."""
return _ph.check_needs_rehash(stored_hash)
__all__ = ["hash_password", "verify_password", "needs_rehash"]
+34
View File
@@ -0,0 +1,34 @@
"""Login rate limiting (TASK-03-03, D-041).
slowapi Limiter with an in-memory backend (single-instance — D-041).
5 login attempts per minute per client IP. On exceed → 429 + Retry-After.
R-AUTH-03 (in-memory counter lost on restart) is an accepted pilot risk
(RESEARCH-v0.4 §2.5) — a restart at most resets the counter, which slightly
widens the brute-force window but does not enable it (argon2id + 5/min is
still the binding control). A hand-rolled counter is the documented
fallback if slowapi is ever removed.
"""
from __future__ import annotations
from slowapi import Limiter
from slowapi.util import get_remote_address
limiter = Limiter(key_func=get_remote_address, storage_uri="memory://")
def reset_login_rate_limit() -> None:
"""Clear the in-memory rate-limit counters (test helper + restart-safe)."""
try:
limiter.reset()
except Exception:
pass
def rate_limit_login():
"""Decorator factory: 5 login attempts per minute per IP (D-041)."""
return limiter.limit("5/minute")
__all__ = ["limiter", "rate_limit_login", "reset_login_rate_limit"]
+118
View File
@@ -0,0 +1,118 @@
"""Auth route handlers — login, logout, me (TASK-03-05, D-041, D-056, D-057).
APIRouter(prefix="/api/operator") with:
POST /login — rate-limited 5/min (TASK-03-03), NOT auth-gated.
POST /logout — auth-gated (Depends(current_operator)).
GET /me — auth-gated (React route guard — D-057).
Stateless cookies (D-056): logout clears the server-side session; the
client also clears its cookie. No sessions table.
"""
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException, Request, status
from pydantic import BaseModel
from server.auth.dependencies import current_operator
from server.auth.models import Operator
from server.auth.passwords import hash_password, needs_rehash, verify_password
from server.auth.rate_limit import rate_limit_login
router = APIRouter(prefix="/api/operator", tags=["operator-auth"])
class LoginBody(BaseModel):
username: str
password: str
class OperatorOut(BaseModel):
id: str
username: str
display_name: str | None
role: str = "operator"
class LoginResponse(BaseModel):
operator: OperatorOut
class MeResponse(BaseModel):
operator: OperatorOut
class OkResponse(BaseModel):
ok: bool = True
def _operator_out(op: Operator) -> OperatorOut:
return OperatorOut(
id=op.id,
username=op.username,
display_name=op.display_name,
role=op.role,
)
@router.post("/login", response_model=LoginResponse)
@rate_limit_login()
async def login(body: LoginBody, request: Request) -> LoginResponse:
"""Rate-limited login (5/min per IP — D-041).
On success: sets `request.session["operator_id"]` (signed cookie via
SessionMiddleware) + updates last_login_at. On needs_rehash → rehash +
update the store. On failure → 401 (no cookie set).
"""
pg_store = getattr(request.app.state, "pg_store", None)
if pg_store is None:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="operator tier unavailable (no Postgres)",
)
row = await pg_store.get_operator_by_username(body.username)
if row is None or not row.get("is_active"):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="invalid credentials",
)
if not verify_password(row["password_hash"], body.password):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="invalid credentials",
)
op_id = str(row["id"])
request.session["operator_id"] = op_id
await pg_store.update_last_login(op_id)
if needs_rehash(row["password_hash"]):
new_hash = hash_password(body.password)
async with pg_store.pool.acquire() as conn:
await conn.execute(
"UPDATE operators SET password_hash = $1 WHERE id = $2",
new_hash, op_id,
)
return LoginResponse(
operator=OperatorOut(
id=op_id,
username=row["username"],
display_name=row.get("display_name"),
role=row.get("role", "operator"),
)
)
@router.post("/logout", response_model=OkResponse)
async def logout(request: Request, op: Operator = Depends(current_operator)) -> OkResponse:
# Stateless (D-056): clearing the server session invalidates the signed
# cookie's payload; the client also clears its cookie.
request.session.clear()
return OkResponse(ok=True)
@router.get("/me", response_model=MeResponse)
async def me(op: Operator = Depends(current_operator)) -> MeResponse:
"""React route guard endpoint (D-057). 200 → render; 401 → redirect."""
return MeResponse(operator=_operator_out(op))
__all__ = ["router"]