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>
147 lines
4.3 KiB
Python
147 lines
4.3 KiB
Python
"""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(include_context=False, include_url=False)}), 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(include_context=False, include_url=False)}), 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)
|