feat: sprint 1 — auth + CRUD engagements
Ship the first feature end-to-end on the UI: users log in with JWT,
admins manage user accounts, and any authenticated user (per RBAC)
can create, list, view, edit, and delete engagements.
Backend (Flask + SQLAlchemy + SQLite, 63 pytest)
- User / Engagement models, Alembic 0001 initial schema
- argon2 password hashing, JWT bearer (60-min TTL), @login_required
and @role_required decorators
- 13 API endpoints under /api/*, including last-admin protection on
DELETE/PATCH user and JSON 404 on unknown /api/* paths
- `flask create-admin` CLI with duplicate / short-password handling
Frontend (React + Vite + Tailwind + TanStack Query, 20 vitest)
- Inter font bundled locally (no CDN), DESIGN.md tokens in Tailwind
- LoginPage / EngagementsList / EngagementForm / EngagementDetail /
UsersAdmin pages with role-aware UI
- Layout, ProtectedRoute, StatusBadge, FormField, LoadingState,
ErrorState, EmptyState, Toast + provider
- Axios client: Bearer interceptor, 401 → purge + /login + "Session
expirée" toast, 403 → "Accès refusé" toast (declarative <Navigate>
for already-authed users, Fragment-keyed admin user rows)
Deployment
- Single multistage Dockerfile (node:20-alpine → python:3.12-slim)
- docker/entrypoint.sh runs `flask db upgrade` before `flask run`
- Makefile: build/start/stop/restart/update/logs/create-admin/
update-mitre/test-{backend,frontend,e2e}/clean
- .env.example documenting MIMIC_JWT_SECRET / MIMIC_DB_PATH / MIMIC_PORT
- SQLite at /data/mimic.sqlite on named volume mimic-data
Acceptance suite (Playwright, 36 tests, all 27 ACs)
- e2e/ scaffold with playwright.config + auth/api fixtures
- One spec per user story (us1-bootstrap through us6-deployment)
- Portable via MIMIC_CONTAINER_CMD / MIMIC_BASE_URL (docker or podman)
Docs
- README.md with quick-start and architecture overview
- CHANGELOG.md updated with Sprint 1 deliverables
- pyrightconfig.json so the Python LSP sees backend/.venv and
resolves the `backend.app.*` absolute imports
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
6
backend/app/api/__init__.py
Normal file
6
backend/app/api/__init__.py
Normal file
@@ -0,0 +1,6 @@
|
||||
"""API blueprints."""
|
||||
from backend.app.api.auth import auth_bp
|
||||
from backend.app.api.engagements import engagements_bp
|
||||
from backend.app.api.users import users_bp
|
||||
|
||||
__all__ = ["auth_bp", "users_bp", "engagements_bp"]
|
||||
46
backend/app/api/auth.py
Normal file
46
backend/app/api/auth.py
Normal file
@@ -0,0 +1,46 @@
|
||||
"""Auth endpoints: login, logout, me."""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, g, jsonify, request
|
||||
|
||||
from backend.app.auth import encode_token, login_required, verify_password
|
||||
from backend.app.models import User
|
||||
from backend.app.serializers import serialize_user
|
||||
|
||||
auth_bp = Blueprint("auth", __name__, url_prefix="/api/auth")
|
||||
|
||||
|
||||
@auth_bp.post("/login")
|
||||
def login():
|
||||
data = request.get_json(silent=True) or {}
|
||||
username = (data.get("username") or "").strip()
|
||||
password = data.get("password") or ""
|
||||
|
||||
generic_error = (jsonify({"error": "Invalid credentials"}), 401)
|
||||
if not username or not password:
|
||||
return generic_error
|
||||
|
||||
user = User.query.filter_by(username=username).first()
|
||||
if user is None or not verify_password(user.password_hash, password):
|
||||
return generic_error
|
||||
|
||||
token = encode_token(user.id, user.role.value)
|
||||
return jsonify(
|
||||
{
|
||||
"access_token": token,
|
||||
"user": {"id": user.id, "username": user.username, "role": user.role.value},
|
||||
}
|
||||
), 200
|
||||
|
||||
|
||||
@auth_bp.post("/logout")
|
||||
@login_required
|
||||
def logout():
|
||||
# V1: stateless JWT — client discards the token. No server-side blacklist.
|
||||
return jsonify({"status": "ok"}), 200
|
||||
|
||||
|
||||
@auth_bp.get("/me")
|
||||
@login_required
|
||||
def me():
|
||||
return jsonify(serialize_user(g.current_user)), 200
|
||||
158
backend/app/api/engagements.py
Normal file
158
backend/app/api/engagements.py
Normal file
@@ -0,0 +1,158 @@
|
||||
"""Engagement CRUD endpoints."""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
|
||||
from flask import Blueprint, g, jsonify, request
|
||||
|
||||
from backend.app.auth import login_required, role_required
|
||||
from backend.app.extensions import db
|
||||
from backend.app.models import Engagement, EngagementStatus
|
||||
from backend.app.serializers import serialize_engagement
|
||||
|
||||
engagements_bp = Blueprint("engagements", __name__, url_prefix="/api/engagements")
|
||||
|
||||
|
||||
def _parse_date(value: object) -> date | None:
|
||||
if not isinstance(value, str):
|
||||
return None
|
||||
try:
|
||||
return date.fromisoformat(value)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _parse_status(value: object) -> EngagementStatus | None:
|
||||
if not isinstance(value, str):
|
||||
return None
|
||||
try:
|
||||
return EngagementStatus(value)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
@engagements_bp.get("")
|
||||
@login_required
|
||||
def list_engagements():
|
||||
items = Engagement.query.order_by(Engagement.id.asc()).all()
|
||||
return jsonify([serialize_engagement(e) for e in items]), 200
|
||||
|
||||
|
||||
@engagements_bp.post("")
|
||||
@role_required("admin", "redteam")
|
||||
def create_engagement():
|
||||
data = request.get_json(silent=True) or {}
|
||||
|
||||
name = (data.get("name") or "").strip()
|
||||
if not name:
|
||||
return jsonify({"error": "name is required"}), 400
|
||||
|
||||
start_raw = data.get("start_date")
|
||||
start_date = _parse_date(start_raw) if start_raw else None
|
||||
if start_date is None:
|
||||
return jsonify({"error": "start_date is required (YYYY-MM-DD)"}), 400
|
||||
|
||||
end_raw = data.get("end_date")
|
||||
end_date: date | None = None
|
||||
if end_raw:
|
||||
end_date = _parse_date(end_raw)
|
||||
if end_date is None:
|
||||
return jsonify({"error": "end_date must be YYYY-MM-DD"}), 400
|
||||
if end_date < start_date:
|
||||
return jsonify({"error": "end_date must be >= start_date"}), 400
|
||||
|
||||
status = EngagementStatus.PLANNED
|
||||
if "status" in data and data.get("status") is not None:
|
||||
parsed = _parse_status(data.get("status"))
|
||||
if parsed is None:
|
||||
return (
|
||||
jsonify({"error": "status must be one of: planned, active, closed"}),
|
||||
400,
|
||||
)
|
||||
status = parsed
|
||||
|
||||
engagement = Engagement(
|
||||
name=name,
|
||||
description=data.get("description"),
|
||||
start_date=start_date,
|
||||
end_date=end_date,
|
||||
status=status,
|
||||
created_by_id=g.current_user.id,
|
||||
)
|
||||
db.session.add(engagement)
|
||||
db.session.commit()
|
||||
return jsonify(serialize_engagement(engagement)), 201
|
||||
|
||||
|
||||
@engagements_bp.get("/<int:engagement_id>")
|
||||
@login_required
|
||||
def get_engagement(engagement_id: int):
|
||||
engagement = db.session.get(Engagement, engagement_id)
|
||||
if engagement is None:
|
||||
return jsonify({"error": "Engagement not found"}), 404
|
||||
return jsonify(serialize_engagement(engagement)), 200
|
||||
|
||||
|
||||
@engagements_bp.patch("/<int:engagement_id>")
|
||||
@role_required("admin", "redteam")
|
||||
def update_engagement(engagement_id: int):
|
||||
engagement = db.session.get(Engagement, engagement_id)
|
||||
if engagement is None:
|
||||
return jsonify({"error": "Engagement not found"}), 404
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
|
||||
if "name" in data:
|
||||
name = (data.get("name") or "").strip()
|
||||
if not name:
|
||||
return jsonify({"error": "name must not be empty"}), 400
|
||||
engagement.name = name
|
||||
|
||||
if "description" in data:
|
||||
engagement.description = data.get("description")
|
||||
|
||||
new_start = engagement.start_date
|
||||
if "start_date" in data:
|
||||
parsed = _parse_date(data.get("start_date"))
|
||||
if parsed is None:
|
||||
return jsonify({"error": "start_date must be YYYY-MM-DD"}), 400
|
||||
new_start = parsed
|
||||
|
||||
new_end = engagement.end_date
|
||||
if "end_date" in data:
|
||||
if data.get("end_date") in (None, ""):
|
||||
new_end = None
|
||||
else:
|
||||
parsed = _parse_date(data.get("end_date"))
|
||||
if parsed is None:
|
||||
return jsonify({"error": "end_date must be YYYY-MM-DD"}), 400
|
||||
new_end = parsed
|
||||
|
||||
if new_end is not None and new_end < new_start:
|
||||
return jsonify({"error": "end_date must be >= start_date"}), 400
|
||||
|
||||
engagement.start_date = new_start
|
||||
engagement.end_date = new_end
|
||||
|
||||
if "status" in data:
|
||||
parsed_status = _parse_status((data.get("status") or "").strip())
|
||||
if parsed_status is None:
|
||||
return (
|
||||
jsonify({"error": "status must be one of: planned, active, closed"}),
|
||||
400,
|
||||
)
|
||||
engagement.status = parsed_status
|
||||
|
||||
db.session.commit()
|
||||
return jsonify(serialize_engagement(engagement)), 200
|
||||
|
||||
|
||||
@engagements_bp.delete("/<int:engagement_id>")
|
||||
@role_required("admin", "redteam")
|
||||
def delete_engagement(engagement_id: int):
|
||||
engagement = db.session.get(Engagement, engagement_id)
|
||||
if engagement is None:
|
||||
return jsonify({"error": "Engagement not found"}), 404
|
||||
db.session.delete(engagement)
|
||||
db.session.commit()
|
||||
return "", 204
|
||||
106
backend/app/api/users.py
Normal file
106
backend/app/api/users.py
Normal file
@@ -0,0 +1,106 @@
|
||||
"""User management endpoints (admin only)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request
|
||||
|
||||
from backend.app.auth import hash_password, role_required
|
||||
from backend.app.extensions import db
|
||||
from backend.app.models import User, UserRole
|
||||
from backend.app.serializers import serialize_user
|
||||
|
||||
users_bp = Blueprint("users", __name__, url_prefix="/api/users")
|
||||
|
||||
|
||||
def _parse_role(value: object) -> UserRole | None:
|
||||
if not isinstance(value, str):
|
||||
return None
|
||||
try:
|
||||
return UserRole(value)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
@users_bp.get("")
|
||||
@role_required("admin")
|
||||
def list_users():
|
||||
users = User.query.order_by(User.id.asc()).all()
|
||||
return jsonify([serialize_user(u) for u in users]), 200
|
||||
|
||||
|
||||
@users_bp.post("")
|
||||
@role_required("admin")
|
||||
def create_user():
|
||||
data = request.get_json(silent=True) or {}
|
||||
username = (data.get("username") or "").strip()
|
||||
password = data.get("password") or ""
|
||||
role_raw = (data.get("role") or "").strip()
|
||||
|
||||
if not username:
|
||||
return jsonify({"error": "username is required"}), 400
|
||||
|
||||
min_len = current_app.config["MIN_PASSWORD_LENGTH"]
|
||||
if len(password) < min_len:
|
||||
return jsonify({"error": f"password must be at least {min_len} characters"}), 400
|
||||
|
||||
role = _parse_role(role_raw)
|
||||
if role is None:
|
||||
return jsonify({"error": "role must be one of: admin, redteam, soc"}), 400
|
||||
|
||||
if User.query.filter_by(username=username).first() is not None:
|
||||
return jsonify({"error": "username already exists"}), 400
|
||||
|
||||
user = User(username=username, password_hash=hash_password(password), role=role)
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
return jsonify(serialize_user(user)), 201
|
||||
|
||||
|
||||
@users_bp.patch("/<int:user_id>")
|
||||
@role_required("admin")
|
||||
def update_user(user_id: int):
|
||||
user = db.session.get(User, user_id)
|
||||
if user is None:
|
||||
return jsonify({"error": "User not found"}), 404
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
|
||||
if "role" in data:
|
||||
new_role = _parse_role((data.get("role") or "").strip())
|
||||
if new_role is None:
|
||||
return jsonify({"error": "role must be one of: admin, redteam, soc"}), 400
|
||||
# Refuse to demote the last admin.
|
||||
if user.role == UserRole.ADMIN and new_role != UserRole.ADMIN:
|
||||
admin_count = User.query.filter_by(role=UserRole.ADMIN).count()
|
||||
if admin_count <= 1:
|
||||
return jsonify({"error": "Cannot demote the last admin"}), 409
|
||||
user.role = new_role
|
||||
|
||||
if "password" in data:
|
||||
password = data.get("password") or ""
|
||||
min_len = current_app.config["MIN_PASSWORD_LENGTH"]
|
||||
if len(password) < min_len:
|
||||
return (
|
||||
jsonify({"error": f"password must be at least {min_len} characters"}),
|
||||
400,
|
||||
)
|
||||
user.password_hash = hash_password(password)
|
||||
|
||||
db.session.commit()
|
||||
return jsonify(serialize_user(user)), 200
|
||||
|
||||
|
||||
@users_bp.delete("/<int:user_id>")
|
||||
@role_required("admin")
|
||||
def delete_user(user_id: int):
|
||||
user = db.session.get(User, user_id)
|
||||
if user is None:
|
||||
return jsonify({"error": "User not found"}), 404
|
||||
|
||||
if user.role == UserRole.ADMIN:
|
||||
admin_count = User.query.filter_by(role=UserRole.ADMIN).count()
|
||||
if admin_count <= 1:
|
||||
return jsonify({"error": "Cannot delete the last admin"}), 409
|
||||
|
||||
db.session.delete(user)
|
||||
db.session.commit()
|
||||
return "", 204
|
||||
Reference in New Issue
Block a user