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.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(phase-B4): apply Business Context Rules post-fusion -> pre-triage (#455)
Beenu Arora6f7ec4ff552c
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 3841347a6..ec5c2a095 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -333,6 +333,7 @@ jobs:tests/test_model_router.py \tests/test_llm_ops.py \tests/test_fused_alert_worker.py \+ tests/test_business_context_hotpath.py \-v --tb=short# ──────────────────────────────────────────────diff --git a/CHANGELOG.md b/CHANGELOG.mdindex da09c35c6..631212712 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- **Phase B4 — Business Context Rules now run on the live path (environment-specific noise reduction).** A leading AI-SOC differentiator — suppress alerts during a maintenance window, bump severity for production assets, route cloud alerts to the cloud team — existed as an engine + authoring UI in `services/api` but only ran in a dry-run preview; it never touched a live alert. New `services/agents/app/workers/business_context.py` applies the same `when`/`then` semantics (dotted-path fields + `eq/ne/lt/gt/contains/in/exists/...` comparators + `all/any/not`; effects `set_severity` / `route_to` / `tag` / `suppress`) in the auto-triage worker's post-fusion → pre-triage seam. A **suppress** rule drops the alert **before any triage spend**; severity/route/tag mutations flow into the alert the agent reasons over. Rules load from `AISOC_BUSINESS_CONTEXT_RULES_FILE` (mtime-reloaded), gated by `AISOC_BUSINESS_CONTEXT_ENABLED` (default on), fail-soft (bad/missing file ⇒ no rules applied, never an error into triage). The agents image can't import `services/api`, so the evaluator is a faithful, independently-tested re-implementation of the same documented semantics (unifying both call sites is a follow-up). 15 unit tests (`test_business_context_hotpath.py`, added to the CI agents gate). Claim-to-gate matrix +1 GATED (23 GATED / 10 PARTIAL / 1 NO GATE).- **Phase B3 — rollback is real, actions are post-verified, and approval SLA timers survive restarts.** Three "honest response" gaps closed. (1) **Real rollback:** every executor's `rollback()` previously returned a bare `True` — logging "rolling back" without calling the vendor. New `services/actions/app/services/rollback.py` performs the **real** reverse via the same clients (isolate→`lift_containment`/`unisolate_machine`, block_ip→`unblock_ip`/`unblock_ip_zone`, disable_user→`enable_user`/`unsuspend_user`, suspend_session→`unsuspend_user`) and returns an honest `RollbackResult` (`reversed_` / `simulated` / `supported`) — never a fake success; a failed reverse is reported, not hidden. `autonomy_safety.REVERSIBLE_ACTIONS` now imports from this module (single source of truth) and `test_rollback.py` gates the two sets so an action can't be declared reversible without a real reverse. (2) **Post-action verification:** new `services/actions/app/services/verification.py` re-queries the vendor to confirm the effect is actually present (`VERIFIED` / `FAILED` / honest `UNVERIFIED` when no probe or no creds) — a probe error is never a false `VERIFIED`. (3) **Durable approvals:** `services/slack-bot/app/services/timer_store.py` adds a Postgres-backed `TimerStore`; the `ApprovalTimeoutScheduler` persists pending SLA timers and `recover()` re-arms them on startup (firing overdue ones promptly), so a bot restart can no longer strand a forgotten approval forever. Fail-soft to in-memory when no DB. 25 new tests across actions + slack-bot. Claim-to-gate matrix +1 GATED (22 GATED / 10 PARTIAL / 1 NO GATE).- **Phase B2 — connector credentials now reach the SOAR executors, and the autonomy policy governs every real execution.** Two wiring gaps closed. (1) Executors read vendor-prefixed parameter keys (`cs_client_id`, `okta_domain`, `splunk_url` …) but connectors store schema field names (`client_id`, `domain`, `base_url` …) — nothing translated, so even fully-configured credentials never reached an executor and every action fell back to simulation. New `services/actions/app/services/credential_resolver.py` pins the per-vendor translation (15 vendors, connector-id aliases like `aws_security_hub`→`aws_security_groups`, `azure_defender`→`defender`; unknown fields dropped, never blindly forwarded), and `LiveActionRequest.auth_config` lets callers pass connector-style creds that the dispatcher resolves at the boundary. (2) The Phase 9a `autonomy_safety.decide()` policy existed but was never called on the live path (the 9b gap) — now every dispatch whose capability maps to an `ActionType` is governed **before** the executor is invoked: above-tier ⇒ downgraded to a dry-run preview; with dry-run disabled ⇒ `PENDING_APPROVAL` (executor never invoked); tier L0 ⇒ `BLOCKED`; explicit dry-run honoured unchanged; governance verdict attached to the result for the audit trail. Deployment tier via `AISOC_MATURITY_TIER` (default L1 — copilot). Also registers ten previously-missing vendor adapters (SentinelOne isolate, Entra/GWS disable-user, PAN-OS/FortiGate/Cloudflare block-ip, Jira/ServiceNow/PagerDuty create-ticket, Slack notify) so the agent can plan against them (19→29 builtins). 29 new/updated tests; full actions suite 224 passed at 64% coverage. Claim-to-gate matrix +1 GATED (21 GATED / 10 PARTIAL / 1 NO GATE).- **Phase B1 — the agent now auto-triages every alert off the stream (copilot default).** The core autonomy gap: investigations were manual/API-only — nothing consumed `aisoc.alerts.fused`, so "an agent that triages every alert" wasn't true out of the box. New `services/agents/app/workers/fused_alert_consumer.py` (`FusedAlertTriageWorker`) subscribes to the fused-alert topic and auto-triages each alert. **Copilot / dry-run is the default**: triage is read-only — it classifies (verdict + calibrated confidence), records the reasoning to the Investigation Ledger (best-effort), and **never dispatches a response** (proposed actions carry `requires_approval=True`; `response_dispatched` is always `False`). Tier selection is cost- and determinism-aware: cost-governor `DEDUPLICATED` reuses the cached verdict (a flood of identical alerts costs one triage), `CIRCUIT_OPEN`/`AISOC_DETERMINISTIC`/no-LLM-key falls to deterministic heuristic triage (`run_triage` — the air-gapped/CI default), otherwise LLM auto-triage with a deterministic fallback on failure. Wired into the agents lifespan (off unless `KAFKA_BOOTSTRAP_SERVERS` is set) + compose (`depends_on: kafka`). 9 unit tests (`test_fused_alert_worker.py`, added to the CI agents gate; the job now also installs `langgraph`). Claim-to-gate matrix adds a GATED row "Agent auto-triages every alert" (20 GATED / 10 PARTIAL / 1 NO GATE).diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex 48e436a37..d7e02ffbe 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -41,10 +41,11 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| Agent auto-triages every alert (not manual/API-only) | README (autonomous triage) | `ci.yml` agents job (`test_fused_alert_worker.py` — `FusedAlertTriageWorker` consumes `aisoc.alerts.fused`, auto-triages each alert copilot/read-only with cost-governor dedup + circuit-breaker, degrades to deterministic triage without an LLM key, never dispatches a response) | GATED | - || Connector credentials reach the SOAR executors (not simulation-only) + autonomy policy governs every real execution | README (SOAR / response) | `ci.yml` actions job (`test_credential_resolver.py` — per-vendor auth_config→executor-param translation pinned; `test_governed_dispatch.py` — Phase 9a `decide()` wired into live dispatch: above-tier ⇒ dry-run preview, dry-run-disabled ⇒ queued approval, L0 ⇒ blocked, executor never invoked when queued/blocked) | GATED | - || Rollback is real (not "return True"), post-action verified, and approvals are restart-durable | README (response / rollback) | `ci.yml` actions job (`test_rollback.py` — real vendor reverse calls, honest simulated/failed states, REVERSIBLE_ACTIONS gated against the actual reverse impls; `test_verification.py` — re-queries vendor, never a false VERIFIED) + slack-bot job (`test_timer_store.py` — pending SLA timers persist + recover across restart) | GATED | - |+| Environment-specific noise reduction (business context) applied post-fusion → pre-triage | README (noise reduction) | `ci.yml` agents job (`test_business_context_hotpath.py` — YAML when/then rules mutate severity/route/tags and suppress before any triage spend, wired into `FusedAlertTriageWorker.triage`; `AISOC_BUSINESS_CONTEXT_ENABLED` gate) | GATED | - |## Summary-- GATED: 22+- GATED: 23- PARTIAL: 10- NO GATE: 1 (progressively closed through Phases 2–11 and A1–A4: insecure-defaults, secret/IaC scanning, signed releases, cross-store isolation, DAC candidate-rule + imported-count honesty, connector live-test, OpenAPI breaking-change, ClickHouse lake population (A1), live-stream detection (A2), default cold-boot stack (A3), and the behavioral-model fusion (A4). The **last** NO GATE row — wet-eval live-agent scoreboard tables — closes in Phase 4c/E1, which needs a budgeted live-agent run)diff --git a/services/agents/app/main.py b/services/agents/app/main.pyindex 27e619293..5f7856722 100644--- a/services/agents/app/main.py+++ b/services/agents/app/main.py@@ -23,6 +23,8 @@ from app.hunt import store as hunt_storefrom app.investigator import ledger as investigation_ledgerfrom app.playbook import PlaybookStorefrom app.tools.mitre_full import embed_techniques_into_qdrant, load_attck_corpus+from app.workers.business_context import BusinessContextApplier+from app.workers.business_context import is_enabled as business_context_enabledfrom app.workers.fused_alert_consumer import FusedAlertTriageWorker, worker_enabledlogger = structlog.get_logger()@@ -82,9 +84,13 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:app.state.triage_worker_task = Noneif worker_enabled():try:+ # Phase B4 — environment-specific noise reduction (post-fusion →+ # pre-triage). Enabled by default; needs a rules file to do anything.+ applier = BusinessContextApplier() if business_context_enabled() else Nonetriage_worker = FusedAlertTriageWorker(bootstrap_servers=os.environ["KAFKA_BOOTSTRAP_SERVERS"],topic=os.getenv("KAFKA_TOPIC_ALERTS_FUSED", "aisoc.alerts.fused"),+ business_context=applier,)app.state.triage_worker = triage_workerapp.state.triage_worker_task = asyncio.create_task(triage_worker.start())diff --git a/services/agents/app/workers/business_context.py b/services/agents/app/workers/business_context.pynew file mode 100644index 000000000..819a636b1--- /dev/null+++ b/services/agents/app/workers/business_context.py@@ -0,0 +1,267 @@+"""Business-context rules in the auto-triage hot path (Phase B4).++The leading AI-SOCs win a lot of their "80% noise reduction" from+*environment-specific* rules: suppress alerts during a known maintenance+window, bump severity for production assets, route cloud alerts to the cloud+team. AiSOC has a Business Context Rules **engine + authoring UI** in+``services/api``, but it was never applied on the live path — it only ran in a+dry-run preview. This module applies it post-fusion → pre-triage.++Placement: the auto-triage worker (``fused_alert_consumer.triage``) is exactly+the post-fusion → pre-triage seam. A **suppress** rule drops the alert before+any (possibly LLM) triage spend; **severity / route / tag** rules mutate the+alert the agent then reasons over.++Why a self-contained evaluator here rather than importing the API engine: the+agents service image ships only its own ``app/`` subtree, so it can't import+``services/api``. This module re-implements the same small, documented+``when`` (dotted-path + comparators + all/any/not) / ``then``+(set_severity / route_to / tag / suppress) semantics, loads rules from a YAML+file (``AISOC_BUSINESS_CONTEXT_RULES_FILE``), and is unit-tested against those+semantics. (Unifying both call sites behind a shared package is a follow-up.)++Everything is fail-soft: a missing/invalid rules file or a bad rule degrades to+"no business context applied", never an error into triage.+"""++from __future__ import annotations++import os+from dataclasses import dataclass+from dataclasses import field as dc_field+from pathlib import Path+from typing import Any++import structlog+import yaml++logger = structlog.get_logger()++_ALLOWED_SEVERITIES = {"info", "low", "medium", "high", "critical"}+_ENABLED_ENV = "AISOC_BUSINESS_CONTEXT_ENABLED"+_RULES_FILE_ENV = "AISOC_BUSINESS_CONTEXT_RULES_FILE"+++def is_enabled() -> bool:+ """Default-on; disable with AISOC_BUSINESS_CONTEXT_ENABLED=0."""+ raw = os.environ.get(_ENABLED_ENV)+ if raw is None:+ return True+ return raw.strip().lower() not in {"0", "false", "no", "off"}+++# ── Rule model (faithful to services/api business_context) ────────────────────+++@dataclass(frozen=True)+class RuleAction:+ set_severity: str | None = None+ route_to: str | None = None+ tag: str | None = None+ suppress: bool = False+++@dataclass(frozen=True)+class RuleCondition:+ field: str | None = None+ op: str | None = None+ value: Any = None+ logical: str | None = None # "all" | "any" | "not"+ children: tuple[RuleCondition, ...] = dc_field(default_factory=tuple)+++@dataclass(frozen=True)+class BusinessContextRule:+ id: str+ when: RuleCondition+ then: RuleAction+ enabled: bool = True+ priority: int = 100+++def _dotted(alert: dict[str, Any], path: str) -> Any:+ cur: Any = alert+ for part in path.split("."):+ if isinstance(cur, dict):+ cur = cur.get(part)+ else:+ return None+ return cur+++def _cmp(op: str, actual: Any, expected: Any) -> bool: # noqa: PLR0911+ try:+ if op == "eq":+ return actual == expected+ if op == "ne":+ return actual != expected+ if op == "lt":+ return actual < expected+ if op == "lte":+ return actual <= expected+ if op == "gt":+ return actual > expected+ if op == "gte":+ return actual >= expected+ if op == "contains":+ return expected in actual if actual is not None else False+ if op == "startswith":+ return isinstance(actual, str) and actual.startswith(str(expected))+ if op == "endswith":+ return isinstance(actual, str) and actual.endswith(str(expected))+ if op == "in":+ return actual in expected if isinstance(expected, list) else False+ if op == "not_in":+ return actual not in expected if isinstance(expected, list) else False+ if op == "exists":+ return actual is not None+ if op == "not_exists":+ return actual is None+ except TypeError:+ return False+ return False+++def evaluate_condition(cond: RuleCondition, alert: dict[str, Any]) -> bool:+ if cond.logical == "all":+ return all(evaluate_condition(c, alert) for c in cond.children)+ if cond.logical == "any":+ return any(evaluate_condition(c, alert) for c in cond.children)+ if cond.logical == "not":+ return not any(evaluate_condition(c, alert) for c in cond.children)+ if cond.field and cond.op:+ return _cmp(cond.op, _dotted(alert, cond.field), cond.value)+ return False+++def _parse_condition(node: dict[str, Any]) -> RuleCondition:+ for logical in ("all", "any", "not"):+ if logical in node:+ kids = node[logical] or []+ return RuleCondition(logical=logical, children=tuple(_parse_condition(k) for k in kids))+ return RuleCondition(field=node.get("field"), op=node.get("op"), value=node.get("value"))+++def load_rules_from_yaml(source: str) -> list[BusinessContextRule]:+ """Parse rules YAML (single mapping or top-level ``rules:`` list)."""+ if not source or not source.strip():+ return []+ doc = yaml.safe_load(source)+ if doc is None:+ return []+ raw_rules = doc.get("rules", doc) if isinstance(doc, dict) else doc+ if isinstance(raw_rules, dict):+ raw_rules = [raw_rules]+ rules: list[BusinessContextRule] = []+ seen: set[str] = set()+ for entry in raw_rules or []:+ if not isinstance(entry, dict) or "id" not in entry:+ continue+ rid = str(entry["id"])+ if rid in seen:+ continue+ seen.add(rid)+ action = entry.get("then") or {}+ sev = action.get("set_severity")+ if sev is not None and sev not in _ALLOWED_SEVERITIES:+ sev = None+ rules.append(+ BusinessContextRule(+ id=rid,+ when=_parse_condition(entry.get("when") or {}),+ then=RuleAction(+ set_severity=sev,+ route_to=action.get("route_to"),+ tag=action.get("tag"),+ suppress=bool(action.get("suppress", False)),+ ),+ enabled=bool(entry.get("enabled", True)),+ priority=int(entry.get("priority", 100)),+ )+ )+ return rules+++@dataclass+class BusinessContextResult:+ alert: dict[str, Any]+ matched_rule_ids: list[str]+ suppressed: bool+ severity_before: Any+ severity_after: Any++ @property+ def changed(self) -> bool:+ return self.suppressed or bool(self.matched_rule_ids)+++def apply_rules(alert: dict[str, Any], rules: list[BusinessContextRule]) -> BusinessContextResult:+ """Apply enabled rules (priority order) to a copy of ``alert``.++ Suppress short-circuits (once suppressed, downstream rules can't un-suppress),+ matching the API engine's deterministic contract.+ """+ out = dict(alert)+ severity_before = out.get("severity")+ matched: list[str] = []+ for rule in sorted((r for r in rules if r.enabled), key=lambda r: (r.priority, r.id)):+ if not evaluate_condition(rule.when, out):+ continue+ matched.append(rule.id)+ act = rule.then+ if act.set_severity is not None:+ out["severity"] = act.set_severity+ if act.route_to is not None:+ out["route_to"] = act.route_to+ if act.tag is not None:+ tags = list(out.get("tags") or [])+ if act.tag not in tags:+ tags.append(act.tag)+ out["tags"] = tags+ if act.suppress:+ out["__suppressed__"] = True+ return BusinessContextResult(out, matched, True, severity_before, out.get("severity"))+ return BusinessContextResult(out, matched, False, severity_before, out.get("severity"))+++class BusinessContextApplier:+ """Loads rules from a YAML file (mtime-reloaded) and applies them."""++ 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._load()++ def _load(self) -> None:+ if not self._path:+ self._rules = []+ return+ try:+ p = Path(self._path)+ if not p.exists():+ self._rules = []+ return+ mtime = p.stat().st_mtime+ if mtime == self._mtime:+ return+ self._rules = load_rules_from_yaml(p.read_text(encoding="utf-8"))+ self._mtime = mtime+ logger.info("business_context.rules_loaded", count=len(self._rules), path=self._path)+ except Exception as exc: # noqa: BLE001 — fail-soft: no rules applied+ logger.warning("business_context.load_failed", error=str(exc), path=self._path)+ self._rules = []++ @property+ def rule_count(self) -> int:+ return len(self._rules)++ def apply(self, alert: dict[str, Any]) -> BusinessContextResult:+ self._load() # cheap mtime check; reload only when the file changed+ if not self._rules:+ return BusinessContextResult(dict(alert), [], False, alert.get("severity"), alert.get("severity"))+ try:+ return apply_rules(alert, self._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"))diff --git a/services/agents/app/workers/fused_alert_consumer.py b/services/agents/app/workers/fused_alert_consumer.pyindex ab935db05..326955683 100644--- a/services/agents/app/workers/fused_alert_consumer.py+++ b/services/agents/app/workers/fused_alert_consumer.py@@ -45,12 +45,21 @@ from app.investigator import ledger as ledger_modulefrom app.models.state import AgentStatus, InvestigationStatefrom app.routing.model_router import is_deterministic_modefrom app.security.llm_resolver import resolve_llm_config+from app.workers.business_context import BusinessContextApplierlogger = structlog.get_logger()_NAMESPACE = uuid.uuid5(uuid.NAMESPACE_URL, "tryaisoc.com/agents/auto-triage")-_METRICS = {"triaged": 0, "deduplicated": 0, "deterministic": 0, "llm": 0, "errors": 0}+_METRICS = {+ "triaged": 0,+ "deduplicated": 0,+ "deterministic": 0,+ "llm": 0,+ "bc_suppressed": 0,+ "bc_mutated": 0,+ "errors": 0,+}def _coerce_uuid(value: Any, *, fallback: str) -> uuid.UUID:@@ -100,12 +109,22 @@ def build_state(message: dict[str, Any]) -> InvestigationState | None:class FusedAlertTriageWorker:"""Consumes ``aisoc.alerts.fused`` and auto-triages each alert (copilot)."""- def __init__(self, *, bootstrap_servers: str, topic: str = "aisoc.alerts.fused", group_id: str = "aisoc-agents-triage") -> None:+ def __init__(+ self,+ *,+ bootstrap_servers: str,+ topic: str = "aisoc.alerts.fused",+ group_id: str = "aisoc-agents-triage",+ business_context: BusinessContextApplier | None = None,+ ) -> None:self._bootstrap = bootstrap_serversself._topic = topicself._group_id = group_idself._consumer: Any | None = Noneself._running = False+ # Phase B4 — environment-specific noise reduction applied post-fusion →+ # pre-triage. None = disabled (no rules file / flag off).+ self._business_context = business_contextasync def start(self) -> None:from aiokafka import AIOKafkaConsumer # noqa: PLC0415 — optional dep, only at runtime@@ -143,6 +162,26 @@ class FusedAlertTriageWorker:async def triage(self, message: dict[str, Any]) -> dict[str, Any] | None:"""Auto-triage one fused alert. Read-only (copilot): never dispatches aresponse. Returns a verdict summary dict, or None if unprocessable."""+ # Phase B4 — apply business-context rules on the post-fusion alert BEFORE+ # any triage work. A suppress rule drops the alert (no triage spend); a+ # 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"])+ bc_matched = bc.matched_rule_ids+ if bc.suppressed:+ _METRICS["bc_suppressed"] += 1+ logger.info("auto_triage_worker.bc_suppressed", matched=bc_matched)+ return {+ "incident_id": str(message.get("incident_id") or message.get("id") or ""),+ "suppressed": True,+ "business_context_rules": bc_matched,+ "response_dispatched": False,+ }+ if bc.changed:+ _METRICS["bc_mutated"] += 1+ message = {**message, "alert": bc.alert}+state = build_state(message)if state is None:logger.warning("auto_triage_worker.unprocessable", keys=sorted(message.keys()) if isinstance(message, dict) else None)@@ -179,6 +218,7 @@ class FusedAlertTriageWorker:"verdict": verdict,"confidence": confidence,"tier": tier,+ "business_context_rules": bc_matched,# Copilot default: triage is read-only, response requires approval."response_dispatched": False,"proposed_actions": [{"action_type": a.action_type, "requires_approval": a.requires_approval} for a in state.proposed_actions],diff --git a/services/agents/tests/test_business_context_hotpath.py b/services/agents/tests/test_business_context_hotpath.pynew file mode 100644index 000000000..85caf1493--- /dev/null+++ b/services/agents/tests/test_business_context_hotpath.py@@ -0,0 +1,165 @@+"""Phase B4 — business-context rules in the auto-triage hot path.++Proves the YAML rule engine (when/then, all/any/not, comparators) applies+correctly, that a suppress rule drops the alert BEFORE triage (no spend), that+severity/route/tag mutations flow into triage, and that it's fail-soft.+"""++from __future__ import annotations++import pytest+from app.workers import business_context as bc+from app.workers.business_context import BusinessContextApplier, apply_rules, load_rules_from_yaml+from app.workers.fused_alert_consumer import FusedAlertTriageWorker++pytestmark = pytest.mark.asyncio++TENANT = "11111111-1111-1111-1111-111111111111"++_RULES_YAML = """+rules:+ - id: prod-bump+ priority: 10+ when:+ field: env+ op: eq+ value: production+ then:+ set_severity: critical+ tag: prod-asset+ - id: maint-suppress+ priority: 5+ when:+ all:+ - {field: source, op: eq, value: scanner}+ - {field: maintenance, op: eq, value: true}+ then:+ suppress: true+ - id: cloud-route+ priority: 20+ when:+ field: category+ op: eq+ value: cloud+ then:+ route_to: cloud+"""+++def _fused(**alert):+ base = {"id": "a1", "title": "t", "severity": "medium", "env": "staging", "source": "edr", "category": "endpoint"}+ base.update(alert)+ return {"id": "a1", "tenant_id": TENANT, "incident_id": "b2", "alert": base}+++# ── parser + engine ───────────────────────────────────────────────────────────+++async def test_parse_yaml_rules():+ rules = load_rules_from_yaml(_RULES_YAML)+ assert {r.id for r in rules} == {"prod-bump", "maint-suppress", "cloud-route"}+++async def test_severity_bump_and_tag():+ rules = load_rules_from_yaml(_RULES_YAML)+ res = apply_rules({"severity": "medium", "env": "production"}, rules)+ assert res.alert["severity"] == "critical"+ assert "prod-asset" in res.alert["tags"]+ assert "prod-bump" in res.matched_rule_ids+ assert res.suppressed is False+++async def test_suppress_short_circuits():+ rules = load_rules_from_yaml(_RULES_YAML)+ res = apply_rules({"severity": "low", "source": "scanner", "maintenance": True}, rules)+ assert res.suppressed is True+ assert "maint-suppress" in res.matched_rule_ids+++async def test_route_rule():+ rules = load_rules_from_yaml(_RULES_YAML)+ res = apply_rules({"severity": "high", "category": "cloud"}, rules)+ assert res.alert["route_to"] == "cloud"+++async def test_no_match_is_unchanged():+ rules = load_rules_from_yaml(_RULES_YAML)+ res = apply_rules({"severity": "medium", "env": "staging", "source": "edr", "category": "endpoint"}, rules)+ assert res.changed is False+ assert res.alert["severity"] == "medium"+++async def test_invalid_severity_dropped():+ rules = load_rules_from_yaml("rules:\n - id: bad\n when: {field: x, op: eq, value: 1}\n then: {set_severity: SUPER}")+ res = apply_rules({"x": 1, "severity": "low"}, rules)+ assert res.alert["severity"] == "low" # invalid override ignored+++# ── applier file loading + fail-soft ─────────────────────────────────────────+++async def test_applier_loads_from_file(tmp_path):+ f = tmp_path / "rules.yaml"+ f.write_text(_RULES_YAML)+ applier = BusinessContextApplier(rules_file=str(f))+ assert applier.rule_count == 3+ res = applier.apply({"severity": "medium", "env": "production"})+ assert res.alert["severity"] == "critical"+++async def test_applier_no_file_is_noop():+ applier = BusinessContextApplier(rules_file="")+ res = applier.apply({"severity": "medium", "env": "production"})+ assert res.changed is False+++async def test_is_enabled_flag(monkeypatch):+ monkeypatch.delenv("AISOC_BUSINESS_CONTEXT_ENABLED", raising=False)+ assert bc.is_enabled() is True+ monkeypatch.setenv("AISOC_BUSINESS_CONTEXT_ENABLED", "0")+ assert bc.is_enabled() is False+++# ── worker integration ───────────────────────────────────────────────────────+++async def test_worker_suppress_skips_triage(tmp_path, monkeypatch):+ f = tmp_path / "rules.yaml"+ f.write_text(_RULES_YAML)+ worker = FusedAlertTriageWorker(bootstrap_servers="unused", business_context=BusinessContextApplier(rules_file=str(f)))+ result = await worker.triage(_fused(source="scanner", maintenance=True))+ assert result is not None+ assert result["suppressed"] is True+ assert "maint-suppress" in result["business_context_rules"]+ assert result["response_dispatched"] is False+++async def test_worker_severity_mutation_flows_into_triage(tmp_path, monkeypatch):+ monkeypatch.setattr("app.workers.fused_alert_consumer.resolve_llm_config", _fake_llm_config_unavailable())+ f = tmp_path / "rules.yaml"+ f.write_text(_RULES_YAML)+ worker = FusedAlertTriageWorker(bootstrap_servers="unused", business_context=BusinessContextApplier(rules_file=str(f)))+ result = await worker.triage(_fused(env="production"))+ assert result is not None+ assert result.get("suppressed") is not True # not suppressed+ assert "prod-bump" in result["business_context_rules"]+++async def test_worker_without_business_context_is_unaffected(monkeypatch):+ monkeypatch.setattr("app.workers.fused_alert_consumer.resolve_llm_config", _fake_llm_config_unavailable())+ worker = FusedAlertTriageWorker(bootstrap_servers="unused") # no applier+ result = await worker.triage(_fused(source="scanner", maintenance=True))+ assert result is not None+ assert result.get("suppressed") is not True # no BC => not suppressed+ assert result["business_context_rules"] == []+++def _fake_llm_config_unavailable():+ class _Cfg:+ allowed = False+ api_key = None++ async def _resolve(_tenant): # noqa: ANN001+ return _Cfg()++ return _resolve