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.

fix(api): the rail's business-context leg reads the event the writer writes (#1579)

Beenu Arora1a9d86dbc9ff
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cff3ae636..46d5d8810 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -69,6 +69,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- **The rail's business-context leg reads the event the writer actually
+ writes.** Its query filtered `kind LIKE 'auto_triage:%'` while the ledger's
+ verdict INSERT hardcodes `kind = 'triage_verdict'` (the `auto_triage:{tier}`
+ string lives in the `agent` column) — so the section could never render on
+ a real deployment while every suite stayed green, because the live test had
+ seeded the assumed shape rather than the writer's. Found by the end-to-end
+ QA slice (console rule row -> real worker -> real ledger -> rail), fixed,
+ and the literal is now pinned on both sides: the writer's recording-pool
+ test asserts the executed INSERT carries `'triage_verdict'` and the
+ business keys land in the payload, and the reader's live test seeds that
+ same literal.
+
- **The context graph's business dimension authenticates.** The bundle's
incident-context fetch sent `X-Tenant-ID` (a header the API's auth never
reads) with an optional `AISOC_AGENTS_API_KEY` bearer that no compose
diff --git a/services/agents/tests/test_auto_triage_ledger_records_the_prompt.py b/services/agents/tests/test_auto_triage_ledger_records_the_prompt.py
index 98abdbf90..e92cd2b8a 100644
--- a/services/agents/tests/test_auto_triage_ledger_records_the_prompt.py
+++ b/services/agents/tests/test_auto_triage_ledger_records_the_prompt.py
@@ -236,6 +236,107 @@ class TestTheLedgerWritesIt:
)
return executed
+ @staticmethod
+ async def _run_with_business(business_context: dict | None, business_impact: dict | None) -> list[tuple[str, tuple]]:
+ """Same recording pool, with the business-context kwargs supplied."""
+ from app.investigator import ledger as ledger_module
+
+ executed: list[tuple[str, tuple]] = []
+ tenant = uuid4()
+
+ class _Conn:
+ async def execute(self, sql: str, *args: Any) -> str:
+ executed.append((sql, args))
+ return "INSERT 0 1"
+
+ async def fetchval(self, *_a: Any, **_k: Any) -> Any:
+ return tenant
+
+ def transaction(self) -> Any:
+ return _Txn()
+
+ class _Txn:
+ async def __aenter__(self) -> None:
+ return None
+
+ async def __aexit__(self, *_a: Any) -> bool:
+ return False
+
+ class _Acquire:
+ async def __aenter__(self) -> _Conn:
+ return _Conn()
+
+ async def __aexit__(self, *_a: Any) -> bool:
+ return False
+
+ class _Pool:
+ def acquire(self) -> _Acquire:
+ return _Acquire()
+
+ async def _pool() -> _Pool:
+ return _Pool()
+
+ async def _resolve(_conn: Any, _ref: str) -> Any:
+ return tenant
+
+ with pytest.MonkeyPatch.context() as mp:
+ mp.setattr(ledger_module, "get_pool", _pool)
+ mp.setattr(ledger_module, "_resolve_tenant_id", _resolve)
+ await ledger_module.persist_auto_triage(
+ run_id=uuid4(),
+ alert_id=str(uuid4()),
+ tenant_ref=str(tenant),
+ alert_summary="s",
+ raw_alert={},
+ tier="L1",
+ verdict="true_positive",
+ confidence=0.9,
+ rationale="because",
+ business_context=business_context,
+ business_impact=business_impact,
+ )
+ return executed
+
+ @staticmethod
+ def _verdict_payload(executed: list[tuple[str, tuple]]) -> dict:
+ """The JSONB payload bound into the verdict-event INSERT."""
+ for sql, args in executed:
+ if "triage_verdict" not in sql:
+ continue
+ for arg in args:
+ if isinstance(arg, str) and '"verdict"' in arg:
+ return json.loads(arg)
+ raise AssertionError("no verdict-event INSERT with a payload was executed")
+
+ @pytest.mark.asyncio
+ async def test_the_verdict_event_kind_is_the_literal_the_rail_reads(self) -> None:
+ """Cross-service pin, writer side. The rail's business-context leg
+ (`services/api/app/services/alert_rail.py`) filters
+ `kind = 'triage_verdict'`, and its live test seeds that same literal.
+ The reader's first version filtered `kind LIKE 'auto_triage:%'`, a
+ shape no real event ever had, so the rail section could never render
+ on a real deployment while every suite stayed green. If this literal
+ is ever renamed, this test and the rail must move together."""
+ executed = await self._run_with_business(None, None)
+ verdict_inserts = [s for s, _ in executed if "INSERT INTO investigation_events" in s and "'triage_verdict'" in s]
+ assert verdict_inserts, "the verdict event must be written with the literal kind 'triage_verdict'"
+
+ @pytest.mark.asyncio
+ async def test_business_context_and_impact_land_in_the_payload(self) -> None:
+ bc = {"matched_rule_ids": ["dc-critical"], "severity_before": "medium", "severity_after": "critical"}
+ impact = {"statement": "Payment path at risk", "citations": ["dc-critical"]}
+ payload = self._verdict_payload(await self._run_with_business(bc, impact))
+ assert payload["business_context"] == bc
+ assert payload["business_impact"] == impact
+
+ @pytest.mark.asyncio
+ async def test_absent_business_keys_stay_absent_not_null(self) -> None:
+ """Absence is the record that nothing matched — a null would read as
+ an older event predating the field."""
+ payload = self._verdict_payload(await self._run_with_business(None, None))
+ assert "business_context" not in payload
+ assert "business_impact" not in payload
+
@pytest.mark.asyncio
async def test_the_verdict_insert_names_both_hash_columns(self) -> None:
executed = await self._run([])
diff --git a/services/api/app/services/alert_rail.py b/services/api/app/services/alert_rail.py
index 65313ff89..df6cedcfb 100644
--- a/services/api/app/services/alert_rail.py
+++ b/services/api/app/services/alert_rail.py
@@ -603,6 +603,15 @@ async def fetch_business_context(db: AsyncSession, alert: Alert) -> BusinessCont
own, so the join goes through the run). Both tables are filtered by
tenant in the query — RLS stays defence-in-depth, not the control.
"""
+ # `kind = 'triage_verdict'` is the literal the writer uses — the verdict
+ # INSERT in `services/agents/app/investigator/ledger.py` hardcodes it,
+ # with `agent` carrying `auto_triage:{tier}`. The first cut of this query
+ # filtered `kind LIKE 'auto_triage:%'`, a shape no real event has ever
+ # had, so the rail section could never render on a real deployment while
+ # every suite stayed green — the live test had seeded the assumed shape
+ # rather than the writer's. Found by the end-to-end QA slice; the literal
+ # is now pinned on both sides (the writer's recording-pool test and the
+ # live test here, naming the same string).
stmt = sa_text(
"""
SELECT e.payload
@@ -611,7 +620,7 @@ async def fetch_business_context(db: AsyncSession, alert: Alert) -> BusinessCont
WHERE r.tenant_id = :tenant_id
AND e.tenant_id = :tenant_id
AND r.case_id = :alert_ref
- AND e.kind LIKE 'auto_triage:%'
+ AND e.kind = 'triage_verdict'
AND (e.payload -> 'business_context' IS NOT NULL
OR e.payload -> 'business_impact' IS NOT NULL)
ORDER BY e.created_at DESC
diff --git a/services/api/tests/test_alert_rail_business_context_live.py b/services/api/tests/test_alert_rail_business_context_live.py
index fe710cdb0..cc5c43b98 100644
--- a/services/api/tests/test_alert_rail_business_context_live.py
+++ b/services/api/tests/test_alert_rail_business_context_live.py
@@ -88,7 +88,19 @@ def _alert(tenant: uuid.UUID) -> Alert:
)
-async def _seed_run_and_event(db, *, tenant: uuid.UUID, alert_id: uuid.UUID, payload: dict, kind: str = "auto_triage:fast") -> None:
+async def _seed_run_and_event(db, *, tenant: uuid.UUID, alert_id: uuid.UUID, payload: dict, kind: str = "triage_verdict") -> None:
+ """Seed exactly the shape `persist_auto_triage` writes.
+
+ `kind` is the literal `'triage_verdict'` and `agent` carries
+ `auto_triage:{tier}` — read off the writer's own INSERT in
+ `services/agents/app/investigator/ledger.py` and pinned there by its
+ recording-pool test. The first version of this seeding invented
+ `kind='auto_triage:fast'`, a shape no real event ever had, which let the
+ reader filter on the same invented shape and ship a rail section that
+ could never render on a real deployment — the test double was more
+ capable than the real writer. Seed the writer's shape, never an assumed
+ one.
+ """
run_id = uuid.uuid4()
await db.execute(
text(
@@ -103,7 +115,7 @@ async def _seed_run_and_event(db, *, tenant: uuid.UUID, alert_id: uuid.UUID, pay
text(
"""
INSERT INTO investigation_events (id, run_id, tenant_id, seq, ts, kind, agent, summary, payload, created_at)
- VALUES (:id, :run_id, :tenant_id, 1, now(), :kind, 'auto_triage', 'verdict', CAST(:payload AS jsonb), now())
+ VALUES (:id, :run_id, :tenant_id, 1, now(), :kind, 'auto_triage:fast', 'verdict', CAST(:payload AS jsonb), now())
"""
),
{"id": uuid.uuid4(), "run_id": run_id, "tenant_id": tenant, "kind": kind, "payload": json.dumps(payload)},