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): wire DetectAgent.process to FusionEngine via cross-service HTTP (#190) (#198)

Beenu Arorafddbf2b54285
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ff9f87fac..ab394c282 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -199,12 +199,21 @@ jobs:
SECRET_KEY: ci-dummy-secret-key-at-least-32bytes!
DATABASE_URL: postgresql+asyncpg://x:x@localhost/x
run: python -m pytest tests/ -v --tb=short
- - name: Run agents unit tests (Pillar-1 eval suites + audit helpers)
+ - name: Run agents unit tests (Pillar-1 eval suites + audit helpers + fusion client)
# `test_audit_helpers.py` imports `app.investigator.state` directly
# (it stubs out the package __init__ to avoid pulling in LangGraph),
# so it only needs stdlib + pydantic — already installed via API_DEPS.
+ # `test_fusion_client.py` (Issue #190) exercises the thin httpx
+ # client that wires `DetectAgent.process` to the fusion service's
+ # `POST /process` endpoint; it mocks the network with respx so the
+ # suite stays offline-safe. The test imports `DetectAgent` from
+ # `app.agents`, which transitively loads sibling sub-agents
+ # (auto_triage / phishing / identity / insider_threat / cloud) that
+ # import `langchain_core` and `langchain_openai` at module scope —
+ # so both packages are required at import time, even though the
+ # fusion-client test itself only calls into `app.tools.fusion`.
run: |
- pip install --quiet pytest pytest-asyncio
+ pip install --quiet pytest pytest-asyncio respx langchain-core langchain-openai
cd services/agents
python3 -m pytest \
tests/test_mitre_accuracy.py \
@@ -212,16 +221,20 @@ jobs:
tests/test_investigation_completeness.py \
tests/test_response_quality.py \
tests/test_audit_helpers.py \
+ tests/test_fusion_client.py \
-v --tb=short
# ──────────────────────────────────────────────
# Python micro-services unit tests
# `services/fusion`, `services/honeytokens`, and `services/purple-team`
# used to ship with no Python tests gated in CI at all — only ruff +
- # format check. These suites cover the *pure* helpers in each service
+ # format check. These suites cover the pure helpers in each service
# (alert fingerprinting/correlation keys, honeytoken generators,
- # ATT&CK coverage matrix builder) — they need pydantic/pydantic-settings
- # only, no Postgres, Redis, or Kafka. Real signal, fast.
+ # ATT&CK coverage matrix builder) plus the thin FastAPI router contracts
+ # that don't need Postgres / Kafka / Redis to exercise (e.g. the
+ # fusion service's ``POST /process`` endpoint added in Issue #190,
+ # which uses an injected fake worker via ``set_worker(...)``). Real
+ # signal, fast — no service boot required.
# ──────────────────────────────────────────────
python-services-test:
name: Python — Service unit tests (fusion, honeytokens, purple-team)
@@ -234,7 +247,17 @@ jobs:
python-version: '3.12'
cache: pip
- name: Install minimal deps
- run: pip install --quiet pydantic pydantic-settings pytest pytest-asyncio structlog redis aioredis
+ # ``fastapi`` + ``httpx`` are required by the fusion router-contract
+ # tests (Issue #190): they import ``app.api.router`` and drive it
+ # with FastAPI's ``ASGITransport`` + ``httpx.AsyncClient``. ``aiokafka``
+ # is needed because ``app/api/router.py`` exposes ``set_worker(...)``
+ # which type-references ``FusionWorker`` from ``app.workers.consumer``;
+ # importing the router module therefore eagerly evaluates the
+ # consumer module, which itself imports ``aiokafka`` at module scope.
+ # We deliberately do NOT install the full API dep set here — the goal
+ # of this job stays "pure helpers + thin router contracts, no
+ # service boot, no Postgres/Kafka/Redis".
+ run: pip install --quiet pydantic pydantic-settings pytest pytest-asyncio structlog redis aioredis fastapi httpx aiokafka
- name: Run fusion unit tests
working-directory: services/fusion
run: python -m pytest tests/ -v --tb=short
diff --git a/services/agents/app/agents/__init__.py b/services/agents/app/agents/__init__.py
index dbb4ca0f8..06d95d935 100644
--- a/services/agents/app/agents/__init__.py
+++ b/services/agents/app/agents/__init__.py
@@ -31,6 +31,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING, Any, ClassVar
+from ..tools.fusion import process_alert as _fusion_process_alert
from .auto_triage_agent import run_auto_triage as _run_auto_triage
from .cloud_agent import run_cloud as _run_cloud
from .enrichment_agent import run_enrichment as _run_enrichment
@@ -107,18 +108,14 @@ class DetectAgent:
* ``detections/`` + ``services/api/app/services/detection_*`` — the
native rule corpus (Sigma / KQL / EQL / SPL / DAC).
- A live ``DetectAgent.process(...)`` method that drives the fusion
- pipeline from inside the agents service is **in flight**: cross-service
- wiring would require a stable client into ``services/fusion``. Until
- that lands, this class exists as the public branding anchor — the four
- branded names are exactly four — and exposes ``capabilities()`` for
- introspection so the docs site, onboarding tour, and tests can rely on
- a consistent description.
-
- TODO(v8.0/T2.5): wire ``DetectAgent.process`` to the
- ``services.fusion.app.services.fusion_engine.FusionEngine`` once a thin
- cross-service client is added (tracked separately so this façade can
- ship independently).
+ ``DetectAgent.process(raw_alert)`` drives the full fusion pipeline
+ (dedup, correlation, ML scoring, confidence labelling, RBA) via the
+ fusion service's ``POST /process`` endpoint
+ (``http://fusion:8003/process`` in the docker-compose network). The
+ HTTP client lives at :mod:`app.tools.fusion`. The same
+ ``FusionEngine`` instance backs both this synchronous path and the
+ Kafka consumer path, so behaviour is identical regardless of how
+ alerts arrive.
"""
name: ClassVar[str] = "Detect"
@@ -132,6 +129,47 @@ class DetectAgent:
def capabilities(cls) -> tuple[str, ...]:
return ("fusion", "entity_risk", "native_detections")
+ @classmethod
+ async def process(
+ cls,
+ raw_alert: dict[str, Any],
+ *,
+ api_token: str | None = None,
+ ) -> dict[str, Any]:
+ """Run a raw alert through the full detection / fusion pipeline.
+
+ This is the public synchronous detection entrypoint for callers
+ outside the fusion service. It delegates to the fusion service
+ over HTTP (see :mod:`app.tools.fusion`), so the same engine that
+ services the Kafka consumer path also services this call —
+ dedup, correlation, ML scoring, confidence labelling, RBA, and
+ narrative generation all run with shared state.
+
+ The input is intentionally typed as a plain dict rather than a
+ Pydantic ``RawAlert``: this keeps the agents service decoupled
+ from the fusion service's schema module, and the fusion service
+ validates the payload on its boundary regardless. The dict must
+ match the shape of ``services.fusion.app.models.alert.RawAlert``.
+
+ Args:
+ raw_alert: ``RawAlert``-shaped dict.
+ api_token: Optional bearer token forwarded to the fusion service.
+
+ Returns:
+ ``FusedAlert``-shaped dict including ``fusion_decision``,
+ ``incident_id``, ``priority_score``, ``confidence_label``,
+ and the original alert envelope.
+
+ Raises:
+ httpx.HTTPStatusError: Fusion service returned non-2xx
+ (e.g. 503 if the fusion worker is not yet ready, 422 on a
+ malformed payload).
+ httpx.HTTPError: Transport-level failure (timeout, connect
+ error, etc.). Failures propagate intentionally: silent
+ failure on the detection plane would lose alerts.
+ """
+ return await _fusion_process_alert(raw_alert, api_token=api_token)
+
@classmethod
def describe(cls) -> dict[str, Any]:
return {
diff --git a/services/agents/app/tools/fusion.py b/services/agents/app/tools/fusion.py
new file mode 100644
index 000000000..11b6622a1
--- /dev/null
+++ b/services/agents/app/tools/fusion.py
@@ -0,0 +1,102 @@
+"""
+Tool: synchronous fusion-pipeline calls via the fusion service.
+
+Wraps ``POST /process`` on the fusion service
+(``http://fusion:8003/process`` inside the docker-compose network — the
+fusion service mounts its router at the root path, not under
+``/api/fusion``). The agents service's ``DetectAgent`` uses this to
+drive the full fusion pipeline (deduplication, correlation, ML scoring,
+confidence labelling, RBA) from a single HTTP call without standing up
+a Kafka producer.
+
+Contract note (Issue #190): unlike ``app.tools.graph`` — which is used
+for *investigation* graph queries and intentionally degrades gracefully
+(returns ``{"error": ..., "nodes": [], ...}``) so an in-flight
+investigation can continue with partial data — this tool **raises** on
+any transport or HTTP failure. Fusion is the primary detection
+pipeline: if it fails, the caller MUST know, otherwise alerts disappear
+silently and downstream consumers would treat a synthetic error
+envelope as a real verdict.
+"""
+
+from __future__ import annotations
+
+import os
+from typing import Any
+
+import httpx
+import structlog
+
+logger = structlog.get_logger()
+
+_DEFAULT_FUSION_URL = "http://fusion:8003"
+_DEFAULT_TIMEOUT = "15.0"
+
+
+def _fusion_url() -> str:
+ # Read at call time so tests (and dynamic redeploys) can override
+ # ``FUSION_SERVICE_URL`` without reloading the module.
+ return os.getenv("FUSION_SERVICE_URL", _DEFAULT_FUSION_URL)
+
+
+def _timeout() -> float:
+ return float(os.getenv("AGENTS_FUSION_TIMEOUT", _DEFAULT_TIMEOUT))
+
+
+def _headers(api_token: str | None) -> dict[str, str]:
+ return {"Authorization": f"Bearer {api_token}"} if api_token else {}
+
+
+async def process_alert(
+ raw_alert: dict[str, Any],
+ api_token: str | None = None,
+) -> dict[str, Any]:
+ """Run a raw alert through the fusion pipeline and return the fused alert.
+
+ Args:
+ raw_alert: A ``RawAlert``-shaped dict (matching the fusion service's
+ Pydantic model). The fusion service validates the schema, so we
+ keep the agent-side boundary as plain dicts to avoid coupling
+ this service to the fusion service's Pydantic models.
+ api_token: Optional bearer token forwarded to the fusion service.
+
+ Returns:
+ The ``FusedAlert``-shaped dict produced by the fusion engine.
+ Includes ``fusion_decision`` (NEW/CORRELATED/DUPLICATE),
+ ``incident_id``, ``priority_score``, ``confidence_label``, and the
+ original alert envelope.
+
+ Raises:
+ httpx.HTTPStatusError: The fusion service returned a non-2xx
+ response (e.g. 503 when the worker is not yet ready, 422 on a
+ malformed payload).
+ httpx.HTTPError: Any transport-level failure (timeout, connect
+ error, etc.).
+ """
+ url = f"{_fusion_url()}/process"
+ try:
+ async with httpx.AsyncClient(timeout=_timeout()) as client:
+ resp = await client.post(
+ url,
+ json=raw_alert,
+ headers=_headers(api_token),
+ )
+ resp.raise_for_status()
+ return resp.json()
+ except httpx.HTTPStatusError as exc:
+ logger.error(
+ "fusion process_alert returned non-2xx",
+ url=url,
+ status_code=exc.response.status_code,
+ body=exc.response.text[:500],
+ alert_id=raw_alert.get("id"),
+ )
+ raise
+ except httpx.HTTPError as exc:
+ logger.error(
+ "fusion process_alert transport failure",
+ url=url,
+ error=str(exc),
+ alert_id=raw_alert.get("id"),
+ )
+ raise
diff --git a/services/agents/tests/test_fusion_client.py b/services/agents/tests/test_fusion_client.py
new file mode 100644
index 000000000..b366e85f6
--- /dev/null
+++ b/services/agents/tests/test_fusion_client.py
@@ -0,0 +1,300 @@
+"""
+Unit tests for ``app.tools.fusion`` — the HTTP client that drives the
+fusion service's ``POST /process`` endpoint (Issue #190).
+
+We mock the network with :mod:`respx` so the suite stays offline-safe.
+Contract being locked in:
+
+* happy path: the client posts the raw alert as JSON to
+ ``{FUSION_SERVICE_URL}/process`` and returns the response body as a
+ dict.
+* the URL is built from ``FUSION_SERVICE_URL`` (default
+ ``http://fusion:8003``) plus the ``/process`` suffix — *not*
+ ``/api/fusion/process``. This is the regression guard for the path
+ mismatch we caught during initial wiring.
+* an optional ``api_token`` is forwarded as a Bearer header.
+* non-2xx responses raise :class:`httpx.HTTPStatusError` (we MUST NOT
+ swallow fusion failures — see the module docstring rationale).
+* transport failures raise :class:`httpx.HTTPError`.
+
+We also lock in ``DetectAgent.process`` as a thin delegate to this
+client: it must pass through ``raw_alert`` and ``api_token`` unchanged
+and return whatever the client returns.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+from typing import Any
+
+import httpx
+import pytest
+import respx
+
+# Match the path-mutation pattern used by the rest of services/agents/tests/.
+_AGENTS_ROOT = Path(__file__).resolve().parents[1]
+if str(_AGENTS_ROOT) not in sys.path:
+ sys.path.insert(0, str(_AGENTS_ROOT))
+
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
+def raw_alert() -> dict[str, Any]:
+ """Minimal ``RawAlert``-shaped dict the fusion service would accept."""
+ return {
+ "id": "alert-fixture-1",
+ "tenant_id": "tenant-a",
+ "source": "edr",
+ "severity": "high",
+ "title": "Suspicious PowerShell encoded command",
+ "description": "Powershell -enc base64...",
+ "timestamp": "2026-05-19T12:00:00Z",
+ "raw_fields": {"host": "lab-1", "user": "alice"},
+ }
+
+
+def fused_alert(raw_alert: dict[str, Any]) -> dict[str, Any]:
+ """A representative ``FusedAlert`` envelope as returned by /process."""
+ return {
+ "alert": raw_alert,
+ "fusion_decision": "NEW_INCIDENT",
+ "incident_id": "inc-fixture-1",
+ "priority_score": 0.72,
+ "confidence_label": "high",
+ }
+
+
+def fusion_url(monkeypatch: pytest.MonkeyPatch) -> str:
+ """Pin ``FUSION_SERVICE_URL`` to a deterministic value for the test."""
+ url = "http://fusion-test:8003"
+ monkeypatch.setenv("FUSION_SERVICE_URL", url)
+ # The module reads the env at import time, so reload it under the
+ # patched env.
+ import importlib
+
+ import app.tools.fusion as fusion_module
+
+ importlib.reload(fusion_module)
+ return url
+
+
+# ---------------------------------------------------------------------------
+# Happy path
+# ---------------------------------------------------------------------------
+
+
+async def test_process_alert_posts_to_root_process_endpoint(
+ raw_alert: dict[str, Any],
+ fused_alert: dict[str, Any],
+ fusion_url: str,
+) -> None:
+ """Client must hit ``/process`` at the root, **not** ``/api/fusion/process``.
+
+ Regression guard: the agents service's ``DetectAgent.process`` reached
+ a 404 in early wiring because the client was posting to a stale path
+ that didn't match where the fusion service mounts its router. The
+ test fails loudly if anyone reintroduces that mismatch.
+ """
+ from app.tools.fusion import process_alert
+
+ async with respx.mock(base_url=fusion_url, assert_all_called=True) as router:
+ route = router.post("/process").mock(
+ return_value=httpx.Response(200, json=fused_alert),
+ )
+
+ result = await process_alert(raw_alert)
+
+ assert result == fused_alert
+ assert route.called
+ # The request body is exactly the raw alert we passed in — the client
+ # is a thin pass-through, not a transformer.
+ assert route.calls.last.request.read() == httpx.Request("POST", f"{fusion_url}/process", json=raw_alert).read()
+
+
+async def test_process_alert_forwards_bearer_token(
+ raw_alert: dict[str, Any],
+ fused_alert: dict[str, Any],
+ fusion_url: str,
+) -> None:
+ """An ``api_token`` arg is forwarded as ``Authorization: Bearer ...``.
+
+ The fusion service can enforce auth on ``/process``; the agents-side
+ client must pass through the caller's token unmodified.
+ """
+ from app.tools.fusion import process_alert
+
+ async with respx.mock(base_url=fusion_url, assert_all_called=True) as router:
+ route = router.post("/process").mock(
+ return_value=httpx.Response(200, json=fused_alert),
+ )
+
+ await process_alert(raw_alert, api_token="tok-123")
+
+ assert route.calls.last.request.headers["authorization"] == "Bearer tok-123"
+
+
+async def test_process_alert_no_token_omits_authorization_header(
+ raw_alert: dict[str, Any],
+ fused_alert: dict[str, Any],
+ fusion_url: str,
+) -> None:
+ """When no token is provided we MUST NOT send a bare/blank Bearer header.
+
+ A blank Authorization header would force the fusion service to reject
+ legitimate unauthenticated calls; this test pins the "absent is
+ absent" contract.
+ """
+ from app.tools.fusion import process_alert
+
+ async with respx.mock(base_url=fusion_url, assert_all_called=True) as router:
+ route = router.post("/process").mock(
+ return_value=httpx.Response(200, json=fused_alert),
+ )
+
+ await process_alert(raw_alert)
+
+ assert "authorization" not in {k.lower() for k in route.calls.last.request.headers}
+
+
+# ---------------------------------------------------------------------------
+# Error handling — fusion failures MUST propagate
+# ---------------------------------------------------------------------------
+
+
+async def test_process_alert_raises_on_503_when_worker_not_ready(
+ raw_alert: dict[str, Any],
+ fusion_url: str,
+) -> None:
+ """A 503 from the fusion worker MUST raise ``HTTPStatusError``.
+
+ Per the module docstring, the fusion plane is the primary detection
+ path: if it's down, callers must know. Silently swallowing the error
+ and returning a fake envelope would lose alerts.
+ """
+ from app.tools.fusion import process_alert
+
+ async with respx.mock(base_url=fusion_url) as router:
+ router.post("/process").mock(
+ return_value=httpx.Response(503, json={"detail": "Fusion worker not ready"}),
+ )
+
+ with pytest.raises(httpx.HTTPStatusError) as exc_info:
+ await process_alert(raw_alert)
+
+ assert exc_info.value.response.status_code == 503
+
+
+async def test_process_alert_raises_on_422_for_malformed_payload(
+ fusion_url: str,
+) -> None:
+ """A 422 from FastAPI validation MUST raise ``HTTPStatusError``.
+
+ Garbage in, loud failure out. The agent that called us needs the
+ feedback to fix its payload, not a silent ``None``.
+ """
+ from app.tools.fusion import process_alert
+
+ async with respx.mock(base_url=fusion_url) as router:
+ router.post("/process").mock(
+ return_value=httpx.Response(422, json={"detail": "validation error"}),
+ )
+
+ with pytest.raises(httpx.HTTPStatusError) as exc_info:
+ await process_alert({"not": "a real alert"})
+
+ assert exc_info.value.response.status_code == 422
+
+
+async def test_process_alert_raises_on_transport_failure(
+ raw_alert: dict[str, Any],
+ fusion_url: str,
+) -> None:
+ """A transport-level failure (connect error, timeout) MUST propagate.
+
+ We assert the broader ``httpx.HTTPError`` so the test stays stable
+ across the specific exception type httpx picks for a side-effect
+ (it varies between connect errors and timeouts).
+ """
+ from app.tools.fusion import process_alert
+
+ async with respx.mock(base_url=fusion_url) as router:
+ router.post("/process").mock(side_effect=httpx.ConnectError("boom"))
+
+ with pytest.raises(httpx.HTTPError):
+ await process_alert(raw_alert)
+
+
+# ---------------------------------------------------------------------------
+# DetectAgent.process — delegate contract
+# ---------------------------------------------------------------------------
+
+
+async def test_detect_agent_process_delegates_to_fusion_client(
+ raw_alert: dict[str, Any],
+ fused_alert: dict[str, Any],
+ fusion_url: str,
+) -> None:
+ """``DetectAgent.process`` is a thin façade over ``process_alert``.
+
+ The public agent surface promises that ``DetectAgent.process`` runs
+ the full fusion pipeline; the implementation route is the HTTP client
+ above. This test guards that contract end-to-end with a mocked HTTP
+ transport so we exercise the *actual* code path the production
+ DetectAgent uses, not a monkeypatched stub.
+ """
+ from app.agents import DetectAgent
+
+ async with respx.mock(base_url=fusion_url, assert_all_called=True) as router:
+ router.post("/process").mock(
+ return_value=httpx.Response(200, json=fused_alert),
+ )
+
+ result = await DetectAgent.process(raw_alert)
+
+ assert result == fused_alert
+
+
+async def test_detect_agent_process_forwards_api_token(
+ raw_alert: dict[str, Any],
+ fused_alert: dict[str, Any],
+ fusion_url: str,
+) -> None:
+ """The keyword-only ``api_token`` must reach the fusion service."""
+ from app.agents import DetectAgent
+
+ async with respx.mock(base_url=fusion_url, assert_all_called=True) as router:
+ route = router.post("/process").mock(
+ return_value=httpx.Response(200, json=fused_alert),
+ )
+
+ await DetectAgent.process(raw_alert, api_token="downstream-tok")
+
+ assert route.calls.last.request.headers["authorization"] == "Bearer downstream-tok"
+
+
+async def test_detect_agent_process_propagates_fusion_errors(
+ raw_alert: dict[str, Any],
+ fusion_url: str,
+) -> None:
+ """``DetectAgent.process`` MUST raise when fusion raises.
+
+ A silent fallback here would hide a degraded detection plane behind
+ a green ``DetectAgent`` call — exactly the failure mode the module
+ docstring warns about.
+ """
+ from app.agents import DetectAgent
+
+ async with respx.mock(base_url=fusion_url) as router:
+ router.post("/process").mock(
+ return_value=httpx.Response(500, json={"detail": "oops"}),
+ )
+
+ with pytest.raises(httpx.HTTPStatusError):
+ await DetectAgent.process(raw_alert)
diff --git a/services/fusion/app/api/router.py b/services/fusion/app/api/router.py
index 5eec5be21..a239be0cc 100644
--- a/services/fusion/app/api/router.py
+++ b/services/fusion/app/api/router.py
@@ -55,6 +55,33 @@ async def trigger_retrain():
return result
+# ─────────────────────────────────────────────────────────────────────────────
+# Synchronous fusion entrypoint (Issue #190)
+# ─────────────────────────────────────────────────────────────────────────────
+
+
[email protected]("/process", response_model=FusedAlert)
+async def process_alert(alert: RawAlert) -> FusedAlert:
+ """Run a single ``RawAlert`` through the full fusion pipeline.
+
+ The Kafka consumer path (``FusionWorker``) is still the production
+ ingest route; this synchronous HTTP entrypoint exists so other
+ services — notably the agents service's ``DetectAgent`` — can drive
+ the fusion pipeline directly without standing up a Kafka producer,
+ and so the contract is testable from a regular HTTP client.
+
+ Behaviour matches the Kafka path exactly: the same ``FusionEngine``
+ instance is reused (``_worker_ref.engine``), so deduplication,
+ correlation, ML scoring, confidence labelling, RBA rollups, and
+ narrative generation all run with the same state as the live
+ consumer. A duplicate alert returns a ``FusionDecision.DUPLICATE``
+ envelope; a new alert returns a fully scored ``FusedAlert``.
+ """
+ if _worker_ref is None or _worker_ref.engine is None:
+ raise HTTPException(status_code=503, detail="Fusion worker not ready")
+ return await _worker_ref.engine.process(alert)
+
+
# ─────────────────────────────────────────────────────────────────────────────
# Risk-Based Alerting (entity rollup)
# ─────────────────────────────────────────────────────────────────────────────
diff --git a/services/fusion/tests/test_process_endpoint.py b/services/fusion/tests/test_process_endpoint.py
new file mode 100644
index 000000000..a4ef10f7d
--- /dev/null
+++ b/services/fusion/tests/test_process_endpoint.py
@@ -0,0 +1,289 @@
+"""
+Tests for the synchronous fusion entrypoint ``POST /process`` (Issue #190).
+
+The endpoint exists so other services (notably ``DetectAgent`` in the
+agents service) can drive the fusion pipeline over HTTP without standing
+up a Kafka producer. Behaviour MUST match the Kafka path exactly — same
+``FusionEngine`` instance, same dedup / correlation / scoring semantics.
+
+These tests cover the contract the agents service depends on:
+
+1. The endpoint returns the same ``FusedAlert`` shape the engine emits.
+2. When the worker / engine is not yet ready, callers get a 503.
+3. Malformed payloads fail validation at the FastAPI boundary (422).
+4. The duplicate fast-path is preserved — duplicates return a
+ ``DUPLICATE`` envelope and never run the rest of the pipeline.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock
+from uuid import UUID, uuid4
+
+import pytest
+from app.api.router import router, set_worker
+from app.models.alert import (
+ AlertSeverity,
+ FusedAlert,
+ FusionDecision,
+ RawAlert,
+)
+from fastapi import FastAPI
+from httpx import ASGITransport, AsyncClient
+
+
+def _raw_alert_payload(**overrides: Any) -> dict[str, Any]:
+ """Build a ``RawAlert``-shaped JSON payload for ``POST /process``.
+
+ We deliberately produce a dict (not a ``RawAlert`` instance) because
+ that's what real HTTP callers send. FastAPI validates the payload
+ against the Pydantic model on the boundary, so a passing test here
+ is also a passing test of the wire-level contract.
+ """
+ base: dict[str, Any] = {
+ "tenant_id": str(UUID("11111111-1111-1111-1111-111111111111")),
+ "source": "edr",
+ "title": "Suspicious PowerShell execution",
+ "severity": "high",
+ "src_ip": "10.0.0.42",
+ "hostname": "host-42",
+ "mitre_tactics": ["execution"],
+ "mitre_techniques": ["T1059.001"],
+ }
+ base.update(overrides)
+ return base
+
+
+def _new_incident_fused(alert: RawAlert) -> FusedAlert:
+ """Stand-in ``FusedAlert`` matching the engine's ``NEW_INCIDENT`` output."""
+ return FusedAlert(
+ id=alert.id,
+ tenant_id=alert.tenant_id,
+ incident_id=uuid4(),
+ fusion_decision=FusionDecision.NEW_INCIDENT,
+ duplicate_of=None,
+ alert=alert,
+ )
+
+
+def _duplicate_fused(alert: RawAlert, original_id: UUID) -> FusedAlert:
+ """Stand-in ``FusedAlert`` matching the engine's ``DUPLICATE`` output."""
+ return FusedAlert(
+ id=alert.id,
+ tenant_id=alert.tenant_id,
+ incident_id=None,
+ fusion_decision=FusionDecision.DUPLICATE,
+ duplicate_of=original_id,
+ alert=alert,
+ )
+
+
+def _make_app(worker: Any | None) -> FastAPI:
+ """Build a fresh FastAPI app with the fusion router mounted.
+
+ We rebuild the app per test so the module-level ``_worker_ref`` is
+ explicitly controlled — leaking worker state across tests would
+ couple unrelated cases (e.g. the 503 test would pass spuriously if a
+ previous test left a ready worker behind).
+ """
+ set_worker(worker) if worker is not None else _clear_worker()
+ app = FastAPI()
+ app.include_router(router)
+ return app
+
+
+def _clear_worker() -> None:
+ """Reset the router's module-level worker reference to ``None``.
+
+ ``set_worker`` only accepts a real ``FusionWorker``; for the 503
+ case we need ``_worker_ref`` itself to be ``None``. Touching the
+ module attribute directly is intentional — it's the same mutation
+ the lifespan handler would do in reverse on shutdown.
+ """
+ import app.api.router as router_mod
+
+ router_mod._worker_ref = None # noqa: SLF001 — test seam
+
+
+def _stub_worker(engine_process: AsyncMock | None) -> MagicMock:
+ """Build a ``FusionWorker``-shaped stub with a controllable engine.
+
+ Passing ``engine_process=None`` simulates "worker exists but engine
+ not yet initialised", which the router treats the same as no worker
+ (both return 503). That branch is tested via :func:`_clear_worker`.
+ """
+ worker = MagicMock()
+ if engine_process is None:
+ worker.engine = None
+ else:
+ worker.engine = MagicMock()
+ worker.engine.process = engine_process
+ return worker
+
+
+def client_factory():
+ """Return an async client factory bound to a fresh app per call.
+
+ Using ``ASGITransport`` keeps the test in-process: no real socket,
+ no port allocation, no flake budget. The factory takes the worker
+ stub so each test can express its own readiness scenario.
+ """
+
+ def _factory(worker: Any | None) -> AsyncClient:
+ app = _make_app(worker)
+ transport = ASGITransport(app=app)
+ return AsyncClient(transport=transport, base_url="http://fusion")
+
+ return _factory
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# Happy path: new incident
+# ─────────────────────────────────────────────────────────────────────────────
+
+
+async def test_process_returns_fused_alert_for_new_alert(client_factory):
+ """A novel alert produces a ``NEW_INCIDENT`` envelope from the engine."""
+ payload = _raw_alert_payload()
+ expected = _new_incident_fused(RawAlert(**payload))
+
+ engine_process = AsyncMock(return_value=expected)
+ worker = _stub_worker(engine_process)
+
+ async with client_factory(worker) as client:
+ resp = await client.post("/process", json=payload)
+
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["fusion_decision"] == FusionDecision.NEW_INCIDENT.value
+ assert body["incident_id"] == str(expected.incident_id)
+ assert body["duplicate_of"] is None
+ assert body["tenant_id"] == payload["tenant_id"]
+ # The engine MUST be called exactly once with a parsed RawAlert.
+ engine_process.assert_awaited_once()
+ called_with = engine_process.await_args.args[0]
+ assert isinstance(called_with, RawAlert)
+ assert called_with.title == payload["title"]
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# Duplicate fast-path
+# ─────────────────────────────────────────────────────────────────────────────
+
+
+async def test_process_returns_duplicate_envelope(client_factory):
+ """A duplicate alert produces a ``DUPLICATE`` envelope without an incident.
+
+ This is the contract the agents service depends on: callers must be
+ able to distinguish a fresh incident from a suppressed duplicate
+ purely from the response body, never from a side channel.
+ """
+ payload = _raw_alert_payload()
+ original_id = uuid4()
+ expected = _duplicate_fused(RawAlert(**payload), original_id=original_id)
+
+ worker = _stub_worker(AsyncMock(return_value=expected))
+
+ async with client_factory(worker) as client:
+ resp = await client.post("/process", json=payload)
+
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["fusion_decision"] == FusionDecision.DUPLICATE.value
+ assert body["incident_id"] is None
+ assert body["duplicate_of"] == str(original_id)
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# Readiness gate (503)
+# ─────────────────────────────────────────────────────────────────────────────
+
+
+async def test_process_returns_503_when_worker_not_ready(client_factory):
+ """Before the lifespan handler wires the worker, ``/process`` is 503."""
+ async with client_factory(None) as client:
+ resp = await client.post("/process", json=_raw_alert_payload())
+
+ assert resp.status_code == 503
+ assert "not ready" in resp.json()["detail"].lower()
+
+
+async def test_process_returns_503_when_engine_not_ready(client_factory):
+ """A worker that exists but hasn't built its engine yet is also 503.
+
+ This matches the router's combined check (``worker is None or
+ worker.engine is None``) — both branches must surface the same 503
+ so callers don't need to special-case partial readiness states.
+ """
+ worker = _stub_worker(engine_process=None)
+ async with client_factory(worker) as client:
+ resp = await client.post("/process", json=_raw_alert_payload())
+
+ assert resp.status_code == 503
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# Validation
+# ─────────────────────────────────────────────────────────────────────────────
+
+
+async def test_process_rejects_malformed_payload(client_factory):
+ """Missing required fields fail at the FastAPI boundary with 422.
+
+ The agents-side client treats 4xx as a hard failure (raises) — we
+ rely on this for the "don't lose alerts silently" contract, so
+ pinning the status code here is load-bearing, not cosmetic.
+ """
+ # Missing ``tenant_id``, ``source``, ``title`` — all required.
+ bad_payload = {"severity": "high"}
+
+ worker = _stub_worker(AsyncMock())
+ async with client_factory(worker) as client:
+ resp = await client.post("/process", json=bad_payload)
+
+ assert resp.status_code == 422
+
+
+async def test_process_rejects_invalid_severity(client_factory):
+ """Unknown enum values fail validation rather than silently downgrading."""
+ payload = _raw_alert_payload(severity="catastrophic") # not in the enum
+
+ worker = _stub_worker(AsyncMock())
+ async with client_factory(worker) as client:
+ resp = await client.post("/process", json=payload)
+
+ assert resp.status_code == 422
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# Same engine as Kafka path
+# ─────────────────────────────────────────────────────────────────────────────
+
+
+async def test_process_uses_same_engine_instance_as_worker(client_factory):
+ """The HTTP path delegates to ``_worker_ref.engine.process`` — not a fresh engine.
+
+ Issue #190 explicitly requires that the synchronous HTTP entrypoint
+ and the Kafka consumer share the same engine instance (so dedup
+ state, RBA rollups, and incident grouping are consistent regardless
+ of how an alert arrives). We verify this by making the worker's
+ engine.process the only mock that should be hit.
+ """
+ payload = _raw_alert_payload(severity=AlertSeverity.CRITICAL.value)
+ engine_process = AsyncMock(return_value=_new_incident_fused(RawAlert(**payload)))
+ worker = _stub_worker(engine_process)
+
+ async with client_factory(worker) as client:
+ await client.post("/process", json=payload)
+ await client.post("/process", json=payload)
+
+ assert engine_process.await_count == 2