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>
This commit is contained in:
146
backend/app/api/invitations.py
Normal file
146
backend/app/api/invitations.py
Normal file
@@ -0,0 +1,146 @@
|
||||
"""Invitation endpoints — admin issues, invitee previews + accepts."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
|
||||
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, require_perm
|
||||
from app.core.rate_limit import limiter
|
||||
from app.services import invitations as inv_svc
|
||||
|
||||
bp = Blueprint("invitations", __name__, url_prefix="/invitations")
|
||||
log = logging.getLogger("metamorph.api.invitations")
|
||||
|
||||
|
||||
class CreateInvitationPayload(BaseModel):
|
||||
email_hint: Email | None = None
|
||||
group_ids: list[uuid.UUID] = Field(default_factory=list)
|
||||
ttl_days: int | None = Field(default=None, ge=1, le=30)
|
||||
|
||||
|
||||
class AcceptInvitationPayload(BaseModel):
|
||||
email: Email
|
||||
password: str = Field(min_length=8)
|
||||
display_name: str | None = None
|
||||
|
||||
|
||||
@bp.post("")
|
||||
@require_auth
|
||||
@require_perm("invitation.create")
|
||||
def create():
|
||||
try:
|
||||
payload = CreateInvitationPayload.model_validate(request.get_json(silent=True) or {})
|
||||
except ValidationError as e:
|
||||
return jsonify({"error": "invalid_request", "details": e.errors()}), 400
|
||||
|
||||
from datetime import timedelta
|
||||
|
||||
ttl = (
|
||||
timedelta(days=payload.ttl_days)
|
||||
if payload.ttl_days is not None
|
||||
else inv_svc.INVITATION_TTL
|
||||
)
|
||||
result = inv_svc.create_invitation(
|
||||
created_by_user_id=g.current_user.id,
|
||||
email_hint=payload.email_hint,
|
||||
group_ids=payload.group_ids,
|
||||
ttl=ttl,
|
||||
)
|
||||
log.info(
|
||||
"metamorph.invitation.created",
|
||||
extra={
|
||||
"invitation_id": str(result.invitation_id),
|
||||
"by_user_id": str(g.current_user.id),
|
||||
"expires_at": result.expires_at.isoformat(),
|
||||
},
|
||||
)
|
||||
return make_response(
|
||||
jsonify(
|
||||
{
|
||||
"id": str(result.invitation_id),
|
||||
"token": result.raw_token, # shown ONCE
|
||||
"expires_at": result.expires_at.isoformat(),
|
||||
}
|
||||
),
|
||||
201,
|
||||
)
|
||||
|
||||
|
||||
@bp.get("")
|
||||
@require_auth
|
||||
@require_perm("invitation.read")
|
||||
def list_active():
|
||||
rows = inv_svc.list_active()
|
||||
return jsonify(
|
||||
[
|
||||
{
|
||||
"id": str(r.id),
|
||||
"email_hint": r.email_hint,
|
||||
"expires_at": r.expires_at.isoformat(),
|
||||
"groups": [g.name for g in r.pre_assigned_groups],
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
@bp.post("/<invitation_id>/revoke")
|
||||
@require_auth
|
||||
@require_perm("invitation.revoke")
|
||||
def revoke(invitation_id: str):
|
||||
try:
|
||||
iid = uuid.UUID(invitation_id)
|
||||
except ValueError:
|
||||
return jsonify({"error": "invalid_id"}), 400
|
||||
ok = inv_svc.revoke(iid)
|
||||
if not ok:
|
||||
return jsonify({"error": "not_revocable"}), 404
|
||||
return jsonify({"ok": True})
|
||||
|
||||
|
||||
@bp.get("/preview/<token>")
|
||||
@limiter.limit("20 per minute")
|
||||
def preview(token: str):
|
||||
p = inv_svc.preview(token)
|
||||
return jsonify(
|
||||
{
|
||||
"is_valid": p.is_valid,
|
||||
"reason": p.reason,
|
||||
"email_hint": p.email_hint,
|
||||
"expires_at": p.expires_at.isoformat(),
|
||||
"groups": p.groups,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@bp.post("/accept/<token>")
|
||||
@limiter.limit("10 per minute")
|
||||
def accept(token: str):
|
||||
try:
|
||||
payload = AcceptInvitationPayload.model_validate(request.get_json(silent=True) or {})
|
||||
except ValidationError as e:
|
||||
return jsonify({"error": "invalid_request", "details": e.errors()}), 400
|
||||
try:
|
||||
user_id = inv_svc.accept(
|
||||
token,
|
||||
email=payload.email,
|
||||
password=payload.password,
|
||||
display_name=payload.display_name,
|
||||
)
|
||||
except inv_svc.InvitationExpired:
|
||||
return jsonify({"error": "invitation_expired"}), 410
|
||||
except inv_svc.InvitationConsumed:
|
||||
return jsonify({"error": "invitation_consumed"}), 410
|
||||
except inv_svc.InvitationRevoked:
|
||||
return jsonify({"error": "invitation_revoked"}), 410
|
||||
except inv_svc.InvitationError as e:
|
||||
return jsonify({"error": "invitation_invalid", "message": str(e)}), 400
|
||||
except ValueError as e:
|
||||
return jsonify({"error": "invalid_request", "message": str(e)}), 400
|
||||
|
||||
return make_response(jsonify({"ok": True, "user_id": str(user_id)}), 201)
|
||||
Reference in New Issue
Block a user