2026-05-26 10:59:14 +02:00
|
|
|
"""Simulation business logic: PATCH rules and state machine transitions."""
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
from datetime import UTC, datetime
|
|
|
|
|
from typing import Any
|
|
|
|
|
|
|
|
|
|
from flask import jsonify
|
|
|
|
|
|
|
|
|
|
from backend.app.extensions import db
|
|
|
|
|
from backend.app.models import User
|
|
|
|
|
from backend.app.models.simulation import Simulation, SimulationStatus
|
|
|
|
|
|
feat(backend): sprint 3 — multi-technique simulations + MITRE matrix
- Simulation model: replace mitre_technique_id/name scalars with techniques JSON column [{id, name}]
- Alembic migration 0003: add techniques, backfill from scalars, drop old columns (reversible)
- MITRE service: add get_tactics(), lookup_name(), get_matrix() with canonical tactic order and sub-technique nesting
- serializer: enrich techniques with tactics from service at serialize time (graceful empty tactics if bundle outdated)
- simulation_workflow: PATCH now accepts technique_ids list, validates against bundle, deduplicates preserving order, auto-transitions on non-empty list
- simulations API: add GET /api/mitre/matrix endpoint (503 if bundle absent)
- test_mitre.py: updated _reset_mitre fixture, added T1059.006 sub-technique, 14 new tests for get_tactics/lookup_name/get_matrix/matrix endpoint
- test_simulations_techniques.py: 20 new tests covering AC-13.1 to AC-13.5 (create, PATCH, dedup, auto-transition, SOC blocked, migration backfill logic)
Total: 161 tests passing. ruff clean. mypy: no new errors.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-27 03:56:02 +02:00
|
|
|
# Fields only admin/redteam may write (excluding technique_ids which is handled separately).
|
2026-05-26 10:59:14 +02:00
|
|
|
REDTEAM_FIELDS = frozenset(
|
|
|
|
|
{
|
|
|
|
|
"name",
|
|
|
|
|
"description",
|
|
|
|
|
"commands",
|
|
|
|
|
"prerequisites",
|
|
|
|
|
"executed_at",
|
|
|
|
|
"execution_result",
|
|
|
|
|
}
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
SOC_FIELDS = frozenset({"log_source", "logs", "soc_comment", "incident_number"})
|
|
|
|
|
|
|
|
|
|
_ALLOWED_TRANSITIONS: dict[str, dict[str, set[str]]] = {
|
|
|
|
|
"review_required": {
|
|
|
|
|
"from": {"pending", "in_progress"},
|
|
|
|
|
"roles": {"admin", "redteam"},
|
|
|
|
|
},
|
|
|
|
|
"done": {
|
|
|
|
|
"from": {"review_required"},
|
|
|
|
|
"roles": {"admin", "redteam", "soc"},
|
|
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _is_non_empty(value: Any) -> bool:
|
|
|
|
|
"""Return True if value counts as "filled" for auto-transition purposes."""
|
|
|
|
|
if value is None:
|
|
|
|
|
return False
|
|
|
|
|
if isinstance(value, str) and value == "":
|
|
|
|
|
return False
|
|
|
|
|
return not (isinstance(value, list) and len(value) == 0)
|
|
|
|
|
|
|
|
|
|
|
feat(backend): sprint 3 — multi-technique simulations + MITRE matrix
- Simulation model: replace mitre_technique_id/name scalars with techniques JSON column [{id, name}]
- Alembic migration 0003: add techniques, backfill from scalars, drop old columns (reversible)
- MITRE service: add get_tactics(), lookup_name(), get_matrix() with canonical tactic order and sub-technique nesting
- serializer: enrich techniques with tactics from service at serialize time (graceful empty tactics if bundle outdated)
- simulation_workflow: PATCH now accepts technique_ids list, validates against bundle, deduplicates preserving order, auto-transitions on non-empty list
- simulations API: add GET /api/mitre/matrix endpoint (503 if bundle absent)
- test_mitre.py: updated _reset_mitre fixture, added T1059.006 sub-technique, 14 new tests for get_tactics/lookup_name/get_matrix/matrix endpoint
- test_simulations_techniques.py: 20 new tests covering AC-13.1 to AC-13.5 (create, PATCH, dedup, auto-transition, SOC blocked, migration backfill logic)
Total: 161 tests passing. ruff clean. mypy: no new errors.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-27 03:56:02 +02:00
|
|
|
def _resolve_technique_ids(
|
|
|
|
|
technique_ids: list[str],
|
|
|
|
|
) -> tuple[list[dict[str, str]] | None, tuple[Any, int] | None]:
|
|
|
|
|
"""Validate and resolve technique IDs to [{id, name}] snapshots.
|
|
|
|
|
|
|
|
|
|
Returns (resolved_list, None) on success or (None, error_tuple) on failure.
|
|
|
|
|
Deduplicates while preserving order.
|
|
|
|
|
"""
|
|
|
|
|
from backend.app.services import mitre as mitre_svc
|
|
|
|
|
|
2026-05-27 03:58:30 +02:00
|
|
|
if not mitre_svc.mitre_loaded:
|
|
|
|
|
return None, (jsonify({"error": "mitre bundle not loaded"}), 503)
|
|
|
|
|
|
feat(backend): sprint 3 — multi-technique simulations + MITRE matrix
- Simulation model: replace mitre_technique_id/name scalars with techniques JSON column [{id, name}]
- Alembic migration 0003: add techniques, backfill from scalars, drop old columns (reversible)
- MITRE service: add get_tactics(), lookup_name(), get_matrix() with canonical tactic order and sub-technique nesting
- serializer: enrich techniques with tactics from service at serialize time (graceful empty tactics if bundle outdated)
- simulation_workflow: PATCH now accepts technique_ids list, validates against bundle, deduplicates preserving order, auto-transitions on non-empty list
- simulations API: add GET /api/mitre/matrix endpoint (503 if bundle absent)
- test_mitre.py: updated _reset_mitre fixture, added T1059.006 sub-technique, 14 new tests for get_tactics/lookup_name/get_matrix/matrix endpoint
- test_simulations_techniques.py: 20 new tests covering AC-13.1 to AC-13.5 (create, PATCH, dedup, auto-transition, SOC blocked, migration backfill logic)
Total: 161 tests passing. ruff clean. mypy: no new errors.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-27 03:56:02 +02:00
|
|
|
# Dedup, preserve order.
|
|
|
|
|
seen: dict[str, None] = dict.fromkeys(technique_ids)
|
|
|
|
|
resolved: list[dict[str, str]] = []
|
|
|
|
|
for tid in seen:
|
|
|
|
|
name = mitre_svc.lookup_name(tid)
|
|
|
|
|
if name is None:
|
|
|
|
|
return None, (jsonify({"error": f"unknown technique id: {tid}"}), 400)
|
|
|
|
|
resolved.append({"id": tid, "name": name})
|
|
|
|
|
return resolved, None
|
|
|
|
|
|
|
|
|
|
|
2026-05-26 10:59:14 +02:00
|
|
|
def apply_patch(
|
|
|
|
|
simulation: Simulation, payload: dict[str, Any], user: User
|
|
|
|
|
) -> tuple[Any, int] | None:
|
|
|
|
|
"""Apply a validated PATCH payload to a simulation.
|
|
|
|
|
|
|
|
|
|
Returns a (response, status_code) tuple on error, or None on success
|
|
|
|
|
(caller is responsible for committing).
|
|
|
|
|
"""
|
|
|
|
|
role = user.role.value
|
|
|
|
|
|
|
|
|
|
if role == "soc":
|
|
|
|
|
if simulation.status not in (
|
|
|
|
|
SimulationStatus.REVIEW_REQUIRED,
|
|
|
|
|
SimulationStatus.DONE,
|
|
|
|
|
):
|
|
|
|
|
return jsonify({"error": "simulation not ready for SOC review"}), 403
|
|
|
|
|
|
feat(backend): sprint 3 — multi-technique simulations + MITRE matrix
- Simulation model: replace mitre_technique_id/name scalars with techniques JSON column [{id, name}]
- Alembic migration 0003: add techniques, backfill from scalars, drop old columns (reversible)
- MITRE service: add get_tactics(), lookup_name(), get_matrix() with canonical tactic order and sub-technique nesting
- serializer: enrich techniques with tactics from service at serialize time (graceful empty tactics if bundle outdated)
- simulation_workflow: PATCH now accepts technique_ids list, validates against bundle, deduplicates preserving order, auto-transitions on non-empty list
- simulations API: add GET /api/mitre/matrix endpoint (503 if bundle absent)
- test_mitre.py: updated _reset_mitre fixture, added T1059.006 sub-technique, 14 new tests for get_tactics/lookup_name/get_matrix/matrix endpoint
- test_simulations_techniques.py: 20 new tests covering AC-13.1 to AC-13.5 (create, PATCH, dedup, auto-transition, SOC blocked, migration backfill logic)
Total: 161 tests passing. ruff clean. mypy: no new errors.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-27 03:56:02 +02:00
|
|
|
# SOC must not send redteam fields or technique_ids.
|
|
|
|
|
redteam_keys_in_payload = (REDTEAM_FIELDS | {"technique_ids"}) & payload.keys()
|
2026-05-26 10:59:14 +02:00
|
|
|
if redteam_keys_in_payload:
|
|
|
|
|
return jsonify({"error": "soc cannot edit redteam fields"}), 403
|
|
|
|
|
|
|
|
|
|
for field in SOC_FIELDS:
|
|
|
|
|
if field in payload:
|
|
|
|
|
setattr(simulation, field, payload[field])
|
|
|
|
|
|
|
|
|
|
else:
|
feat(backend): sprint 3 — multi-technique simulations + MITRE matrix
- Simulation model: replace mitre_technique_id/name scalars with techniques JSON column [{id, name}]
- Alembic migration 0003: add techniques, backfill from scalars, drop old columns (reversible)
- MITRE service: add get_tactics(), lookup_name(), get_matrix() with canonical tactic order and sub-technique nesting
- serializer: enrich techniques with tactics from service at serialize time (graceful empty tactics if bundle outdated)
- simulation_workflow: PATCH now accepts technique_ids list, validates against bundle, deduplicates preserving order, auto-transitions on non-empty list
- simulations API: add GET /api/mitre/matrix endpoint (503 if bundle absent)
- test_mitre.py: updated _reset_mitre fixture, added T1059.006 sub-technique, 14 new tests for get_tactics/lookup_name/get_matrix/matrix endpoint
- test_simulations_techniques.py: 20 new tests covering AC-13.1 to AC-13.5 (create, PATCH, dedup, auto-transition, SOC blocked, migration backfill logic)
Total: 161 tests passing. ruff clean. mypy: no new errors.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-27 03:56:02 +02:00
|
|
|
# admin / redteam path.
|
2026-05-26 10:59:14 +02:00
|
|
|
redteam_keys_present = REDTEAM_FIELDS & payload.keys()
|
|
|
|
|
|
feat(backend): sprint 3 — multi-technique simulations + MITRE matrix
- Simulation model: replace mitre_technique_id/name scalars with techniques JSON column [{id, name}]
- Alembic migration 0003: add techniques, backfill from scalars, drop old columns (reversible)
- MITRE service: add get_tactics(), lookup_name(), get_matrix() with canonical tactic order and sub-technique nesting
- serializer: enrich techniques with tactics from service at serialize time (graceful empty tactics if bundle outdated)
- simulation_workflow: PATCH now accepts technique_ids list, validates against bundle, deduplicates preserving order, auto-transitions on non-empty list
- simulations API: add GET /api/mitre/matrix endpoint (503 if bundle absent)
- test_mitre.py: updated _reset_mitre fixture, added T1059.006 sub-technique, 14 new tests for get_tactics/lookup_name/get_matrix/matrix endpoint
- test_simulations_techniques.py: 20 new tests covering AC-13.1 to AC-13.5 (create, PATCH, dedup, auto-transition, SOC blocked, migration backfill logic)
Total: 161 tests passing. ruff clean. mypy: no new errors.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-27 03:56:02 +02:00
|
|
|
# Validate executed_at upfront before any writes.
|
2026-05-26 11:21:32 +02:00
|
|
|
executed_at_value: datetime | None = None
|
|
|
|
|
if "executed_at" in redteam_keys_present:
|
|
|
|
|
val = payload["executed_at"]
|
|
|
|
|
if val is not None:
|
|
|
|
|
if not isinstance(val, str):
|
|
|
|
|
return jsonify({"error": "invalid executed_at"}), 400
|
|
|
|
|
try:
|
|
|
|
|
executed_at_value = datetime.fromisoformat(val)
|
|
|
|
|
except ValueError:
|
|
|
|
|
return jsonify({"error": "invalid executed_at"}), 400
|
|
|
|
|
|
feat(backend): sprint 3 — multi-technique simulations + MITRE matrix
- Simulation model: replace mitre_technique_id/name scalars with techniques JSON column [{id, name}]
- Alembic migration 0003: add techniques, backfill from scalars, drop old columns (reversible)
- MITRE service: add get_tactics(), lookup_name(), get_matrix() with canonical tactic order and sub-technique nesting
- serializer: enrich techniques with tactics from service at serialize time (graceful empty tactics if bundle outdated)
- simulation_workflow: PATCH now accepts technique_ids list, validates against bundle, deduplicates preserving order, auto-transitions on non-empty list
- simulations API: add GET /api/mitre/matrix endpoint (503 if bundle absent)
- test_mitre.py: updated _reset_mitre fixture, added T1059.006 sub-technique, 14 new tests for get_tactics/lookup_name/get_matrix/matrix endpoint
- test_simulations_techniques.py: 20 new tests covering AC-13.1 to AC-13.5 (create, PATCH, dedup, auto-transition, SOC blocked, migration backfill logic)
Total: 161 tests passing. ruff clean. mypy: no new errors.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-27 03:56:02 +02:00
|
|
|
# Validate and resolve technique_ids upfront.
|
|
|
|
|
resolved_techniques: list[dict[str, str]] | None = None
|
|
|
|
|
if "technique_ids" in payload:
|
|
|
|
|
raw_ids = payload["technique_ids"]
|
|
|
|
|
if not isinstance(raw_ids, list):
|
|
|
|
|
return jsonify({"error": "technique_ids must be a list"}), 400
|
|
|
|
|
resolved_techniques, err = _resolve_technique_ids(raw_ids)
|
|
|
|
|
if err is not None:
|
|
|
|
|
return err
|
|
|
|
|
|
|
|
|
|
# Apply scalar redteam fields.
|
2026-05-26 10:59:14 +02:00
|
|
|
for field in redteam_keys_present:
|
|
|
|
|
if field == "executed_at":
|
2026-05-26 11:21:32 +02:00
|
|
|
simulation.executed_at = executed_at_value
|
2026-05-26 10:59:14 +02:00
|
|
|
else:
|
|
|
|
|
setattr(simulation, field, payload[field])
|
|
|
|
|
|
feat(backend): sprint 3 — multi-technique simulations + MITRE matrix
- Simulation model: replace mitre_technique_id/name scalars with techniques JSON column [{id, name}]
- Alembic migration 0003: add techniques, backfill from scalars, drop old columns (reversible)
- MITRE service: add get_tactics(), lookup_name(), get_matrix() with canonical tactic order and sub-technique nesting
- serializer: enrich techniques with tactics from service at serialize time (graceful empty tactics if bundle outdated)
- simulation_workflow: PATCH now accepts technique_ids list, validates against bundle, deduplicates preserving order, auto-transitions on non-empty list
- simulations API: add GET /api/mitre/matrix endpoint (503 if bundle absent)
- test_mitre.py: updated _reset_mitre fixture, added T1059.006 sub-technique, 14 new tests for get_tactics/lookup_name/get_matrix/matrix endpoint
- test_simulations_techniques.py: 20 new tests covering AC-13.1 to AC-13.5 (create, PATCH, dedup, auto-transition, SOC blocked, migration backfill logic)
Total: 161 tests passing. ruff clean. mypy: no new errors.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-27 03:56:02 +02:00
|
|
|
# Apply resolved techniques.
|
|
|
|
|
if resolved_techniques is not None:
|
|
|
|
|
simulation.techniques = resolved_techniques
|
|
|
|
|
|
|
|
|
|
# Apply SOC fields (admin/redteam may also write them).
|
2026-05-26 10:59:14 +02:00
|
|
|
for field in SOC_FIELDS:
|
|
|
|
|
if field in payload:
|
|
|
|
|
setattr(simulation, field, payload[field])
|
|
|
|
|
|
feat(backend): sprint 3 — multi-technique simulations + MITRE matrix
- Simulation model: replace mitre_technique_id/name scalars with techniques JSON column [{id, name}]
- Alembic migration 0003: add techniques, backfill from scalars, drop old columns (reversible)
- MITRE service: add get_tactics(), lookup_name(), get_matrix() with canonical tactic order and sub-technique nesting
- serializer: enrich techniques with tactics from service at serialize time (graceful empty tactics if bundle outdated)
- simulation_workflow: PATCH now accepts technique_ids list, validates against bundle, deduplicates preserving order, auto-transitions on non-empty list
- simulations API: add GET /api/mitre/matrix endpoint (503 if bundle absent)
- test_mitre.py: updated _reset_mitre fixture, added T1059.006 sub-technique, 14 new tests for get_tactics/lookup_name/get_matrix/matrix endpoint
- test_simulations_techniques.py: 20 new tests covering AC-13.1 to AC-13.5 (create, PATCH, dedup, auto-transition, SOC blocked, migration backfill logic)
Total: 161 tests passing. ruff clean. mypy: no new errors.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-27 03:56:02 +02:00
|
|
|
# Auto-transition pending → in_progress.
|
|
|
|
|
# Triggers when any redteam scalar has a non-empty value, OR technique_ids is non-empty.
|
|
|
|
|
auto_trigger = any(_is_non_empty(payload[k]) for k in redteam_keys_present)
|
|
|
|
|
if not auto_trigger and "technique_ids" in payload:
|
|
|
|
|
auto_trigger = len(payload["technique_ids"]) > 0
|
|
|
|
|
|
|
|
|
|
if simulation.status == SimulationStatus.PENDING and auto_trigger:
|
2026-05-26 10:59:14 +02:00
|
|
|
simulation.status = SimulationStatus.IN_PROGRESS
|
|
|
|
|
|
|
|
|
|
simulation.updated_at = datetime.now(UTC)
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def transition(
|
|
|
|
|
simulation: Simulation, to_status: str, user: User
|
|
|
|
|
) -> tuple[Any, int] | None:
|
|
|
|
|
"""Attempt a manual transition. Returns error tuple or None on success."""
|
|
|
|
|
rule = _ALLOWED_TRANSITIONS.get(to_status)
|
|
|
|
|
if rule is None:
|
|
|
|
|
return jsonify({"error": "invalid transition"}), 409
|
|
|
|
|
|
|
|
|
|
if simulation.status.value not in rule["from"]:
|
|
|
|
|
return jsonify({"error": "invalid transition"}), 409
|
|
|
|
|
|
|
|
|
|
if user.role.value not in rule["roles"]:
|
|
|
|
|
return jsonify({"error": "Forbidden"}), 403
|
|
|
|
|
|
|
|
|
|
simulation.status = SimulationStatus(to_status)
|
|
|
|
|
simulation.updated_at = datetime.now(UTC)
|
|
|
|
|
db.session.commit()
|
|
|
|
|
return None
|