Files
praxis/server/auth/cookies.py
T
Praxis CI e39521d51d feat(P01): SLICE-03 operator auth — argon2id + signed cookies + rate limit
- TASK-03-01 server/auth/passwords.py: argon2id via argon2-cffi
  PasswordHasher (t=3, m=64MiB, p=4 — exceeds OWASP). hash/verify/
  needs_rehash; verify returns False on mismatch (uniform 401 path).
- TASK-03-02 server/auth/cookies.py: get_session_middleware_kwargs()
  → Starlette SessionMiddleware (itsdangerous HMAC-SHA256, D-056).
  Cookie praxis_op, httpOnly, SameSite=strict, max_age=28800 (8h).
  PRAXIS_COOKIE_SECURE default true; false logs WARNING (R-AUTH-01).
  G-031 reframe documented: k-anon defense-in-depth is the PRIMARY
  mitigation (sniffed cookie → no PII); secure flag is SECONDARY.
- TASK-03-03 server/auth/rate_limit.py: slowapi Limiter (in-memory,
  D-041), 5/minute per IP on login. reset_login_rate_limit() helper.
- TASK-03-04 server/auth/dependencies.py + models.py: current_operator
  Depends — reads signed-cookie session, fetches operator from PgStore,
  401 on missing/invalid/inactive (clears session), 503 if no Postgres.
  Never trusts the client (D-057).
- TASK-03-05 server/auth/routes.py: APIRouter(prefix=/api/operator)
  with POST /login (rate-limited, rehash-on-login), POST /logout
  (auth-gated, clears session), GET /me (auth-gated, React guard).
- TASK-03-06 tests/test_auth.py: 18 unit tests (mocked PgStore) —
  passwords, cookie config, rate limit, 401/503 cases, login/logout/me,
  rehash-on-login.
- pyproject.toml: added itsdangerous>=2.1 (SessionMiddleware dep).

---ci---
project: praxis
phase: 1
milestone: v0.4
status: execute
persona: security-engineer
task: 03-01,03-02,03-03,03-04,03-05,03-06
requirements:
  covered: [REQ-AUTH-01, REQ-NFR-AUTH-01]
  grill:
    - G-031 (R-AUTH-01 reframe: k-anon primary, secure flag secondary)
---/ci---
2026-08-04 00:52:16 +00:00

69 lines
2.5 KiB
Python

"""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,
"httponly": True,
"samesite": "strict",
"secure": secure,
"path": "/",
}
__all__ = ["get_session_middleware_kwargs"]