Files
taylanbakircioglu bd6a31cb0d feat: v1.6.0 — Multi-Factor Authentication (Issue #18)
Adds opt-in TOTP-based Multi-Factor Authentication that is fully
backwards compatible with existing logins. Operators choose to enable
MFA per account; nothing changes for users who do not opt in.

Highlights
==========

* RFC 6238 TOTP (6 digits, 30s period, SHA1) with ±30s skew tolerance,
  compatible with Microsoft / Google Authenticator, Authy, Duo, 1Password.
* Per-step replay protection (`mfa_last_used_totp_step`) so a captured
  code cannot be reused inside the same window.
* Fernet-encrypted TOTP secrets at rest, key resolution via
  `MFA_ENCRYPTION_KEY` env (HKDF-derived from `SECRET_KEY` as fallback).
* 10 single-use, bcrypt-hashed backup codes per user, formatted
  `XXXX-YYYY` from a confusion-free alphabet (no 0/O/1/I/L).
* Two-step login flow: `POST /api/auth/login` returns `mfa_required`
  + `mfa_token`, then `POST /api/auth/login/mfa-verify` accepts a TOTP
  code OR a backup code. JWT is minted only after MFA succeeds.
* Self-service: users enable / disable MFA from their own row in the
  Users page; admins reset (single user or bulk) but never enable on
  behalf of someone else (matches AWS IAM / GitHub / Google Workspace).
* Bulk emergency reset CLI: `scripts/admin-mfa-reset-all.sh`.

Security hardening
==================

* Atomic transactions with `SELECT … FOR UPDATE` on `mfa_pending_logins`
  and `users` rows so concurrent verify / enroll calls cannot race.
* `/api/mfa/enroll/start` refuses re-enrollment when MFA is already on
  (prevents silent secret rotation via a stolen JWT).
* Pydantic `ValidationError` messages are sanitized before reaching the
  audit log so request bodies (TOTP / backup codes in flight) never
  appear in plaintext.
* Slowapi rate limits are per-USER, not per-IP, with a trusted-proxy
  XFF strategy so a single ingress address cannot exhaust the bucket
  for thousands of operators (`MFA_TRUSTED_PROXY_CIDRS`,
  `MFA_RATE_LIMIT_*` env-overridable).
* Login query now scopes to `is_active = TRUE` so a soft-deleted row
  with the same username can no longer occlude the active user
  (also closes a small account-enumeration side channel).

Database
========

Additive migrations (idempotent `ADD COLUMN IF NOT EXISTS`,
`CREATE TABLE IF NOT EXISTS`):

  - users: mfa_enabled, mfa_method, mfa_secret_encrypted,
    mfa_enrolled_at, mfa_last_used_at, mfa_last_used_totp_step
  - mfa_backup_codes (user_id ON DELETE CASCADE)
  - mfa_pending_logins (user_id ON DELETE CASCADE, challenge_token,
    attempts, expires_at)
  - mfa_pending_enrollments (user_id ON DELETE CASCADE)

Frontend
========

* Login page becomes a 3-phase state machine
  (credentials → MFA → submitting); legacy single-step login is
  preserved for users who haven't enrolled.
* New MFAEnrollModal (3-step wizard: QR + secret → verify → backup
  codes) using `qrcode.react`.
* Users page shows MFA column + per-row enable/disable/reset actions.
  Admins viewing other users with MFA off see a non-actionable info
  icon explaining that only the user themselves can enable MFA.

Deployment
==========

* `MFA_ENCRYPTION_KEY` is added to `k8s/manifests/03-secrets.yaml` as
  a placeholder; `SECRET_KEY` is also placeholder-ized so both are
  injected by the existing pipeline pattern (sed-replace + apply).
* No new build-time env vars are required for the frontend. The SPA
  uses `window.location.host` for `/api/*` and is routed by the
  existing nginx ingress configuration.
* `frontend/.dockerignore` ensures host `.env*` files cannot bleed
  into the production bundle.

Tests
=====

* New unit suites:
  - `test_mfa_service.py` (TOTP, encryption, backup codes)
  - `test_mfa_backwards_compat.py` (regression — non-MFA flow unchanged)
  - `test_mfa_rate_limits.py` (env override + dataclass immutability)
  - `test_mfa_rate_limit_key.py` (JWT key, trusted-proxy XFF, fallbacks)
* All existing 1000+ unit tests continue to pass.

Documentation
=============

* README MFA section (overview, day-to-day operations, emergency
  reset CLI, env variables, rate-limit tuning).
* `scripts/README.md` documents the bulk reset script.

Issue: #18
2026-05-19 04:35:16 +03:00

77 lines
2.5 KiB
Bash
Executable File

#!/usr/bin/env bash
# scripts/admin-mfa-reset-all.sh
# Issue #18 — v1.6.0 — Emergency: disable MFA for ALL users in one call.
#
# This is a break-glass tool. It calls POST /api/mfa/admin-reset-all on the
# backend with a strict, double-confirmed body and writes the action into the
# server's audit log (action=mfa.disabled.admin_bulk_reset). All users will be
# able to log in with username/password alone afterwards and must re-enroll if
# they want MFA again.
#
# Usage:
# ./scripts/admin-mfa-reset-all.sh
# API_URL=https://hap.example.com ADMIN_TOKEN=ey... ./scripts/admin-mfa-reset-all.sh
#
# Required: a JWT bearer token belonging to a user whose `users.is_admin = TRUE`.
set -euo pipefail
API_URL="${API_URL:-http://localhost:8000}"
ADMIN_TOKEN="${ADMIN_TOKEN:-}"
if [ -z "$ADMIN_TOKEN" ]; then
read -rsp "Admin Bearer token (user with is_admin=TRUE): " ADMIN_TOKEN
echo
fi
if [ -z "$ADMIN_TOKEN" ]; then
echo "ERROR: no admin token provided." >&2
exit 1
fi
cat <<'WARN'
========================================================================
WARNING — IRREVERSIBLE BULK ACTION
========================================================================
This will:
* set mfa_enabled = FALSE for every user
* delete every backup code
* invalidate all pending MFA login challenges and enrollments
* write a permanent entry to user_activity_logs
After this, all users can sign in with username/password only and must
re-enroll MFA from the Users page.
========================================================================
WARN
read -rp "Type 'yes' to proceed: " confirm1
if [ "$confirm1" != "yes" ]; then
echo "Aborted."
exit 1
fi
read -rp "Type 'RESET ALL MFA' (exact) to confirm: " confirm2
if [ "$confirm2" != "RESET ALL MFA" ]; then
echo "Aborted."
exit 1
fi
read -rp "Reason (logged in audit): " reason
if [ -z "$reason" ]; then
echo "Aborted: reason is required."
exit 1
fi
# Compose JSON safely (python3 for proper JSON escaping; reliably available
# everywhere the backend already runs).
payload=$(python3 -c "
import json, sys
print(json.dumps({'confirm': 'RESET ALL MFA', 'reason': sys.argv[1]}))
" "$reason")
echo "Calling $API_URL/api/mfa/admin-reset-all ..."
http_response=$(curl -fsS -X POST "$API_URL/api/mfa/admin-reset-all" \
-H "Authorization: Bearer $ADMIN_TOKEN" \
-H "Content-Type: application/json" \
-d "$payload")
echo "$http_response"
echo
echo "Done. Verify in user_activity_logs: action='mfa.disabled.admin_bulk_reset'."