feat(m2): auth, JWT, invitations, bootstrap, RTOps SPA pages
Crypto + tokens
- app/core/security.py: Argon2id PasswordHasher (time_cost=2, memory_cost=
64 MiB, parallelism=2) + opaque-token SHA-256 helpers (raw token shown
once, only the hash lives in the DB).
- app/core/jwt_tokens.py: HS256, claims iss/sub/type/jti/iat/exp. Access
1h, refresh 30d.
Services
- services/auth.py: login, refresh with token rotation + reuse-detection
chain revoke, logout (idempotent), change_password (forces logout-all).
- services/invitations.py: create, preview, accept, revoke. Default 7d TTL.
- services/bootstrap.py: seeds the 3 system groups (admin/redteam/blueteam),
consumes the install token, attaches the first user to admin.
- core/install_token.py: mints, persists in settings, marks consumed,
regenerate hook for /diag/reset.
API
- POST /setup (consume install token, create 1st admin) + GET /setup
(status).
- POST /auth/{login,refresh,logout,change-password} + GET /auth/me.
- POST /invitations + GET /invitations + GET /invitations/preview/<token> +
POST /invitations/accept/<token> + POST /invitations/<id>/revoke.
- POST /diag/reset: test-only kill switch (truncate auth tables + mint
fresh install token). Allowed in dev too (with WARNING log) so the e2e
suite can run against a make-up stack; production locked out.
Middleware
- @require_auth populates g.current_user (snapshot dataclass, session
closed before request handler runs).
- @require_perm(*codes): atomic perm union check; admin group bypasses.
Perm catalogue lands in M3, scaffolding here.
- flask-limiter: 10/min/IP on /auth/login & /auth/refresh, 5/min on
/auth/change-password & /setup, 10–20/min on invitation endpoints.
Disabled in APP_ENV=test.
CLI
- flask --app app.cli metamorph print-install-token [--force]
- flask --app app.cli metamorph seed-mitre (M4 placeholder)
Refresh cookie metamorph_refresh: HttpOnly + Secure (localhost is a secure
context for modern browsers) + SameSite=Strict + Path=/api/v1/auth/.
Email validation: app.api._validation.Email permissive RFC-shape regex so
internal TLDs (.local/.corp/.test) are accepted — pydantic.EmailStr's
deliverability check is too strict for red-team labs.
Frontend
- lib/{api,auth}.ts: access token in module memory, refresh cookie,
automatic 401-retry via /auth/refresh, useAuth() hook.
- components/{Layout,RequireAuth}.tsx + ui/{TextField,Alert}.tsx.
- pages/{Login,Setup,Register,Profile}.
Testing
- tests/test_auth_flow.py: 15 integration tests (24 backend total).
- e2e/tests/m2-auth.spec.ts: 8 Playwright tests (20 e2e total).
- tasks/testing-m2.md.
DoD: make test-api → 24 passed, make e2e → 20 passed; spec-reviewer pass
applied (Secure unconditional, refresh limit 10/min/IP).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 06:16:48 +02:00
|
|
|
"""Authentication endpoints.
|
|
|
|
|
|
|
|
|
|
`POST /auth/login` returns the access token in the body and sets the refresh
|
|
|
|
|
token in an HTTPOnly cookie scoped to `/api/v1/auth/`. The cookie is
|
|
|
|
|
`Secure; SameSite=Strict` and only the matching paths can read it.
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
import logging
|
|
|
|
|
|
|
|
|
|
from flask import Blueprint, g, jsonify, make_response, request
|
|
|
|
|
from pydantic import BaseModel, Field, ValidationError
|
|
|
|
|
|
|
|
|
|
from app.api._validation import Email
|
|
|
|
|
from app.core.auth_decorators import require_auth
|
|
|
|
|
from app.core.config import settings
|
|
|
|
|
from app.core.rate_limit import limiter
|
|
|
|
|
from app.services import auth as auth_svc
|
|
|
|
|
|
|
|
|
|
bp = Blueprint("auth", __name__, url_prefix="/auth")
|
|
|
|
|
log = logging.getLogger("metamorph.api.auth")
|
|
|
|
|
|
|
|
|
|
REFRESH_COOKIE_NAME = "metamorph_refresh"
|
|
|
|
|
REFRESH_COOKIE_PATH = "/api/v1/auth/"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class LoginPayload(BaseModel):
|
|
|
|
|
email: Email
|
|
|
|
|
password: str = Field(min_length=1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ChangePasswordPayload(BaseModel):
|
|
|
|
|
current_password: str = Field(min_length=1)
|
|
|
|
|
new_password: str = Field(min_length=8)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _set_refresh_cookie(resp, token: str, expires_at) -> None:
|
|
|
|
|
resp.set_cookie(
|
|
|
|
|
REFRESH_COOKIE_NAME,
|
|
|
|
|
token,
|
|
|
|
|
expires=expires_at,
|
|
|
|
|
httponly=True,
|
|
|
|
|
secure=True, # spec §M2; localhost is a secure context for modern browsers
|
|
|
|
|
samesite="Strict",
|
|
|
|
|
path=REFRESH_COOKIE_PATH,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _clear_refresh_cookie(resp) -> None:
|
|
|
|
|
resp.set_cookie(
|
|
|
|
|
REFRESH_COOKIE_NAME,
|
|
|
|
|
"",
|
|
|
|
|
expires=0,
|
|
|
|
|
httponly=True,
|
|
|
|
|
secure=True, # spec §M2; localhost is a secure context for modern browsers
|
|
|
|
|
samesite="Strict",
|
|
|
|
|
path=REFRESH_COOKIE_PATH,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _read_refresh_cookie() -> str | None:
|
|
|
|
|
return request.cookies.get(REFRESH_COOKIE_NAME)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _serialize_pair(pair: auth_svc.TokenPair) -> dict:
|
|
|
|
|
return {
|
|
|
|
|
"access_token": pair.access_token,
|
|
|
|
|
"token_type": "Bearer",
|
|
|
|
|
"user_id": str(pair.user_id),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@bp.post("/login")
|
|
|
|
|
@limiter.limit("10 per minute")
|
|
|
|
|
def login():
|
|
|
|
|
try:
|
|
|
|
|
payload = LoginPayload.model_validate(request.get_json(silent=True) or {})
|
|
|
|
|
except ValidationError as e:
|
feat(m7): blue review fields + spec amendment + reviewer follow-ups
User feedback after the M7 ship: blue team's Excel workflow had 5 extra
fields we didn't capture. Per-test page also doesn't match their
workflow — they need a tabular view, one table per scenario.
Spec
- tasks/spec.md amended (`revised: 2026-05-15`): §4 in-scope, §F6, §8
model bullet. §F6 now pins the column matrix, single-row-edit
semantics, Esc-cancel, blur-confirm, and reconciles detection_level
as a pill inside the Commentaires cell (no 8th column).
- tasks/todo.md M7 section grew an "Amendement 2026-05-15" sub-block
tracking backend ☑ and frontend ☐.
Backend
- Migration c2a8f4b1d6e9: 5 nullable columns on mission_tests
(blue_log_source, blue_siem_logs, blue_incident_at,
blue_incident_number, blue_incident_recipient_email).
- _BLUE_FIELDS extended; update_mission_test_fields propagates each
field; MissionTestDetailView + MissionTestView (the nested view in
GET /missions/{id}) surface every annotation field, plus
last_actor_*, updated_at, detection_level_key — O(1) batch lookup
for detection-level keys and last-actor users keeps it scalable.
- UpdateMissionTestPayload accepts each field with length caps
(120/200_000/120/255).
Reviewer follow-ups applied
- blue_incident_at + executed_at now reject naïve datetimes
(_ensure_aware_datetime) — Postgres would otherwise interpret
them in the session TZ, defeating the M7 verbatim-time contract.
- blue_incident_recipient_email goes through a permissive RFC-shape
regex (_validate_email_shape) so internal/lab TLDs like .local
/ .corp / .test pass — Pydantic EmailStr is too strict (lessons.md
M2 trap).
- Project-wide: switched `e.errors()` to
`e.errors(include_context=False, include_url=False)` because the
AfterValidator-raised ValueError lands in ctx and Flask can't
serialize it.
Tests
- 5 new pytest cases: blue user writes the 5 new fields, red user is
individually 403'd on each, round-trip via GET, naïve datetime
rejected, email shape validated (.local accepted, bad shape 400).
- 138 pytest green.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 14:45:18 +02:00
|
|
|
return jsonify({"error": "invalid_request", "details": e.errors(include_context=False, include_url=False)}), 400
|
feat(m2): auth, JWT, invitations, bootstrap, RTOps SPA pages
Crypto + tokens
- app/core/security.py: Argon2id PasswordHasher (time_cost=2, memory_cost=
64 MiB, parallelism=2) + opaque-token SHA-256 helpers (raw token shown
once, only the hash lives in the DB).
- app/core/jwt_tokens.py: HS256, claims iss/sub/type/jti/iat/exp. Access
1h, refresh 30d.
Services
- services/auth.py: login, refresh with token rotation + reuse-detection
chain revoke, logout (idempotent), change_password (forces logout-all).
- services/invitations.py: create, preview, accept, revoke. Default 7d TTL.
- services/bootstrap.py: seeds the 3 system groups (admin/redteam/blueteam),
consumes the install token, attaches the first user to admin.
- core/install_token.py: mints, persists in settings, marks consumed,
regenerate hook for /diag/reset.
API
- POST /setup (consume install token, create 1st admin) + GET /setup
(status).
- POST /auth/{login,refresh,logout,change-password} + GET /auth/me.
- POST /invitations + GET /invitations + GET /invitations/preview/<token> +
POST /invitations/accept/<token> + POST /invitations/<id>/revoke.
- POST /diag/reset: test-only kill switch (truncate auth tables + mint
fresh install token). Allowed in dev too (with WARNING log) so the e2e
suite can run against a make-up stack; production locked out.
Middleware
- @require_auth populates g.current_user (snapshot dataclass, session
closed before request handler runs).
- @require_perm(*codes): atomic perm union check; admin group bypasses.
Perm catalogue lands in M3, scaffolding here.
- flask-limiter: 10/min/IP on /auth/login & /auth/refresh, 5/min on
/auth/change-password & /setup, 10–20/min on invitation endpoints.
Disabled in APP_ENV=test.
CLI
- flask --app app.cli metamorph print-install-token [--force]
- flask --app app.cli metamorph seed-mitre (M4 placeholder)
Refresh cookie metamorph_refresh: HttpOnly + Secure (localhost is a secure
context for modern browsers) + SameSite=Strict + Path=/api/v1/auth/.
Email validation: app.api._validation.Email permissive RFC-shape regex so
internal TLDs (.local/.corp/.test) are accepted — pydantic.EmailStr's
deliverability check is too strict for red-team labs.
Frontend
- lib/{api,auth}.ts: access token in module memory, refresh cookie,
automatic 401-retry via /auth/refresh, useAuth() hook.
- components/{Layout,RequireAuth}.tsx + ui/{TextField,Alert}.tsx.
- pages/{Login,Setup,Register,Profile}.
Testing
- tests/test_auth_flow.py: 15 integration tests (24 backend total).
- e2e/tests/m2-auth.spec.ts: 8 Playwright tests (20 e2e total).
- tasks/testing-m2.md.
DoD: make test-api → 24 passed, make e2e → 20 passed; spec-reviewer pass
applied (Secure unconditional, refresh limit 10/min/IP).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 06:16:48 +02:00
|
|
|
try:
|
|
|
|
|
pair = auth_svc.login(payload.email, payload.password)
|
|
|
|
|
except auth_svc.InvalidCredentials:
|
|
|
|
|
return jsonify({"error": "invalid_credentials"}), 401
|
|
|
|
|
|
|
|
|
|
resp = make_response(jsonify(_serialize_pair(pair)))
|
|
|
|
|
_set_refresh_cookie(resp, pair.refresh_token, pair.refresh_expires_at)
|
|
|
|
|
return resp
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@bp.post("/refresh")
|
|
|
|
|
@limiter.limit("10 per minute")
|
|
|
|
|
def refresh_endpoint():
|
|
|
|
|
raw = _read_refresh_cookie()
|
|
|
|
|
if not raw:
|
|
|
|
|
return jsonify({"error": "no_refresh_cookie"}), 401
|
|
|
|
|
try:
|
|
|
|
|
pair = auth_svc.refresh(raw)
|
|
|
|
|
except auth_svc.TokenRevoked:
|
|
|
|
|
resp = make_response(jsonify({"error": "token_revoked"}), 401)
|
|
|
|
|
_clear_refresh_cookie(resp)
|
|
|
|
|
return resp
|
|
|
|
|
except auth_svc.InvalidCredentials:
|
|
|
|
|
resp = make_response(jsonify({"error": "invalid_refresh"}), 401)
|
|
|
|
|
_clear_refresh_cookie(resp)
|
|
|
|
|
return resp
|
|
|
|
|
|
|
|
|
|
resp = make_response(jsonify(_serialize_pair(pair)))
|
|
|
|
|
_set_refresh_cookie(resp, pair.refresh_token, pair.refresh_expires_at)
|
|
|
|
|
return resp
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@bp.post("/logout")
|
|
|
|
|
def logout():
|
|
|
|
|
raw = _read_refresh_cookie()
|
|
|
|
|
if raw:
|
|
|
|
|
auth_svc.logout(raw)
|
|
|
|
|
resp = make_response(jsonify({"ok": True}))
|
|
|
|
|
_clear_refresh_cookie(resp)
|
|
|
|
|
return resp
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@bp.get("/me")
|
|
|
|
|
@require_auth
|
|
|
|
|
def me():
|
|
|
|
|
u = g.current_user
|
|
|
|
|
return jsonify(
|
|
|
|
|
{
|
|
|
|
|
"id": str(u.id),
|
|
|
|
|
"email": u.email,
|
|
|
|
|
"display_name": u.display_name,
|
|
|
|
|
"locale": u.locale,
|
|
|
|
|
"is_admin": u.is_admin,
|
|
|
|
|
"groups": sorted(u.group_names),
|
|
|
|
|
"permissions": sorted(u.permissions),
|
|
|
|
|
}
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@bp.post("/change-password")
|
|
|
|
|
@require_auth
|
|
|
|
|
@limiter.limit("5 per minute")
|
|
|
|
|
def change_password():
|
|
|
|
|
try:
|
|
|
|
|
payload = ChangePasswordPayload.model_validate(request.get_json(silent=True) or {})
|
|
|
|
|
except ValidationError as e:
|
feat(m7): blue review fields + spec amendment + reviewer follow-ups
User feedback after the M7 ship: blue team's Excel workflow had 5 extra
fields we didn't capture. Per-test page also doesn't match their
workflow — they need a tabular view, one table per scenario.
Spec
- tasks/spec.md amended (`revised: 2026-05-15`): §4 in-scope, §F6, §8
model bullet. §F6 now pins the column matrix, single-row-edit
semantics, Esc-cancel, blur-confirm, and reconciles detection_level
as a pill inside the Commentaires cell (no 8th column).
- tasks/todo.md M7 section grew an "Amendement 2026-05-15" sub-block
tracking backend ☑ and frontend ☐.
Backend
- Migration c2a8f4b1d6e9: 5 nullable columns on mission_tests
(blue_log_source, blue_siem_logs, blue_incident_at,
blue_incident_number, blue_incident_recipient_email).
- _BLUE_FIELDS extended; update_mission_test_fields propagates each
field; MissionTestDetailView + MissionTestView (the nested view in
GET /missions/{id}) surface every annotation field, plus
last_actor_*, updated_at, detection_level_key — O(1) batch lookup
for detection-level keys and last-actor users keeps it scalable.
- UpdateMissionTestPayload accepts each field with length caps
(120/200_000/120/255).
Reviewer follow-ups applied
- blue_incident_at + executed_at now reject naïve datetimes
(_ensure_aware_datetime) — Postgres would otherwise interpret
them in the session TZ, defeating the M7 verbatim-time contract.
- blue_incident_recipient_email goes through a permissive RFC-shape
regex (_validate_email_shape) so internal/lab TLDs like .local
/ .corp / .test pass — Pydantic EmailStr is too strict (lessons.md
M2 trap).
- Project-wide: switched `e.errors()` to
`e.errors(include_context=False, include_url=False)` because the
AfterValidator-raised ValueError lands in ctx and Flask can't
serialize it.
Tests
- 5 new pytest cases: blue user writes the 5 new fields, red user is
individually 403'd on each, round-trip via GET, naïve datetime
rejected, email shape validated (.local accepted, bad shape 400).
- 138 pytest green.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 14:45:18 +02:00
|
|
|
return jsonify({"error": "invalid_request", "details": e.errors(include_context=False, include_url=False)}), 400
|
feat(m2): auth, JWT, invitations, bootstrap, RTOps SPA pages
Crypto + tokens
- app/core/security.py: Argon2id PasswordHasher (time_cost=2, memory_cost=
64 MiB, parallelism=2) + opaque-token SHA-256 helpers (raw token shown
once, only the hash lives in the DB).
- app/core/jwt_tokens.py: HS256, claims iss/sub/type/jti/iat/exp. Access
1h, refresh 30d.
Services
- services/auth.py: login, refresh with token rotation + reuse-detection
chain revoke, logout (idempotent), change_password (forces logout-all).
- services/invitations.py: create, preview, accept, revoke. Default 7d TTL.
- services/bootstrap.py: seeds the 3 system groups (admin/redteam/blueteam),
consumes the install token, attaches the first user to admin.
- core/install_token.py: mints, persists in settings, marks consumed,
regenerate hook for /diag/reset.
API
- POST /setup (consume install token, create 1st admin) + GET /setup
(status).
- POST /auth/{login,refresh,logout,change-password} + GET /auth/me.
- POST /invitations + GET /invitations + GET /invitations/preview/<token> +
POST /invitations/accept/<token> + POST /invitations/<id>/revoke.
- POST /diag/reset: test-only kill switch (truncate auth tables + mint
fresh install token). Allowed in dev too (with WARNING log) so the e2e
suite can run against a make-up stack; production locked out.
Middleware
- @require_auth populates g.current_user (snapshot dataclass, session
closed before request handler runs).
- @require_perm(*codes): atomic perm union check; admin group bypasses.
Perm catalogue lands in M3, scaffolding here.
- flask-limiter: 10/min/IP on /auth/login & /auth/refresh, 5/min on
/auth/change-password & /setup, 10–20/min on invitation endpoints.
Disabled in APP_ENV=test.
CLI
- flask --app app.cli metamorph print-install-token [--force]
- flask --app app.cli metamorph seed-mitre (M4 placeholder)
Refresh cookie metamorph_refresh: HttpOnly + Secure (localhost is a secure
context for modern browsers) + SameSite=Strict + Path=/api/v1/auth/.
Email validation: app.api._validation.Email permissive RFC-shape regex so
internal TLDs (.local/.corp/.test) are accepted — pydantic.EmailStr's
deliverability check is too strict for red-team labs.
Frontend
- lib/{api,auth}.ts: access token in module memory, refresh cookie,
automatic 401-retry via /auth/refresh, useAuth() hook.
- components/{Layout,RequireAuth}.tsx + ui/{TextField,Alert}.tsx.
- pages/{Login,Setup,Register,Profile}.
Testing
- tests/test_auth_flow.py: 15 integration tests (24 backend total).
- e2e/tests/m2-auth.spec.ts: 8 Playwright tests (20 e2e total).
- tasks/testing-m2.md.
DoD: make test-api → 24 passed, make e2e → 20 passed; spec-reviewer pass
applied (Secure unconditional, refresh limit 10/min/IP).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 06:16:48 +02:00
|
|
|
try:
|
|
|
|
|
auth_svc.change_password(g.current_user.id, payload.current_password, payload.new_password)
|
|
|
|
|
except auth_svc.InvalidCredentials:
|
|
|
|
|
return jsonify({"error": "current_password_incorrect"}), 400
|
|
|
|
|
except ValueError as e:
|
|
|
|
|
return jsonify({"error": "weak_password", "message": str(e)}), 400
|
|
|
|
|
|
|
|
|
|
resp = make_response(jsonify({"ok": True}))
|
|
|
|
|
_clear_refresh_cookie(resp)
|
|
|
|
|
return resp
|