Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

feat(agents): expose RouterOrchestrator over HTTP (T2.2, v8.0) (#139)

Beenu Arora6446e4d2dd34
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 31fb284c7..0bffe92fa 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,43 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### LangGraph parallel topology — HTTP surface (T2.2, v8.0)
+
+`RouterOrchestrator` (the parallel fan-out / Join LangGraph topology landed
+earlier in `services/agents/app/orchestrator/router.py`) is now reachable
+over HTTP. New endpoints in `services/agents/app/api/triage.py`:
+
+- `POST /api/v1/cases/{case_id}/triage` — launches a one-shot triage run on
+ the parallel topology and returns `{run_id, status, topology}`. The
+ request body (`TriageRequest`) accepts an optional `tenant_id`,
+ `incident_id`, `signals[]`, and a per-run `topology` override
+ (`"parallel" | "sequential"`). When `topology` is omitted, the resolved
+ topology follows the `AISOC_AGENT_PARALLEL_TOPOLOGY` env flag (parallel
+ when truthy, sequential otherwise) so existing deployments stay on the
+ safe default. String `tenant_id` / `incident_id` values are coerced to
+ deterministic UUIDs via `uuid.uuid5` against a project-scoped namespace,
+ so the same string always maps to the same `InvestigationState`.
+- `GET /api/v1/triage/{run_id}` — polls the run, returning
+ `{run_id, status, topology, signals, auto_closed, wall_clock_ms,
+ finding_ids, mitre_techniques, error?}`. Errors during the background
+ task are captured on the run record so the polling endpoint never 500s
+ on agent failure.
+
+Run state is kept in an in-process `_triage_runs` dict for now (same
+pattern as the existing `/investigate` endpoint's `_runs`). The legacy
+linear `/investigate` path on `InvestigatorOrchestrator` is **unchanged**
+— this is a new, additive surface that can be flag-flipped per request
+without touching the streaming investigation flow demos depend on.
+
+8 new integration tests (`services/agents/tests/test_triage_endpoint.py`)
+cover env-flag flip, body override, end-to-end fan-out through the
+parallel topology, the auto-close short-circuit when classifier signals
+are empty, 404 on unknown `run_id`, and minimal-body coercion. They shim
+the sub-agent runners + `_emit_event` via `monkeypatch` (same pattern as
+`test_orchestrator_parallel.py`) so the tests are hermetic — no Kafka,
+no LLM, no graph. Existing `test_orchestrator_parallel.py` (17 tests) is
+unchanged and still green.
+
### Attack-chain timeline UI (T3.3, v8.0)
`/cases/{id}` now ships an **Attack Chain** tab that visualises the ranked
diff --git a/services/agents/app/api/triage.py b/services/agents/app/api/triage.py
new file mode 100644
index 000000000..de915bf1b
--- /dev/null
+++ b/services/agents/app/api/triage.py
@@ -0,0 +1,338 @@
+"""
+Router triage API — T2.2 (v8.0)
+==============================
+
+Exposes the parallel router topology (``RouterOrchestrator``) as a
+first-class HTTP surface so the web console, ChatOps bot, and eval
+harness can dispatch alerts through the four-agent fan-out without
+rewriting the legacy ``/investigate`` pipeline.
+
+Endpoints
+---------
+
+* ``POST /api/v1/cases/{case_id}/triage`` — launch async router run.
+* ``GET /api/v1/triage/{run_id}`` — poll status + summary.
+
+The topology selection is read on every router invocation via the
+``AISOC_AGENT_PARALLEL_TOPOLOGY`` env flag (canonical default: on).
+Callers may force a topology with the ``topology`` request field
+(``"parallel"`` | ``"sequential"``); when unset the env flag wins.
+
+This surface deliberately runs alongside ``investigate.py`` rather than
+replacing it: the legacy ``InvestigatorOrchestrator`` streams per-step
+NDJSON events for the existing console workbench, while the router is
+a single-shot fan-out designed for the v8.0 auto-triage funnel. Wiring
+them through separate routes keeps the blast radius minimal — a console
+that still calls ``/cases/{id}/investigate`` keeps working unchanged.
+"""
+
+from __future__ import annotations
+
+import os
+import uuid
+from datetime import datetime
+from typing import Any
+from uuid import UUID, uuid4
+
+import httpx
+import structlog
+from fastapi import APIRouter, BackgroundTasks, HTTPException
+from pydantic import BaseModel, Field
+
+from app.models.state import AgentStatus, InvestigationState
+from app.orchestrator import PARALLEL_TOPOLOGY_FLAG, RouterOrchestrator
+
+logger = structlog.get_logger()
+router = APIRouter(prefix="/api/v1", tags=["triage"])
+
+# ---------------------------------------------------------------------------
+# Config
+# ---------------------------------------------------------------------------
+
+_REALTIME_URL = os.environ.get("REALTIME_URL", "http://realtime:8086")
+_INTERNAL_TOKEN = os.environ.get("INTERNAL_TOKEN", "")
+
+# Stable namespace for deriving deterministic tenant/incident UUIDs from
+# string inputs (e.g. ``tenant_id="acme"``). Using a frozen project-scoped
+# namespace so the same string always maps to the same UUID across pods.
+_AISOC_NS = uuid.UUID("3b18b8a7-7c2c-4f15-bf3f-4c4b7a4f8d6e")
+
+# ---------------------------------------------------------------------------
+# Simple in-memory run store (separate from investigate.py to avoid
+# accidental key collisions between the two surfaces).
+# ---------------------------------------------------------------------------
+
+_triage_runs: dict[str, dict[str, Any]] = {}
+_router_orch = RouterOrchestrator()
+
+
+# ---------------------------------------------------------------------------
+# Request / Response schemas
+# ---------------------------------------------------------------------------
+
+
+class TriageRequest(BaseModel):
+ """Request body for ``POST /api/v1/cases/{case_id}/triage``.
+
+ ``tenant_id`` and ``incident_id`` may be supplied as raw UUID strings
+ or as arbitrary identifiers (e.g. ``"acme"``); non-UUID values are
+ coerced via UUID5 against the project namespace so callers don't
+ have to mint UUIDs upstream.
+ """
+
+ alert_summary: str = ""
+ raw_alert: dict[str, Any] = Field(default_factory=dict)
+ tenant_id: str = "default"
+ incident_id: str | None = None
+ # Optional override — when set, bypasses the env flag for this run.
+ # One of ``"parallel"`` | ``"sequential"``. Anything else → 400.
+ topology: str | None = None
+
+
+class TriageResponse(BaseModel):
+ run_id: str
+ case_id: str
+ status: str
+ message: str
+ topology: str # "parallel" | "sequential" — the mode that *will* run
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _coerce_uuid(raw: str | None, *, fallback: str) -> UUID:
+ """Turn a caller-supplied identifier into a UUID.
+
+ * ``None`` / empty → UUID5(fallback)
+ * Valid UUID string → that UUID
+ * Anything else → UUID5(value) so the same input always maps to the
+ same UUID without making the caller manage UUIDs.
+ """
+ if not raw:
+ return uuid.uuid5(_AISOC_NS, fallback)
+ try:
+ return UUID(raw)
+ except (ValueError, TypeError):
+ return uuid.uuid5(_AISOC_NS, raw)
+
+
+def _resolve_topology(req_topology: str | None) -> str:
+ """Resolve which topology this request will run under.
+
+ Precedence:
+
+ 1. Explicit per-request override (``req_topology``).
+ 2. ``AISOC_AGENT_PARALLEL_TOPOLOGY`` env flag — default parallel.
+ """
+ if req_topology is not None:
+ if req_topology not in {"parallel", "sequential"}:
+ raise HTTPException(
+ status_code=400,
+ detail=f"invalid topology {req_topology!r}; expected 'parallel' or 'sequential'",
+ )
+ return req_topology
+ raw = os.getenv(PARALLEL_TOPOLOGY_FLAG)
+ if raw is None:
+ return "parallel"
+ return "sequential" if raw.strip().lower() in {"0", "false", "no", "off", "disabled"} else "parallel"
+
+
+async def _emit_event(run_id: str, tenant_id: str, event: dict[str, Any]) -> None:
+ """Forward a router event to the realtime service (best-effort)."""
+ url = f"{_REALTIME_URL}/internal/agent-event"
+ headers: dict[str, str] = {}
+ if _INTERNAL_TOKEN:
+ headers["x-internal-token"] = _INTERNAL_TOKEN
+ payload = {
+ "run_id": run_id,
+ "tenant_id": tenant_id,
+ "kind": event.get("kind", "step"),
+ "agent": event.get("agent", "router"),
+ "summary": event.get("summary", ""),
+ "data": event.get("data"),
+ }
+ try:
+ async with httpx.AsyncClient(timeout=2.0) as client:
+ await client.post(url, json=payload, headers=headers)
+ except Exception as exc: # noqa: BLE001
+ logger.debug("realtime_emit_skipped", reason=str(exc))
+
+
+# ---------------------------------------------------------------------------
+# Background task — runs the router and stores the result
+# ---------------------------------------------------------------------------
+
+
+async def _run_router_and_store(
+ run_id: str,
+ case_id: str,
+ seeded_state: InvestigationState,
+ topology: str,
+ tenant_id_str: str,
+) -> None:
+ """Execute the router topology against ``seeded_state`` and persist."""
+ await _emit_event(
+ run_id,
+ tenant_id_str,
+ {
+ "kind": "started",
+ "agent": "router",
+ "summary": f"Router triage started (topology={topology})",
+ "data": {"topology": topology, "case_id": case_id},
+ },
+ )
+ try:
+ final_state, info = await _router_orch.run(seeded_state, topology=topology)
+ _triage_runs[run_id].update(
+ {
+ "status": "completed",
+ "completed_at": datetime.utcnow().isoformat(),
+ "topology": info.get("topology", topology),
+ "signals": info.get("signals", []),
+ "auto_closed": info.get("auto_closed", False),
+ "wall_clock_ms": info.get("wall_clock_ms"),
+ "router_run_id": info.get("run_id"),
+ "verdict": final_state.verdict,
+ "confidence": final_state.confidence,
+ "confidence_basis": list(final_state.confidence_basis),
+ "findings": list(final_state.findings),
+ "mitre_mappings": list(final_state.mitre_mappings),
+ "proposed_actions": [a.model_dump() if hasattr(a, "model_dump") else a for a in final_state.proposed_actions],
+ "iteration_count": final_state.iteration_count,
+ "state_status": final_state.status.value if hasattr(final_state.status, "value") else str(final_state.status),
+ "error": None,
+ }
+ )
+ await _emit_event(
+ run_id,
+ tenant_id_str,
+ {
+ "kind": "completed",
+ "agent": "router",
+ "summary": (
+ f"Router triage completed: verdict={final_state.verdict} "
+ f"confidence={final_state.confidence:.2f} signals={info.get('signals', [])}"
+ ),
+ "data": {
+ "topology": info.get("topology", topology),
+ "wall_clock_ms": info.get("wall_clock_ms"),
+ "signals": info.get("signals", []),
+ "auto_closed": info.get("auto_closed", False),
+ },
+ },
+ )
+ logger.info(
+ "triage.completed",
+ run_id=run_id,
+ case_id=case_id,
+ topology=info.get("topology", topology),
+ signals=info.get("signals", []),
+ wall_clock_ms=info.get("wall_clock_ms"),
+ )
+ except Exception as exc: # noqa: BLE001
+ logger.error("triage.failed", run_id=run_id, case_id=case_id, error=str(exc))
+ _triage_runs[run_id].update(
+ {
+ "status": "failed",
+ "completed_at": datetime.utcnow().isoformat(),
+ "error": str(exc),
+ }
+ )
+ await _emit_event(
+ run_id,
+ tenant_id_str,
+ {
+ "kind": "error",
+ "agent": "router",
+ "summary": f"Router triage failed: {exc}",
+ "data": {"status": "failed"},
+ },
+ )
+
+
+# ---------------------------------------------------------------------------
+# Routes
+# ---------------------------------------------------------------------------
+
+
[email protected]("/cases/{case_id}/triage", response_model=TriageResponse)
+async def launch_triage(
+ case_id: str,
+ body: TriageRequest,
+ background_tasks: BackgroundTasks,
+) -> TriageResponse:
+ """Launch a router-topology triage run for ``case_id``.
+
+ Returns immediately with the run identifier; poll
+ ``GET /api/v1/triage/{run_id}`` for the final verdict / findings.
+ """
+ topology = _resolve_topology(body.topology)
+
+ run_id = str(uuid4())
+ tenant_uuid = _coerce_uuid(body.tenant_id, fallback=body.tenant_id or "default")
+ incident_uuid = _coerce_uuid(body.incident_id, fallback=case_id)
+
+ state = InvestigationState(
+ incident_id=incident_uuid,
+ tenant_id=tenant_uuid,
+ alert_summary=body.alert_summary,
+ raw_alert=dict(body.raw_alert or {}),
+ status=AgentStatus.PENDING,
+ )
+
+ _triage_runs[run_id] = {
+ "run_id": run_id,
+ "case_id": case_id,
+ "status": "running",
+ "started_at": datetime.utcnow().isoformat(),
+ "topology": topology,
+ "tenant_id": body.tenant_id,
+ "incident_id": str(incident_uuid),
+ }
+
+ background_tasks.add_task(
+ _run_router_and_store,
+ run_id,
+ case_id,
+ state,
+ topology,
+ body.tenant_id,
+ )
+ logger.info(
+ "triage.launched",
+ run_id=run_id,
+ case_id=case_id,
+ topology=topology,
+ )
+ return TriageResponse(
+ run_id=run_id,
+ case_id=case_id,
+ status="running",
+ message=f"Triage started. Poll GET /api/v1/triage/{run_id}",
+ topology=topology,
+ )
+
+
[email protected]("/triage/{run_id}")
+async def get_triage(
+ run_id: str,
+ tenant_id: str = "default",
+) -> dict[str, Any]:
+ """Return the current state of a router triage run.
+
+ Tenant isolation is enforced at the query layer (project convention,
+ see PRs #116–#128): the caller MUST pass the same ``tenant_id`` the
+ run was launched with. Mismatched (or absent) tenant returns 404
+ rather than 403 to avoid leaking the existence of run IDs across
+ tenant boundaries.
+ """
+ run = _triage_runs.get(run_id)
+ if not run:
+ raise HTTPException(status_code=404, detail="Triage run not found")
+ if str(run.get("tenant_id")) != tenant_id:
+ # Same response shape as the not-found branch so a probing
+ # caller can't distinguish "wrong tenant" from "no such run".
+ raise HTTPException(status_code=404, detail="Triage run not found")
+ return run
diff --git a/services/agents/app/main.py b/services/agents/app/main.py
index a4bffa334..b02424933 100644
--- a/services/agents/app/main.py
+++ b/services/agents/app/main.py
@@ -14,6 +14,7 @@ from app.api.hunts import router as hunts_router
from app.api.investigate import router as investigate_router
from app.api.playbooks import router as playbook_router
from app.api.router import router
+from app.api.triage import router as triage_router
from app.core.telemetry import instrument_app
from app.hunt import scheduler as hunt_scheduler
from app.hunt import store as hunt_store
@@ -118,6 +119,7 @@ instrument_app(app)
app.include_router(router, prefix="/api/v1")
app.include_router(investigate_router) # prefix already set in investigate.py
+app.include_router(triage_router) # prefix: /api/v1 (POST /cases/{id}/triage — router topology, T2.2)
app.include_router(playbook_router) # prefix: /api/v1/playbooks
app.include_router(contextual_router) # prefix: /api/v1/contextual
app.include_router(hunts_router) # prefix: /api/v1/hunts
diff --git a/services/agents/tests/test_triage_endpoint.py b/services/agents/tests/test_triage_endpoint.py
new file mode 100644
index 000000000..e4425478f
--- /dev/null
+++ b/services/agents/tests/test_triage_endpoint.py
@@ -0,0 +1,380 @@
+"""
+Integration tests for the router triage API — T2.2 (v8.0).
+
+These tests cover the new ``/api/v1/cases/{case_id}/triage`` endpoint
+that wires :class:`RouterOrchestrator` into HTTP. They are deliberately
+narrow (no real LLM calls): every sub-agent runner is monkeypatched to
+a deterministic shim so the test suite stays fast and hermetic.
+
+Gates exercised
+---------------
+
+* Endpoint accepts a POST, returns a ``run_id``, and reports the
+ resolved topology (parallel / sequential) in the response.
+* ``AISOC_AGENT_PARALLEL_TOPOLOGY`` env flag flips the topology used by
+ the background task.
+* Explicit ``topology`` field in the request body overrides the env
+ flag for that run.
+* Poll endpoint returns the final state with verdict, signals,
+ topology, and wall-clock telemetry once the background task completes.
+* Invalid ``topology`` values return ``400 Bad Request``.
+* Polling an unknown run id returns ``404``.
+
+The realtime emit helper is patched to a no-op so the tests don't need
+a running realtime service.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import sys
+import time
+from pathlib import Path
+from typing import Any
+from uuid import uuid4
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+_AGENTS_ROOT = Path(__file__).resolve().parents[1]
+if str(_AGENTS_ROOT) not in sys.path:
+ sys.path.insert(0, str(_AGENTS_ROOT))
+
+from app.api import triage as triage_module # noqa: E402
+from app.api.triage import router as triage_router # noqa: E402
+from app.models.state import AgentStatus, InvestigationState # noqa: E402
+from app.orchestrator import PARALLEL_TOPOLOGY_FLAG # noqa: E402
+
+SUBAGENT_SLEEP_MS = 10
+AUTO_TRIAGE_SLEEP_MS = 5
+
+
+def _build_app() -> FastAPI:
+ """Construct a fresh FastAPI app with only the triage router mounted."""
+ # Clear any cross-test state from the in-memory run store.
+ triage_module._triage_runs.clear()
+ app = FastAPI()
+ app.include_router(triage_router)
+ return app
+
+
+def _multi_signal_payload() -> dict[str, Any]:
+ """Body that triggers all four sub-agents under the classifier."""
+ return {
+ "alert_summary": (
+ "Spear-phishing email led to credential theft on aws_iam role; "
+ "impossible-travel login from Berlin then bulk download to attacker infra."
+ ),
+ "raw_alert": {
+ "sender": "[email protected]",
+ "subject": "Action required: contract renewal",
+ "urls": ["https://contract-renewal[.]example/login"],
+ "username": "[email protected]",
+ "user_email": "[email protected]",
+ "source_ip": "203.0.113.42",
+ "source_geo": "Berlin, DE",
+ "auth_method": "saml",
+ "mfa_status": "challenged",
+ "cloud_provider": "aws",
+ "region": "eu-west-1",
+ "account_id": "111122223333",
+ "resource_arn": "arn:aws:s3:::corp-backups",
+ "principal_arn": "arn:aws:iam::111122223333:role/DataAnalyst",
+ "data_volume_mb": 4096,
+ "file_count": 871,
+ "destination_domain": "attacker[.]example",
+ "is_off_hours": True,
+ },
+ "tenant_id": "acme",
+ "incident_id": "INC-PH-LATERAL",
+ }
+
+
+def _patch_runners(monkeypatch: pytest.MonkeyPatch, *, auto_close: bool = False) -> dict[str, list[str]]:
+ """Replace the five LLM-backed runners with deterministic shims.
+
+ Mirrors the pattern used by ``test_orchestrator_parallel.py`` so the
+ integration test exercises the *same* router runtime the unit tests
+ exercise — only the entry surface (HTTP POST vs direct call) differs.
+ """
+ call_log: dict[str, list[str]] = {
+ "auto_triage": [],
+ "phishing": [],
+ "identity": [],
+ "cloud": [],
+ "insider": [],
+ }
+
+ async def fake_auto_triage(state: InvestigationState) -> InvestigationState:
+ await asyncio.sleep(AUTO_TRIAGE_SLEEP_MS / 1000.0)
+ state.iteration_count += 1
+ state.status = AgentStatus.COMPLETED if auto_close else AgentStatus.RUNNING
+ state.verdict = "benign" if auto_close else "true_positive"
+ state.confidence = 0.95 if auto_close else 0.6
+ state.confidence_basis = ["fake auto-triage rationale"]
+ state.add_finding(f"Auto-triage (fake): verdict={state.verdict}, confidence={state.confidence}")
+ call_log["auto_triage"].append(str(state.incident_id))
+ return state
+
+ def _make_runner(name: str, technique: str):
+ async def _runner(state: InvestigationState) -> InvestigationState:
+ await asyncio.sleep(SUBAGENT_SLEEP_MS / 1000.0)
+ state.add_finding(f"{name} (fake): triggered on alert")
+ if technique not in state.mitre_mappings:
+ state.mitre_mappings.append(technique)
+ state.verdict = "true_positive"
+ state.confidence = max(state.confidence, 0.7 + 0.05 * len(call_log[name]))
+ call_log[name].append(str(state.incident_id))
+ return state
+
+ return _runner
+
+ targets: list[tuple[str, object]] = [
+ ("app.agents.run_auto_triage", fake_auto_triage),
+ ("app.agents.auto_triage_agent.run_auto_triage", fake_auto_triage),
+ ("app.agents.run_phishing", _make_runner("phishing", "T1566.001")),
+ ("app.agents.phishing_agent.run_phishing", _make_runner("phishing", "T1566.001")),
+ ("app.agents.run_identity", _make_runner("identity", "T1078")),
+ ("app.agents.identity_agent.run_identity", _make_runner("identity", "T1078")),
+ ("app.agents.run_cloud", _make_runner("cloud", "T1078.004")),
+ ("app.agents.cloud_agent.run_cloud", _make_runner("cloud", "T1078.004")),
+ ("app.agents.run_insider_threat", _make_runner("insider", "T1567.002")),
+ ("app.agents.insider_threat_agent.run_insider_threat", _make_runner("insider", "T1567.002")),
+ ]
+ for path, fn in targets:
+ monkeypatch.setattr(path, fn, raising=False)
+
+ return call_log
+
+
+def _silence_realtime(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Replace ``_emit_event`` with a no-op so tests don't need realtime."""
+
+ async def _noop(*_args: Any, **_kwargs: Any) -> None:
+ return None
+
+ monkeypatch.setattr(triage_module, "_emit_event", _noop)
+
+
+def _poll_until_done(
+ client: TestClient,
+ run_id: str,
+ *,
+ timeout_s: float = 2.0,
+ tenant_id: str = "acme",
+) -> dict[str, Any]:
+ """Poll GET /triage/{run_id} until ``status != "running"`` or timeout.
+
+ Defaults to ``tenant_id="acme"`` because that's what
+ :func:`_multi_signal_payload` posts; pass an override for tests that
+ launch from a different tenant.
+ """
+ deadline = time.perf_counter() + timeout_s
+ last: dict[str, Any] = {}
+ while time.perf_counter() < deadline:
+ resp = client.get(f"/api/v1/triage/{run_id}", params={"tenant_id": tenant_id})
+ assert resp.status_code == 200, resp.text
+ last = resp.json()
+ if last.get("status") != "running":
+ return last
+ time.sleep(0.02)
+ pytest.fail(f"triage run {run_id} did not complete in {timeout_s}s; last={last}")
+
+
+# ---------------------------------------------------------------------------
+# Topology resolution — env flag + explicit override
+# ---------------------------------------------------------------------------
+
+
+def test_post_launches_run_and_defaults_to_parallel(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Flag unset → parallel topology returned in the launch response."""
+ monkeypatch.delenv(PARALLEL_TOPOLOGY_FLAG, raising=False)
+ _silence_realtime(monkeypatch)
+ _patch_runners(monkeypatch)
+ client = TestClient(_build_app())
+
+ resp = client.post("/api/v1/cases/CASE-001/triage", json=_multi_signal_payload())
+ assert resp.status_code == 200, resp.text
+ body = resp.json()
+ assert body["status"] == "running"
+ assert body["topology"] == "parallel"
+ assert body["case_id"] == "CASE-001"
+ assert isinstance(body["run_id"], str)
+
+
+def test_flag_off_runs_sequential_topology(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Flag set to a falsy value → sequential topology selected."""
+ monkeypatch.setenv(PARALLEL_TOPOLOGY_FLAG, "0")
+ _silence_realtime(monkeypatch)
+ _patch_runners(monkeypatch)
+ client = TestClient(_build_app())
+
+ resp = client.post("/api/v1/cases/CASE-002/triage", json=_multi_signal_payload())
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["topology"] == "sequential"
+
+ final = _poll_until_done(client, resp.json()["run_id"])
+ assert final["topology"] == "sequential"
+
+
+def test_explicit_topology_override_beats_env_flag(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Body-level ``topology`` override wins even when env flag disagrees."""
+ monkeypatch.setenv(PARALLEL_TOPOLOGY_FLAG, "0") # env says sequential
+ _silence_realtime(monkeypatch)
+ _patch_runners(monkeypatch)
+ client = TestClient(_build_app())
+
+ body = _multi_signal_payload()
+ body["topology"] = "parallel"
+ resp = client.post("/api/v1/cases/CASE-003/triage", json=body)
+ assert resp.status_code == 200
+ assert resp.json()["topology"] == "parallel"
+
+ final = _poll_until_done(client, resp.json()["run_id"])
+ assert final["topology"] == "parallel"
+
+
+def test_invalid_topology_value_returns_400(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _silence_realtime(monkeypatch)
+ _patch_runners(monkeypatch)
+ client = TestClient(_build_app())
+
+ body = _multi_signal_payload()
+ body["topology"] = "diagonal"
+ resp = client.post("/api/v1/cases/CASE-004/triage", json=body)
+ assert resp.status_code == 400
+ assert "diagonal" in resp.json()["detail"]
+
+
+# ---------------------------------------------------------------------------
+# End-to-end flow — POST + poll → completed run with router telemetry
+# ---------------------------------------------------------------------------
+
+
+def test_run_completes_and_exposes_router_telemetry(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Parallel run should expose verdict, signals, MITRE, wall-clock ms."""
+ monkeypatch.delenv(PARALLEL_TOPOLOGY_FLAG, raising=False)
+ _silence_realtime(monkeypatch)
+ _patch_runners(monkeypatch)
+ client = TestClient(_build_app())
+
+ resp = client.post("/api/v1/cases/CASE-005/triage", json=_multi_signal_payload())
+ assert resp.status_code == 200
+ run_id = resp.json()["run_id"]
+
+ final = _poll_until_done(client, run_id)
+
+ assert final["status"] == "completed"
+ assert final["topology"] == "parallel"
+ assert final["verdict"] == "true_positive"
+ assert set(final["signals"]) == {"phishing", "identity", "cloud", "insider"}
+ # All four sub-agents fanned out → their techniques are present.
+ assert {"T1566.001", "T1078", "T1078.004", "T1567.002"}.issubset(set(final["mitre_mappings"]))
+ # Telemetry: wall-clock recorded as a non-negative number.
+ assert isinstance(final.get("wall_clock_ms"), int | float)
+ assert final["wall_clock_ms"] >= 0
+
+
+def test_auto_close_short_circuits_router(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """High-confidence benign verdict during auto-triage skips sub-agents."""
+ monkeypatch.delenv(PARALLEL_TOPOLOGY_FLAG, raising=False)
+ _silence_realtime(monkeypatch)
+ _patch_runners(monkeypatch, auto_close=True)
+ client = TestClient(_build_app())
+
+ resp = client.post("/api/v1/cases/CASE-006/triage", json=_multi_signal_payload())
+ assert resp.status_code == 200
+ run_id = resp.json()["run_id"]
+
+ final = _poll_until_done(client, run_id)
+ assert final["status"] == "completed"
+ assert final["verdict"] == "benign"
+ assert final["auto_closed"] is True
+ assert final["signals"] == [] # no fan-out
+
+
+# ---------------------------------------------------------------------------
+# Error surfaces
+# ---------------------------------------------------------------------------
+
+
+def test_get_unknown_run_id_returns_404(monkeypatch: pytest.MonkeyPatch) -> None:
+ _silence_realtime(monkeypatch)
+ client = TestClient(_build_app())
+
+ resp = client.get(f"/api/v1/triage/{uuid4()}")
+ assert resp.status_code == 404
+ assert resp.json()["detail"] == "Triage run not found"
+
+
+def test_post_accepts_minimal_body_with_only_case_path(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Empty body should not blow up — endpoint coerces defaults."""
+ monkeypatch.delenv(PARALLEL_TOPOLOGY_FLAG, raising=False)
+ _silence_realtime(monkeypatch)
+ _patch_runners(monkeypatch)
+ client = TestClient(_build_app())
+
+ resp = client.post("/api/v1/cases/CASE-007/triage", json={})
+ assert resp.status_code == 200, resp.text
+ body = resp.json()
+ assert body["topology"] == "parallel"
+ assert body["case_id"] == "CASE-007"
+
+
+# ---------------------------------------------------------------------------
+# Tenant isolation on GET — regression for PR review item
+# (https://github.com/beenuar/AiSOC/pull/139)
+# ---------------------------------------------------------------------------
+
+
+def test_get_with_mismatched_tenant_returns_404(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A caller from tenant B must not see runs launched by tenant A.
+
+ The handler returns 404 (not 403) on mismatch so a probing caller
+ can't distinguish "wrong tenant" from "no such run" — same shape as
+ the unknown-run-id branch above.
+ """
+ monkeypatch.delenv(PARALLEL_TOPOLOGY_FLAG, raising=False)
+ _silence_realtime(monkeypatch)
+ _patch_runners(monkeypatch)
+ client = TestClient(_build_app())
+
+ # Launch a run as tenant "acme".
+ resp = client.post(
+ "/api/v1/cases/CASE-TENANT-A/triage",
+ json={**_multi_signal_payload(), "tenant_id": "acme"},
+ )
+ assert resp.status_code == 200, resp.text
+ run_id = resp.json()["run_id"]
+
+ # Owning tenant gets 200.
+ own = client.get(f"/api/v1/triage/{run_id}", params={"tenant_id": "acme"})
+ assert own.status_code == 200, own.text
+ assert own.json()["tenant_id"] == "acme"
+
+ # Different tenant gets 404, NOT 200 with the other tenant's findings.
+ other = client.get(f"/api/v1/triage/{run_id}", params={"tenant_id": "evilcorp"})
+ assert other.status_code == 404
+ assert other.json()["detail"] == "Triage run not found"
+
+ # Absent tenant_id falls back to "default" and still 404s — fail closed.
+ no_tenant = client.get(f"/api/v1/triage/{run_id}")
+ assert no_tenant.status_code == 404
+ assert no_tenant.json()["detail"] == "Triage run not found"