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: make business-context rules actually reach triage (#672)

Beenu Arora538519a3c3d8
diff --git a/services/agents/app/workers/business_context.py b/services/agents/app/workers/business_context.py
index 819a636b1..4d39820ee 100644
--- a/services/agents/app/workers/business_context.py
+++ b/services/agents/app/workers/business_context.py
@@ -27,6 +27,8 @@ Everything is fail-soft: a missing/invalid rules file or a bad rule degrades to
from __future__ import annotations
import os
+import time
+import uuid
from dataclasses import dataclass
from dataclasses import field as dc_field
from pathlib import Path
@@ -224,15 +226,106 @@ def apply_rules(alert: dict[str, Any], rules: list[BusinessContextRule]) -> Busi
return BusinessContextResult(out, matched, False, severity_before, out.get("severity"))
+#: How long a tenant's rules are cached before re-reading Postgres. Business
+#: context changes rarely and this sits on the hot path for every fused alert.
+_TENANT_CACHE_TTL_SECONDS = 30.0
+
+
class BusinessContextApplier:
- """Loads rules from a YAML file (mtime-reloaded) and applies them."""
+ """Applies business-context rules from Postgres, and from a YAML file.
+
+ Rules authored in the console are stored per tenant in
+ `aisoc_business_context_rule_sets`. This class only ever read a YAML file
+ whose path comes from `AISOC_BUSINESS_CONTEXT_RULES_FILE` — which nothing
+ sets — so a tenant could author a rule ("this host is a domain controller,
+ escalate anything touching it"), see it saved, preview it against their
+ last 50 alerts, and have it apply to no triage decision ever. The console
+ and the worker were looking at two different places.
+
+ The file path is kept as an operator-level override: an air-gapped install
+ that ships rules on disk should keep working, and its rules apply to every
+ tenant. Tenant rules are evaluated first, because a tenant's own statement
+ about their estate is more specific than a deployment-wide default.
+ """
def __init__(self, rules_file: str | None = None) -> None:
self._path = rules_file or os.environ.get(_RULES_FILE_ENV, "")
self._rules: list[BusinessContextRule] = []
self._mtime: float | None = None
+ self._tenant_rules: dict[str, tuple[float, list[BusinessContextRule]]] = {}
self._load()
+ # ── tenant rules (Postgres) ───────────────────────────────────────────
+
+ async def _load_tenant_rules(self, tenant_id: str) -> list[BusinessContextRule]:
+ """Read and cache the tenant's authored rules. Never raises."""
+ cached = self._tenant_rules.get(tenant_id)
+ now = time.monotonic()
+ if cached is not None and now - cached[0] < _TENANT_CACHE_TTL_SECONDS:
+ return cached[1]
+
+ dsn = os.environ.get("DATABASE_DSN") or os.environ.get("DATABASE_URL") or ""
+ dsn = dsn.strip().replace("postgresql+asyncpg://", "postgresql://")
+ if not dsn:
+ return []
+
+ try:
+ import asyncpg # noqa: PLC0415 — optional at import time
+
+ conn = await asyncpg.connect(dsn, timeout=5.0)
+ try:
+ row = await conn.fetchrow(
+ """
+ SELECT yaml_text, enabled
+ FROM aisoc_business_context_rule_sets
+ WHERE tenant_id = $1
+ """,
+ uuid.UUID(tenant_id),
+ )
+ finally:
+ await conn.close()
+ except Exception as exc: # noqa: BLE001 — fail-soft: no tenant rules applied
+ logger.warning(
+ "business_context.tenant_load_failed",
+ tenant_id=tenant_id,
+ error=str(exc),
+ )
+ # Serve the last known rules rather than silently dropping a
+ # tenant's suppressions during a brief outage.
+ return cached[1] if cached else []
+
+ rules: list[BusinessContextRule] = []
+ if row is not None and row["enabled"] and row["yaml_text"]:
+ try:
+ rules = load_rules_from_yaml(row["yaml_text"])
+ except Exception as exc: # noqa: BLE001 — a bad rule set applies none
+ logger.warning(
+ "business_context.tenant_parse_failed",
+ tenant_id=tenant_id,
+ error=str(exc),
+ )
+ rules = []
+
+ self._tenant_rules[tenant_id] = (now, rules)
+ return rules
+
+ async def apply_for_tenant(self, tenant_id: str | None, alert: dict[str, Any]) -> BusinessContextResult:
+ """Apply this tenant's authored rules, then any deployment-wide ones."""
+ self._load() # cheap mtime check on the file-based rules
+ tenant_rules = await self._load_tenant_rules(str(tenant_id)) if tenant_id else []
+ rules = [*tenant_rules, *self._rules]
+ if not rules:
+ return BusinessContextResult(dict(alert), [], False, alert.get("severity"), alert.get("severity"))
+ try:
+ return apply_rules(alert, rules)
+ except Exception as exc: # noqa: BLE001 — never break triage
+ logger.warning("business_context.apply_failed", error=str(exc))
+ return BusinessContextResult(dict(alert), [], False, alert.get("severity"), alert.get("severity"))
+
+ def clear_tenant_cache(self) -> None:
+ """Drop cached tenant rules. Used by tests."""
+ self._tenant_rules.clear()
+
def _load(self) -> None:
if not self._path:
self._rules = []
diff --git a/services/agents/app/workers/fused_alert_consumer.py b/services/agents/app/workers/fused_alert_consumer.py
index c0a06459b..479b8d4f9 100644
--- a/services/agents/app/workers/fused_alert_consumer.py
+++ b/services/agents/app/workers/fused_alert_consumer.py
@@ -349,7 +349,14 @@ class FusedAlertTriageWorker:
# severity/route/tag rule mutates the alert the agent reasons over.
bc_matched: list[str] = []
if self._business_context is not None and isinstance(message, dict) and isinstance(message.get("alert"), dict):
- bc = self._business_context.apply(message["alert"])
+ # Per tenant, not one global rule set. The console writes
+ # business-context rules per tenant and this worker only ever read
+ # a YAML file whose path nothing sets, so authored rules applied to
+ # no triage decision.
+ bc = await self._business_context.apply_for_tenant(
+ message.get("tenant_id") or message["alert"].get("tenant_id"),
+ message["alert"],
+ )
bc_matched = bc.matched_rule_ids
if bc.suppressed:
_METRICS["bc_suppressed"] += 1
diff --git a/services/agents/tests/test_business_context_per_tenant.py b/services/agents/tests/test_business_context_per_tenant.py
new file mode 100644
index 000000000..1ffde9d70
--- /dev/null
+++ b/services/agents/tests/test_business_context_per_tenant.py
@@ -0,0 +1,177 @@
+"""Business-context rules authored in the console must reach triage.
+
+The console has let a tenant author business-context rules since T3.5 — "this
+host is a domain controller, escalate anything touching it", "this service
+account runs the nightly backup, suppress its noise". Two independent bugs
+meant none of them ever affected a triage decision.
+
+The API stored them in a module-level dict inside whichever process served the
+write, so they were lost on restart and invisible to other replicas. And this
+worker loaded rules only from a YAML file whose path comes from
+`AISOC_BUSINESS_CONTEXT_RULES_FILE`, which nothing sets. The console and the
+worker were looking at two different places, and one of them was empty.
+
+A tenant could author a rule, see it saved, preview it against their last 50
+alerts, and have it apply to nothing.
+"""
+
+from __future__ import annotations
+
+import pytest
+from app.workers import business_context as bc_mod
+from app.workers.business_context import BusinessContextApplier
+
+pytestmark = pytest.mark.asyncio
+
+TENANT_A = "11111111-1111-1111-1111-111111111111"
+TENANT_B = "22222222-2222-2222-2222-222222222222"
+
+SUPPRESS_BACKUP = """
+rules:
+ - id: backup-noise
+ priority: 10
+ when:
+ field: username
+ op: eq
+ value: svc_backup
+ then:
+ suppress: true
+"""
+
+ESCALATE_DC = """
+rules:
+ - id: dc-critical
+ priority: 10
+ when:
+ field: hostname
+ op: eq
+ value: WIN-DC01
+ then:
+ set_severity: critical
+"""
+
+
+def _alert(**overrides):
+ alert = {"hostname": "WIN-WS42", "username": "alice", "severity": "low"}
+ alert.update(overrides)
+ return alert
+
+
+def _stub_tenant_rules(monkeypatch: pytest.MonkeyPatch, mapping: dict[str, str]):
+ """Stand in for the Postgres read, keyed by tenant."""
+
+ async def _load(self, tenant_id): # noqa: ANN001, ANN202
+ yaml_text = mapping.get(tenant_id, "")
+ return bc_mod.load_rules_from_yaml(yaml_text) if yaml_text else []
+
+ monkeypatch.setattr(BusinessContextApplier, "_load_tenant_rules", _load)
+
+
+# ── the regression ────────────────────────────────────────────────────────
+
+
+async def test_a_tenants_authored_suppression_is_applied(monkeypatch: pytest.MonkeyPatch):
+ _stub_tenant_rules(monkeypatch, {TENANT_A: SUPPRESS_BACKUP})
+ result = await BusinessContextApplier().apply_for_tenant(TENANT_A, _alert(username="svc_backup"))
+ assert result.suppressed
+ assert "backup-noise" in result.matched_rule_ids
+
+
+async def test_a_tenants_authored_escalation_is_applied(monkeypatch: pytest.MonkeyPatch):
+ _stub_tenant_rules(monkeypatch, {TENANT_A: ESCALATE_DC})
+ result = await BusinessContextApplier().apply_for_tenant(TENANT_A, _alert(hostname="WIN-DC01"))
+ assert result.alert["severity"] == "critical"
+
+
+async def test_one_tenants_rules_do_not_affect_another(monkeypatch: pytest.MonkeyPatch):
+ """The reason a single global rule set was wrong.
+
+ Tenant A suppressing their backup account must not suppress tenant B's
+ alerts for an account that happens to share the name.
+ """
+ _stub_tenant_rules(monkeypatch, {TENANT_A: SUPPRESS_BACKUP})
+ applier = BusinessContextApplier()
+ assert (await applier.apply_for_tenant(TENANT_A, _alert(username="svc_backup"))).suppressed
+ assert not (await applier.apply_for_tenant(TENANT_B, _alert(username="svc_backup"))).suppressed
+
+
+async def test_a_tenant_with_no_rules_passes_the_alert_through(
+ monkeypatch: pytest.MonkeyPatch,
+):
+ _stub_tenant_rules(monkeypatch, {})
+ result = await BusinessContextApplier().apply_for_tenant(TENANT_A, _alert())
+ assert not result.suppressed
+ assert result.matched_rule_ids == []
+
+
+async def test_no_tenant_id_still_works(monkeypatch: pytest.MonkeyPatch):
+ """An alert with no tenant must not crash triage."""
+ _stub_tenant_rules(monkeypatch, {TENANT_A: SUPPRESS_BACKUP})
+ result = await BusinessContextApplier().apply_for_tenant(None, _alert(username="svc_backup"))
+ assert not result.suppressed
+
+
+# ── fail-soft ─────────────────────────────────────────────────────────────
+
+
+async def test_an_unreachable_database_never_breaks_triage(
+ monkeypatch: pytest.MonkeyPatch,
+):
+ """Exercises the real loader against a DSN that cannot connect.
+
+ A business-context outage must degrade to "no rules applied", never to a
+ dropped alert.
+ """
+ monkeypatch.setenv("DATABASE_DSN", "postgresql://[email protected]:1/nope")
+ applier = BusinessContextApplier()
+ applier.clear_tenant_cache()
+ assert await applier._load_tenant_rules(TENANT_A) == []
+ assert not (await applier.apply_for_tenant(TENANT_A, _alert())).suppressed
+
+
+async def test_a_transient_outage_serves_the_last_known_rules(
+ monkeypatch: pytest.MonkeyPatch,
+):
+ """Otherwise a blip silently un-suppresses a tenant's known-noisy alerts."""
+ applier = BusinessContextApplier()
+ applier._tenant_rules[TENANT_A] = (0.0, bc_mod.load_rules_from_yaml(SUPPRESS_BACKUP))
+ monkeypatch.setenv("DATABASE_DSN", "postgresql://[email protected]:1/nope")
+ rules = await applier._load_tenant_rules(TENANT_A)
+ assert [r.id for r in rules] == ["backup-noise"]
+
+
+async def test_malformed_tenant_yaml_applies_no_rules_rather_than_crashing():
+ """A tenant can save syntactically broken YAML; triage must survive it."""
+ assert bc_mod.load_rules_from_yaml("rules:\n - no_id_field: true") == []
+
+
+async def test_no_database_configured_is_not_an_error(monkeypatch: pytest.MonkeyPatch):
+ """Single-node installs with no DSN must still triage."""
+ monkeypatch.delenv("DATABASE_DSN", raising=False)
+ monkeypatch.delenv("DATABASE_URL", raising=False)
+ applier = BusinessContextApplier()
+ applier.clear_tenant_cache()
+ assert await applier._load_tenant_rules(TENANT_A) == []
+
+
+# ── precedence ────────────────────────────────────────────────────────────
+
+
+async def test_tenant_rules_are_evaluated_before_deployment_wide_ones(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path,
+):
+ """A tenant's statement about their own estate is the more specific one.
+
+ The file-based path is kept so an air-gapped install shipping rules on disk
+ keeps working; those rules apply to every tenant.
+ """
+ rules_file = tmp_path / "rules.yaml"
+ rules_file.write_text(ESCALATE_DC)
+ _stub_tenant_rules(monkeypatch, {TENANT_A: SUPPRESS_BACKUP})
+
+ applier = BusinessContextApplier(rules_file=str(rules_file))
+ # Deployment-wide rule still applies to a tenant with none of their own.
+ assert (await applier.apply_for_tenant(TENANT_B, _alert(hostname="WIN-DC01"))).alert["severity"] == "critical"
+ # And the tenant's own suppression is reached.
+ assert (await applier.apply_for_tenant(TENANT_A, _alert(username="svc_backup"))).suppressed
diff --git a/services/api/app/api/v1/endpoints/business_context.py b/services/api/app/api/v1/endpoints/business_context.py
index edd419a97..86d08c803 100644
--- a/services/api/app/api/v1/endpoints/business_context.py
+++ b/services/api/app/api/v1/endpoints/business_context.py
@@ -61,6 +61,7 @@ import structlog
import yaml
from fastapi import APIRouter, HTTPException, status
from pydantic import BaseModel, Field
+from sqlalchemy import text
from app.api.v1.deps import AuthUser, DBSession
from app.services.business_context import (
@@ -231,32 +232,110 @@ def _envelope(
_RuleStoreEntry = dict[str, Any]
+
+#: Cache of the last read per tenant, so a GET that immediately follows a PUT
+#: in the same request cycle sees the write without a second round trip. It is
+#: NOT the store: `aisoc_business_context_rule_sets` is.
_rule_store: dict[UUID, _RuleStoreEntry] = {}
-def _persist_for(tenant_id: UUID, *, yaml_text: str, enabled: bool) -> datetime:
+async def _persist_for(
+ db: Any, # noqa: ANN401 — AsyncSession; kept loose so tests can stub
+ tenant_id: UUID,
+ *,
+ yaml_text: str,
+ enabled: bool,
+) -> datetime:
+ """Write the tenant's rules to Postgres.
+
+ These used to live only in `_rule_store`, a module-level dict inside
+ whichever API process served the write. So they were lost on restart,
+ invisible to every other replica, and — the part that mattered — invisible
+ to the auto-triage worker, which loads business-context rules from a YAML
+ file path that nothing sets. A tenant could author a rule, see it saved,
+ preview it against their last 50 alerts, and have it apply to no triage
+ decision ever.
+ """
now = datetime.now(UTC)
- _rule_store[tenant_id] = {
- "yaml": yaml_text,
- "enabled": enabled,
- "updated_at": now,
- }
+ _rule_store[tenant_id] = {"yaml": yaml_text, "enabled": enabled, "updated_at": now}
+ try:
+ await db.execute(
+ text(
+ """
+ INSERT INTO aisoc_business_context_rule_sets
+ (tenant_id, yaml_text, enabled, updated_at)
+ VALUES (:tenant_id, :yaml_text, :enabled, :updated_at)
+ ON CONFLICT (tenant_id) DO UPDATE SET
+ yaml_text = EXCLUDED.yaml_text,
+ enabled = EXCLUDED.enabled,
+ updated_at = EXCLUDED.updated_at
+ """
+ ),
+ {
+ "tenant_id": str(tenant_id),
+ "yaml_text": yaml_text,
+ "enabled": enabled,
+ "updated_at": now,
+ },
+ )
+ await db.commit()
+ except Exception as exc: # noqa: BLE001 — surfaced below, never silently dropped
+ logger.error(
+ "business_context.persist_failed",
+ tenant_id=str(tenant_id),
+ error=str(exc).replace("\r", " ").replace("\n", " ")[:500],
+ )
+ raise HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail=("Could not save business-context rules. They were not persisted, " "so nothing has changed."),
+ ) from exc
return now
-def _load_for(tenant_id: UUID) -> _RuleStoreEntry:
- entry = _rule_store.get(tenant_id)
- if entry is None:
- return {
- "yaml": "",
- "enabled": True, # default-on per spec
- "updated_at": datetime.now(UTC),
- }
+async def _load_for(
+ db: Any, # noqa: ANN401 — AsyncSession; kept loose so tests can stub
+ tenant_id: UUID,
+) -> _RuleStoreEntry:
+ """Read the tenant's rules from Postgres, falling back to the defaults."""
+ default: _RuleStoreEntry = {
+ "yaml": "",
+ "enabled": True, # default-on per spec
+ "updated_at": datetime.now(UTC),
+ }
+ try:
+ result = await db.execute(
+ text(
+ """
+ SELECT yaml_text, enabled, updated_at
+ FROM aisoc_business_context_rule_sets
+ WHERE tenant_id = :tenant_id
+ """
+ ),
+ {"tenant_id": str(tenant_id)},
+ )
+ row = result.first()
+ except Exception as exc: # noqa: BLE001 — a read failure falls back to cache
+ logger.warning(
+ "business_context.load_failed",
+ tenant_id=str(tenant_id),
+ error=str(exc).replace("\r", " ").replace("\n", " ")[:500],
+ )
+ return _rule_store.get(tenant_id, default)
+
+ if row is None:
+ return _rule_store.get(tenant_id, default)
+
+ entry: _RuleStoreEntry = {
+ "yaml": row[0] or "",
+ "enabled": bool(row[1]),
+ "updated_at": row[2] or datetime.now(UTC),
+ }
+ _rule_store[tenant_id] = entry
return entry
def _reset_store_for_tests() -> None:
- """Clear in-process state — only safe in test code."""
+ """Clear the read cache — only safe in test code."""
_rule_store.clear()
@@ -282,8 +361,6 @@ async def _fetch_sample_alerts(
(test envs without the schema, demo Fly.io stack) — the UI then
falls back to its built-in illustrative samples.
"""
- from sqlalchemy import text # noqa: PLC0415
-
try:
result = await db.execute(
text(
@@ -355,7 +432,7 @@ async def get_rules(
"""
await user.require_permission_db("settings:read", db)
- entry = _load_for(user.tenant_id)
+ entry = await _load_for(db, user.tenant_id)
yaml_text = entry["yaml"]
enabled = entry["enabled"]
@@ -400,10 +477,11 @@ async def replace_rules(
detail=str(exc),
) from exc
- updated_at = _persist_for(
+ updated_at = await _persist_for(
+ db,
user.tenant_id,
yaml_text=payload.yaml,
- enabled=_load_for(user.tenant_id)["enabled"],
+ enabled=(await _load_for(db, user.tenant_id))["enabled"],
)
snapshot = _engine().replace(user.tenant_id, rules)
@@ -417,7 +495,7 @@ async def replace_rules(
user.tenant_id,
snapshot,
yaml_text=payload.yaml,
- enabled=_load_for(user.tenant_id)["enabled"],
+ enabled=(await _load_for(db, user.tenant_id))["enabled"],
updated_at=updated_at,
)
@@ -458,16 +536,17 @@ async def update_rule(
detail=(f"rule id in URL ({rule_id!r}) must match rule id in body " f"({new_rule.id!r})"),
)
- existing_yaml = _load_for(user.tenant_id)["yaml"]
+ existing_yaml = (await _load_for(db, user.tenant_id))["yaml"]
existing_rules = load_rules_from_yaml(existing_yaml) if existing_yaml else []
by_id = {r.id: r for r in existing_rules}
by_id[new_rule.id] = new_rule
next_yaml = _serialise_rules(list(by_id.values()))
- updated_at = _persist_for(
+ updated_at = await _persist_for(
+ db,
user.tenant_id,
yaml_text=next_yaml,
- enabled=_load_for(user.tenant_id)["enabled"],
+ enabled=(await _load_for(db, user.tenant_id))["enabled"],
)
snapshot = _engine().replace(user.tenant_id, by_id.values())
@@ -481,7 +560,7 @@ async def update_rule(
user.tenant_id,
snapshot,
yaml_text=next_yaml,
- enabled=_load_for(user.tenant_id)["enabled"],
+ enabled=(await _load_for(db, user.tenant_id))["enabled"],
updated_at=updated_at,
)
@@ -498,7 +577,7 @@ async def delete_rule(
) -> None:
await user.require_permission_db("settings:write", db)
- existing_yaml = _load_for(user.tenant_id)["yaml"]
+ existing_yaml = (await _load_for(db, user.tenant_id))["yaml"]
existing_rules = load_rules_from_yaml(existing_yaml) if existing_yaml else []
remaining = [r for r in existing_rules if r.id != rule_id]
if len(remaining) == len(existing_rules):
@@ -508,10 +587,11 @@ async def delete_rule(
)
next_yaml = _serialise_rules(remaining)
- _persist_for(
+ await _persist_for(
+ db,
user.tenant_id,
yaml_text=next_yaml,
- enabled=_load_for(user.tenant_id)["enabled"],
+ enabled=(await _load_for(db, user.tenant_id))["enabled"],
)
_engine().replace(user.tenant_id, remaining)
logger.info(
diff --git a/services/api/migrations/050_business_context_rule_sets.sql b/services/api/migrations/050_business_context_rule_sets.sql
new file mode 100644
index 000000000..030a00e58
--- /dev/null
+++ b/services/api/migrations/050_business_context_rule_sets.sql
@@ -0,0 +1,39 @@
+-- Business-context rules: durable, tenant-scoped, readable by the triage worker.
+--
+-- The console has let a tenant author business-context rules — "this host is a
+-- domain controller, escalate anything touching it", "this service account runs
+-- the nightly backup, suppress its noise" — since T3.5. They were stored in a
+-- module-level dict inside whichever API process served the write:
+--
+-- _rule_store: dict[UUID, _RuleStoreEntry] = {}
+--
+-- so they were lost on restart, invisible to every other replica, and — worse —
+-- the auto-triage worker never read them at all. `BusinessContextApplier` loads
+-- YAML from a file path in `AISOC_BUSINESS_CONTEXT_RULES_FILE`, which nothing
+-- sets. A tenant could configure business context, see it saved, preview it
+-- against their last 50 alerts, and have it apply to no triage decision ever.
+--
+-- The endpoint's own comment pointed at this table as the follow-up. This is it.
+
+CREATE TABLE IF NOT EXISTS aisoc_business_context_rule_sets (
+ tenant_id UUID PRIMARY KEY REFERENCES tenants(id) ON DELETE CASCADE,
+ -- The authored YAML, kept verbatim rather than normalised: it is the
+ -- artifact the analyst edits, and round-tripping it through a parser would
+ -- lose their comments and ordering.
+ yaml_text TEXT NOT NULL DEFAULT '',
+ -- Default-on, matching the endpoint's existing behaviour for a tenant with
+ -- no stored row.
+ enabled BOOLEAN NOT NULL DEFAULT TRUE,
+ updated_by UUID REFERENCES users(id) ON DELETE SET NULL,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+-- The triage worker polls this on a short interval, once per tenant, on the
+-- hot path for every fused alert. Index the freshness column so it can ask
+-- "anything changed?" without reading the YAML payloads.
+CREATE INDEX IF NOT EXISTS idx_business_context_updated_at
+ ON aisoc_business_context_rule_sets (updated_at DESC);
+
+COMMENT ON TABLE aisoc_business_context_rule_sets IS
+ 'Per-tenant business-context rules authored in the console and applied by the auto-triage worker.';
diff --git a/services/api/tests/test_business_context.py b/services/api/tests/test_business_context.py
index b5aea4252..6b5bc4549 100644
--- a/services/api/tests/test_business_context.py
+++ b/services/api/tests/test_business_context.py
@@ -500,6 +500,28 @@ class TestPreview:
# ---------------------------------------------------------------------------
+def _db() -> MagicMock:
+ """A session stub whose `execute`/`commit` are awaitable.
+
+ The rules used to live in a module-level dict, so a bare `MagicMock()` was
+ a sufficient stand-in for the session. They are now persisted to
+ `aisoc_business_context_rule_sets` — the console and the auto-triage worker
+ were previously reading two different places, and the worker's was always
+ empty — so these tests exercise a real async session shape.
+
+ `first()` returns None: a tenant with no stored row, which is the state
+ every one of these tests starts from. The endpoint's read cache then serves
+ what the test just wrote, matching production behaviour for a
+ write-then-read inside one request cycle.
+ """
+ db = MagicMock()
+ result = MagicMock()
+ result.first.return_value = None
+ db.execute = AsyncMock(return_value=result)
+ db.commit = AsyncMock()
+ return db
+
+
def _run(coro): # type: ignore[no-untyped-def]
"""Drive an async endpoint coroutine to completion in a fresh loop.
@@ -516,7 +538,7 @@ def _run(coro): # type: ignore[no-untyped-def]
class TestEndpoints:
def test_get_returns_empty_envelope_when_no_rules(self) -> None:
user = _user()
- env = _run(endpoint.get_rules(user, MagicMock()))
+ env = _run(endpoint.get_rules(user, _db()))
assert env.tenant_id == str(user.tenant_id)
assert env.rules == []
assert env.yaml == ""
@@ -535,7 +557,7 @@ class TestEndpoints:
endpoint.replace_rules(
endpoint.ReplaceRulesRequest(yaml=yaml_text),
user,
- MagicMock(),
+ _db(),
)
)
assert env.yaml == yaml_text
@@ -543,7 +565,7 @@ class TestEndpoints:
assert env.rules[0].id == "prod-critical"
assert env.rules[0].then.set_severity == "critical"
# Subsequent GET sees the same persisted YAML.
- env2 = _run(endpoint.get_rules(user, MagicMock()))
+ env2 = _run(endpoint.get_rules(user, _db()))
assert env2.yaml == yaml_text
assert env2.rules[0].id == "prod-critical"
@@ -554,7 +576,7 @@ class TestEndpoints:
endpoint.replace_rules(
endpoint.ReplaceRulesRequest(yaml="id: BAD\nthen: { tag: t }"),
user,
- MagicMock(),
+ _db(),
)
)
assert exc_info.value.status_code == 422
@@ -576,7 +598,7 @@ class TestEndpoints:
endpoint.replace_rules(
endpoint.ReplaceRulesRequest(yaml=seed),
user,
- MagicMock(),
+ _db(),
)
)
# Patch rule-a only.
@@ -587,7 +609,7 @@ class TestEndpoints:
yaml=("id: rule-a\n" "when: { field: alert.severity, op: eq, value: high }\n" "then: { route_to: tier3 }\n")
),
user,
- MagicMock(),
+ _db(),
)
)
rules_by_id = {r.id: r for r in env.rules}
@@ -604,7 +626,7 @@ class TestEndpoints:
"rule-a",
endpoint.UpdateRuleRequest(yaml=("id: rule-other\n" "when: { field: x, op: eq, value: 1 }\n" "then: { tag: t }\n")),
user,
- MagicMock(),
+ _db(),
)
)
assert exc_info.value.status_code == 422
@@ -625,18 +647,18 @@ class TestEndpoints:
endpoint.replace_rules(
endpoint.ReplaceRulesRequest(yaml=seed),
user,
- MagicMock(),
+ _db(),
)
)
- result = _run(endpoint.delete_rule("drop", user, MagicMock()))
+ result = _run(endpoint.delete_rule("drop", user, _db()))
assert result is None
- env = _run(endpoint.get_rules(user, MagicMock()))
+ env = _run(endpoint.get_rules(user, _db()))
assert [r.id for r in env.rules] == ["keep"]
def test_delete_404_when_rule_missing(self) -> None:
user = _user()
with pytest.raises(HTTPException) as exc_info:
- _run(endpoint.delete_rule("never-existed", user, MagicMock()))
+ _run(endpoint.delete_rule("never-existed", user, _db()))
assert exc_info.value.status_code == 404
def test_preview_against_supplied_alerts(self) -> None:
@@ -648,7 +670,7 @@ class TestEndpoints:
_alert("b", target_tag="dev", severity="medium"),
],
)
- resp = _run(endpoint.preview_rules(req, user, MagicMock()))
+ resp = _run(endpoint.preview_rules(req, user, _db()))
assert resp.sample_size == 2
assert resp.changed_count == 1
assert resp.suppressed_count == 0
@@ -666,7 +688,7 @@ class TestEndpoints:
endpoint.preview_rules(
endpoint.PreviewRequest(yaml="id: BAD\nthen: { tag: t }"),
user,
- MagicMock(),
+ _db(),
)
)
assert exc_info.value.status_code == 422
@@ -714,7 +736,7 @@ class TestEndpoints:
endpoint.replace_rules(
endpoint.ReplaceRulesRequest(yaml=yaml_text),
user,
- MagicMock(),
+ _db(),
)
)
engine = get_engine()