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(fusion): give the windowed detection engine a loader, and fix its field namespace (#678)

Beenu Arora6f139b798580
diff --git a/.github/workflows/validate-detections.yml b/.github/workflows/validate-detections.yml
index 4f3dc419d..5054f9253 100644
--- a/.github/workflows/validate-detections.yml
+++ b/.github/workflows/validate-detections.yml
@@ -57,6 +57,13 @@ jobs:
- name: Verify detection rules match on fields that exist
run: python3 scripts/check_detection_fields.py
+ # The windowed engine loads its corpus from a JSON artifact the same way
+ # the stateless one does, so it needs the same drift gate: a spec change
+ # without a re-export would leave the deployed engine running a corpus
+ # nobody reviewed.
+ - name: Verify exported windowed ruleset is current
+ run: python3 scripts/export_windowed_ruleset.py --check
+
- name: Count rules by severity
if: always()
run: |
diff --git a/scripts/export_windowed_ruleset.py b/scripts/export_windowed_ruleset.py
new file mode 100644
index 000000000..6349d8dbd
--- /dev/null
+++ b/scripts/export_windowed_ruleset.py
@@ -0,0 +1,162 @@
+#!/usr/bin/env python3
+"""Export windowed detection rules for `services/fusion` to load at startup.
+
+The windowed engine shipped with three hardcoded rules and no way to add a
+fourth without editing the module. That mattered beyond inconvenience: a large
+share of the 2,005 quarantined Splunk rules are `| stats count ... by`
+aggregations. They cannot be expressed in the stateless `match_when` at all,
+because that matcher evaluates one event in isolation, and until now they had
+nowhere else to go — which is most of why the quarantine has stayed at ~2,000
+rules.
+
+This mirrors `export_detection_ruleset.py` exactly: specs are the source of
+truth, the JSON is a build artifact, and `--check` fails CI when the two drift
+so the deployed engine cannot silently diverge from the committed corpus.
+
+A windowed rule is deliberately a narrow shape — match, group by one entity,
+count, threshold, window. It is not a general aggregation language. Anything
+needing joins, subsearches or multi-field grouping is out of scope here and
+should stay quarantined with an honest reason rather than be half-translated.
+
+Usage:
+ python3 scripts/export_windowed_ruleset.py # write the JSON
+ python3 scripts/export_windowed_ruleset.py --check # fail on drift
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+OUT = ROOT / "services" / "fusion" / "app" / "data" / "windowed_ruleset.json"
+
+#: Windowed rules, authored here rather than in the engine module.
+#:
+#: Thresholds are chosen to be defensible rather than impressive. A brute-force
+#: rule that fires on three failures generates more work than it saves, and the
+#: fastest way to have a detection corpus ignored is to ship it noisy.
+#:
+#: `group_by` names the entity the count accumulates against, and it must be a
+#: field some connector actually emits — `scripts/check_detection_fields.py`
+#: gates the stateless corpus for exactly this and the same discipline applies
+#: here.
+WINDOWED_RULES: list[dict] = [
+ {
+ "id": "wd-ai-agent-tool-denials",
+ "name": "AI agent repeatedly denied a tool call",
+ "severity": "high",
+ "category": "application",
+ "mitre": ["T1078"],
+ "match_when": {"outcome": "denied"},
+ "group_by": "agent_id",
+ "threshold": 10,
+ "window_seconds": 300,
+ # A single denial is routine: agents retry, and tools go down. Ten in
+ # five minutes from one agent is the shape that separates an agent
+ # probing its boundaries — or being steered into doing so — from one
+ # that is merely misconfigured. The stateless
+ # `ai-agent-tool-call-failed-repeatedly` rule exists as the low-severity
+ # building block for precisely this, and says so in its description.
+ },
+ {
+ "id": "wd-ai-model-fanout",
+ "name": "AI agent called an unusual number of distinct models",
+ "severity": "medium",
+ "category": "application",
+ "mitre": ["T1078"],
+ "match_when": {"tool_name_startswith": "model:"},
+ "group_by": "agent_id",
+ "threshold": 50,
+ "window_seconds": 300,
+ # Model-shopping at volume is either a runaway loop burning budget or
+ # someone enumerating which providers a key can reach. Both are worth
+ # a look, neither is worth a critical.
+ },
+ {
+ "id": "wd-mfa-fatigue",
+ "name": "MFA fatigue: repeated push denials for one account",
+ "severity": "high",
+ "category": "identity",
+ "mitre": ["T1621"],
+ "match_when": {"event_type": "authentication", "outcome": "denied"},
+ "group_by": "user",
+ "threshold": 8,
+ "window_seconds": 600,
+ # The attack works by wearing the user down, so the signal is
+ # repetition against a single account rather than any one denial.
+ },
+ {
+ "id": "wd-impossible-travel-volume",
+ "name": "Many distinct source IPs authenticating one account",
+ "severity": "medium",
+ "category": "identity",
+ "mitre": ["T1078"],
+ "match_when": {"event_type": "authentication"},
+ "group_by": "user",
+ "threshold": 25,
+ "window_seconds": 900,
+ # Volume-based rather than geo-based on purpose: geo needs an enrichment
+ # this pipeline does not compute, and inventing a `geo_distance_km`
+ # field would produce a rule that can never fire — the exact defect
+ # `check_detection_fields.py` was written to catch.
+ },
+ {
+ "id": "wd-data-egress-burst",
+ "name": "Burst of outbound transfers from one host",
+ "severity": "high",
+ "category": "data-exfil",
+ "mitre": ["T1041"],
+ "match_when": {"event_type": "network"},
+ "group_by": "hostname",
+ "threshold": 200,
+ "window_seconds": 300,
+ },
+]
+
+
+def build() -> dict:
+ return {"count": len(WINDOWED_RULES), "rules": WINDOWED_RULES}
+
+
+def _strip_count(payload: dict) -> list:
+ return payload.get("rules") or []
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--check", action="store_true", help="fail if the committed JSON is stale")
+ args = parser.parse_args()
+
+ payload = build()
+ rendered = json.dumps(payload, indent=2, sort_keys=True) + "\n"
+
+ ids = [r["id"] for r in WINDOWED_RULES]
+ if len(ids) != len(set(ids)):
+ duplicates = sorted({i for i in ids if ids.count(i) > 1})
+ print(f"ERROR: duplicate windowed rule ids: {duplicates}", file=sys.stderr)
+ return 2
+
+ if args.check:
+ if not OUT.exists():
+ print(f"ERROR: {OUT.relative_to(ROOT)} missing — run scripts/export_windowed_ruleset.py", file=sys.stderr)
+ return 1
+ if _strip_count(json.loads(OUT.read_text(encoding="utf-8"))) != _strip_count(payload):
+ print(
+ f"ERROR: {OUT.relative_to(ROOT)} is stale. Run: python3 scripts/export_windowed_ruleset.py",
+ file=sys.stderr,
+ )
+ return 1
+ print(f"OK: windowed ruleset current ({len(WINDOWED_RULES)} rules)")
+ return 0
+
+ OUT.parent.mkdir(parents=True, exist_ok=True)
+ OUT.write_text(rendered, encoding="utf-8")
+ print(f"wrote {OUT.relative_to(ROOT)} — {len(WINDOWED_RULES)} windowed rules")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/services/fusion/app/data/windowed_ruleset.json b/services/fusion/app/data/windowed_ruleset.json
new file mode 100644
index 000000000..b79fe15ea
--- /dev/null
+++ b/services/fusion/app/data/windowed_ruleset.json
@@ -0,0 +1,81 @@
+{
+ "count": 5,
+ "rules": [
+ {
+ "category": "application",
+ "group_by": "agent_id",
+ "id": "wd-ai-agent-tool-denials",
+ "match_when": {
+ "outcome": "denied"
+ },
+ "mitre": [
+ "T1078"
+ ],
+ "name": "AI agent repeatedly denied a tool call",
+ "severity": "high",
+ "threshold": 10,
+ "window_seconds": 300
+ },
+ {
+ "category": "application",
+ "group_by": "agent_id",
+ "id": "wd-ai-model-fanout",
+ "match_when": {
+ "tool_name_startswith": "model:"
+ },
+ "mitre": [
+ "T1078"
+ ],
+ "name": "AI agent called an unusual number of distinct models",
+ "severity": "medium",
+ "threshold": 50,
+ "window_seconds": 300
+ },
+ {
+ "category": "identity",
+ "group_by": "user",
+ "id": "wd-mfa-fatigue",
+ "match_when": {
+ "event_type": "authentication",
+ "outcome": "denied"
+ },
+ "mitre": [
+ "T1621"
+ ],
+ "name": "MFA fatigue: repeated push denials for one account",
+ "severity": "high",
+ "threshold": 8,
+ "window_seconds": 600
+ },
+ {
+ "category": "identity",
+ "group_by": "user",
+ "id": "wd-impossible-travel-volume",
+ "match_when": {
+ "event_type": "authentication"
+ },
+ "mitre": [
+ "T1078"
+ ],
+ "name": "Many distinct source IPs authenticating one account",
+ "severity": "medium",
+ "threshold": 25,
+ "window_seconds": 900
+ },
+ {
+ "category": "data-exfil",
+ "group_by": "hostname",
+ "id": "wd-data-egress-burst",
+ "match_when": {
+ "event_type": "network"
+ },
+ "mitre": [
+ "T1041"
+ ],
+ "name": "Burst of outbound transfers from one host",
+ "severity": "high",
+ "threshold": 200,
+ "window_seconds": 300
+ }
+ ]
+}
diff --git a/services/fusion/app/services/windowed_detection.py b/services/fusion/app/services/windowed_detection.py
index 8caaa1b2b..8031a9d44 100644
--- a/services/fusion/app/services/windowed_detection.py
+++ b/services/fusion/app/services/windowed_detection.py
@@ -23,6 +23,7 @@ import json
import time
import uuid
from dataclasses import dataclass
+from pathlib import Path
from typing import Any
import structlog
@@ -98,12 +99,81 @@ _BUILTIN_RULES: tuple[WindowRule, ...] = (
)
+#: Windowed rules exported from the spec modules, mirroring the stateless
+#: engine's `detection_ruleset.json`. Absent the file, only the builtins load.
+#:
+#: This exists because the windowed engine had three hardcoded rules and no way
+#: to add a fourth without editing this module. That mattered beyond
+#: inconvenience: a large share of the 2,005 quarantined Splunk rules are
+#: `| stats count ... by` aggregations, which cannot be expressed in the
+#: stateless `match_when` at all and have nowhere else to go. The quarantine
+#: README now tells contributors to skip them "until it has one" — this is it.
+_WINDOWED_RULESET_PATH = Path(__file__).resolve().parent.parent / "data" / "windowed_ruleset.json"
+
+
+def load_window_rules(path: Path | None = None) -> tuple[WindowRule, ...]:
+ """Builtins plus any exported windowed rules.
+
+ Fail-soft by design: a missing or malformed ruleset yields the builtins
+ rather than an empty corpus, because silently detecting nothing is worse
+ than detecting only the high-signal three. A malformed entry is skipped
+ individually so one bad rule cannot disable the rest.
+ """
+ target = path or _WINDOWED_RULESET_PATH
+ if not target.exists():
+ return _BUILTIN_RULES
+
+ try:
+ payload = json.loads(target.read_text(encoding="utf-8"))
+ except (ValueError, OSError) as exc:
+ logger.warning("windowed_detection.ruleset_load_failed", path=str(target), error=str(exc))
+ return _BUILTIN_RULES
+
+ loaded: list[WindowRule] = list(_BUILTIN_RULES)
+ seen = {rule.id for rule in _BUILTIN_RULES}
+ for entry in payload.get("rules") or []:
+ if not isinstance(entry, dict):
+ continue
+ rule_id = str(entry.get("id") or "")
+ if not rule_id or rule_id in seen:
+ continue
+ try:
+ rule = WindowRule(
+ id=rule_id,
+ name=str(entry["name"]),
+ severity=str(entry["severity"]),
+ category=str(entry["category"]),
+ mitre=[str(m).upper() for m in entry.get("mitre") or []],
+ match_when=dict(entry["match_when"]),
+ group_by=str(entry["group_by"]),
+ threshold=int(entry["threshold"]),
+ window_seconds=int(entry["window_seconds"]),
+ )
+ except (KeyError, TypeError, ValueError) as exc:
+ logger.warning("windowed_detection.rule_skipped", rule_id=rule_id, error=str(exc))
+ continue
+ if rule.threshold < 1 or rule.window_seconds < 1:
+ # A zero threshold fires on the first event, which is a stateless
+ # rule wearing a windowed rule's clothes, and a zero window never
+ # accumulates. Both are authoring mistakes, not policies.
+ logger.warning("windowed_detection.rule_bounds_invalid", rule_id=rule_id)
+ continue
+ loaded.append(rule)
+ seen.add(rule_id)
+
+ logger.info("windowed_detection.ruleset_loaded", count=len(loaded), builtins=len(_BUILTIN_RULES))
+ return tuple(loaded)
+
+
class WindowedDetectionEngine:
"""Redis-backed sliding-window threshold detections."""
- def __init__(self, redis: Any, rules: tuple[WindowRule, ...] = _BUILTIN_RULES, *, key_prefix: str = "aisoc:wd") -> None:
+ def __init__(self, redis: Any, rules: tuple[WindowRule, ...] | None = None, *, key_prefix: str = "aisoc:wd") -> None:
self._redis = redis
- self._rules = rules
+ # None means "whatever is declared", so a deployment picks up exported
+ # rules without a code change. An explicit tuple still wins, which is
+ # what the tests rely on.
+ self._rules = rules if rules is not None else load_window_rules()
self._prefix = key_prefix
@property
@@ -112,19 +182,37 @@ class WindowedDetectionEngine:
@staticmethod
def _fields(message: dict[str, Any]) -> dict[str, Any]:
+ """Flat field namespace, matching the stateless engine exactly.
+
+ Carries the same fix: `raw_data` holds the connector's normalized dict
+ and connectors put the untouched vendor payload one level down under
+ `raw_event`, so a rule naming a vendor field read None and could never
+ fire. Both engines must agree on the namespace, or a rule that works
+ stateless would silently not work windowed.
+
+ Connector-normalized keys win on collision, for the same reason: a
+ connector that mapped a vendor's severity ladder onto AiSOC's five
+ tiers must not have that undone by the raw vendor value.
+ """
ocsf = message.get("ocsf_event")
if not isinstance(ocsf, dict):
return {}
+ fields = ocsf
raw = ocsf.get("raw_data")
if isinstance(raw, str) and raw.strip():
try:
parsed = json.loads(raw)
if isinstance(parsed, dict):
- return parsed
+ fields = parsed
except (ValueError, TypeError):
# raw_data isn't valid JSON — fall back to the OCSF envelope.
pass
- return ocsf
+ nested = fields.get("raw_event")
+ if isinstance(nested, dict):
+ merged = {k: v for k, v in nested.items() if isinstance(k, str)}
+ merged.update(fields)
+ return merged
+ return fields
async def evaluate(self, message: dict[str, Any]) -> list[DetectionHit]:
"""Count this event into any matching window; return threshold-crossing hits."""
diff --git a/services/fusion/tests/test_windowed_ruleset_loader.py b/services/fusion/tests/test_windowed_ruleset_loader.py
new file mode 100644
index 000000000..2b5f980ca
--- /dev/null
+++ b/services/fusion/tests/test_windowed_ruleset_loader.py
@@ -0,0 +1,160 @@
+"""Windowed rules must be declarable without editing the engine.
+
+The windowed engine shipped with three hardcoded rules and no loader. That was
+not merely inconvenient: a large share of the ~2,000 quarantined Splunk rules
+are `| stats count ... by` aggregations, which cannot be expressed in the
+stateless `match_when` at all because that matcher sees one event in isolation.
+They had nowhere to go, which is most of why the quarantine never shrank. The
+quarantine README told contributors to skip them "until it has one".
+
+The loader is deliberately fail-soft in one direction only. A missing or
+malformed ruleset falls back to the builtins rather than to an empty corpus,
+because silently detecting nothing is worse than detecting only the
+high-signal three — and an operator reading "0 rules loaded" in a log line is
+far less likely than noticing alerts stopped.
+"""
+
+from __future__ import annotations
+
+import json
+
+from app.services.windowed_detection import (
+ _BUILTIN_RULES,
+ WindowedDetectionEngine,
+ load_window_rules,
+)
+
+VALID = {
+ "id": "wd-test-rule",
+ "name": "Test",
+ "severity": "high",
+ "category": "identity",
+ "mitre": ["t1110"],
+ "match_when": {"event_type": "authentication"},
+ "group_by": "user",
+ "threshold": 5,
+ "window_seconds": 300,
+}
+
+
+def _write(tmp_path, rules):
+ path = tmp_path / "windowed_ruleset.json"
+ path.write_text(json.dumps({"count": len(rules), "rules": rules}), encoding="utf-8")
+ return path
+
+
+# ── loading ───────────────────────────────────────────────────────────────
+
+
+def test_declared_rules_are_added_to_the_builtins(tmp_path):
+ rules = load_window_rules(_write(tmp_path, [VALID]))
+ assert len(rules) == len(_BUILTIN_RULES) + 1
+ assert any(r.id == "wd-test-rule" for r in rules)
+
+
+def test_the_committed_ruleset_loads(tmp_path):
+ """Guards the real artifact, not just a fixture."""
+ rules = load_window_rules()
+ assert len(rules) > len(_BUILTIN_RULES)
+ ids = {r.id for r in rules}
+ assert "wd-ai-agent-tool-denials" in ids
+ assert "wd-mfa-fatigue" in ids
+
+
+def test_mitre_ids_are_upper_cased():
+ """So coverage mapping joins against the ATT&CK catalogue."""
+ rules = load_window_rules()
+ for rule in rules:
+ for technique in rule.mitre:
+ assert technique == technique.upper()
+
+
+# ── fail-soft, in the right direction ─────────────────────────────────────
+
+
+def test_a_missing_ruleset_keeps_the_builtins(tmp_path):
+ rules = load_window_rules(tmp_path / "absent.json")
+ assert rules == _BUILTIN_RULES
+
+
+def test_malformed_json_keeps_the_builtins(tmp_path):
+ path = tmp_path / "bad.json"
+ path.write_text("{not json", encoding="utf-8")
+ assert load_window_rules(path) == _BUILTIN_RULES
+
+
+def test_one_bad_rule_does_not_disable_the_others(tmp_path):
+ """A single authoring mistake must not empty the corpus."""
+ broken = {"id": "wd-broken"} # missing every required field
+ rules = load_window_rules(_write(tmp_path, [broken, VALID]))
+ ids = {r.id for r in rules}
+ assert "wd-test-rule" in ids
+ assert "wd-broken" not in ids
+
+
+# ── bounds ────────────────────────────────────────────────────────────────
+
+
+def test_a_zero_threshold_is_rejected(tmp_path):
+ """That is a stateless rule wearing a windowed rule's clothes.
+
+ Threshold 0 fires on the first matching event, which means it would
+ duplicate the stateless engine while paying for Redis state.
+ """
+ rules = load_window_rules(_write(tmp_path, [{**VALID, "threshold": 0}]))
+ assert not any(r.id == "wd-test-rule" for r in rules)
+
+
+def test_a_zero_window_is_rejected(tmp_path):
+ """Nothing ever accumulates, so the rule can never fire."""
+ rules = load_window_rules(_write(tmp_path, [{**VALID, "window_seconds": 0}]))
+ assert not any(r.id == "wd-test-rule" for r in rules)
+
+
+def test_a_duplicate_id_does_not_shadow_a_builtin(tmp_path):
+ """Otherwise a declared rule could silently weaken a builtin threshold."""
+ clash = {**VALID, "id": _BUILTIN_RULES[0].id, "threshold": 9999}
+ rules = load_window_rules(_write(tmp_path, [clash]))
+ matching = [r for r in rules if r.id == _BUILTIN_RULES[0].id]
+ assert len(matching) == 1
+ assert matching[0].threshold == _BUILTIN_RULES[0].threshold
+
+
+# ── the field namespace must match the stateless engine ───────────────────
+
+
+def test_vendor_fields_under_raw_event_are_visible():
+ """Both engines must agree on the namespace.
+
+ Otherwise a rule that works stateless silently does not work windowed,
+ which is the harder failure to notice of the two.
+ """
+ fields = WindowedDetectionEngine._fields(
+ {"ocsf_event": {"raw_data": json.dumps({"source": "imperva", "severity": "high", "raw_event": {"agent_id": "bot-1"}})}}
+ )
+ assert fields["agent_id"] == "bot-1"
+ assert fields["source"] == "imperva"
+
+
+def test_connector_normalization_wins_on_collision():
+ fields = WindowedDetectionEngine._fields(
+ {"ocsf_event": {"raw_data": json.dumps({"severity": "critical", "raw_event": {"severity": "SEV-3"}})}}
+ )
+ assert fields["severity"] == "critical"
+
+
+def test_a_message_without_an_ocsf_event_is_empty():
+ assert WindowedDetectionEngine._fields({}) == {}
+ assert WindowedDetectionEngine._fields({"ocsf_event": "not-a-dict"}) == {}
+
+
+def test_the_engine_defaults_to_the_declared_set():
+ """A deployment picks up exported rules without a code change."""
+ engine = WindowedDetectionEngine(redis=None)
+ assert engine.rule_count > len(_BUILTIN_RULES)
+
+
+def test_an_explicit_rule_tuple_still_wins():
+ """Tests and targeted deployments need to pin the corpus."""
+ engine = WindowedDetectionEngine(redis=None, rules=_BUILTIN_RULES)
+ assert engine.rule_count == len(_BUILTIN_RULES)