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.

perf(fusion): index rules by required field, not by log source (parity 6.9)

Beenu Arora18753685c399
diff --git a/services/fusion/app/services/detection_engine.py b/services/fusion/app/services/detection_engine.py
index 1815c7cea..7a8185de5 100644
--- a/services/fusion/app/services/detection_engine.py
+++ b/services/fusion/app/services/detection_engine.py
@@ -19,18 +19,23 @@ as a JSON string. The native ``match_when`` specs were authored against exactly
those flat connector fields, so ``matches(rule.match_when, json.loads(raw_data))``
is the correct evaluation contract.
-Performance: every event is evaluated against the **whole corpus**. A
-product-based pre-filter was tried and removed, because connector product
-names do not line up with spec products (``aws_cloudtrail`` against ``aws``,
-``crowdstrike_falcon`` against ``edr``) and any such filter silently drops
-real matches. See ``_candidates``, which returns ``self._rules`` unchanged
-and records that reasoning. The full pass is cheap because the matcher
-short-circuits on the first absent field, so a benign event touches almost
-no rule past its first clause. The engine is pure and synchronous; the
-consumer calls it inline.
-
-Indexing by log source is parity plan 6.9, and it has to solve the
-product-name mapping first.
+Performance: parity plan 6.9 / depth plan 4.4. Events are routed through
+``app.services.rule_index``, which maps an event's field *names* to the
+rules that could possibly match it.
+
+Not by log source, which is what the plan asks for and what this module
+previously recorded as unsafe: connector product names do not line up
+with spec products (``aws_cloudtrail`` against ``aws``,
+``crowdstrike_falcon`` against ``edr``), a product-based pre-filter was
+tried and reverted for silently dropping real matches, and a mapping
+table would leave every new connector one missing entry away from a
+detection that stops firing. The index is on required fields instead,
+which is strictly more selective *and* provably lossless: ``match_when``
+is an AND at the top level, so a rule that requires a field an event does
+not carry cannot match it, whatever the product names say. ADR-0011
+records the decision.
+
+The engine is pure and synchronous; the consumer calls it inline.
"""
from __future__ import annotations
@@ -49,6 +54,7 @@ from app.services.derived_fields import enrich, requested_derived_fields
from app.services.detection_matcher import matches
from app.services.provenance import extract_provenance
from app.services.raw_data import decode_raw_data
+from app.services.rule_index import RuleIndex
logger = structlog.get_logger()
@@ -103,21 +109,53 @@ class DetectionEngine:
# change, not when traffic arrives. Doing it per event would mean a
# regex over every rule's clauses for every ingested event.
self._derived_wanted: set[str] = requested_derived_fields(self._rules)
+ # Parity 6.9. Built once at load for the same reason.
+ self._index = RuleIndex(self._rules)
+ logger.info(
+ "detection_engine.rule_index_built",
+ rules=self._index.stats.rules,
+ indexed=self._index.stats.indexed,
+ always_evaluated=self._index.stats.always_evaluated,
+ distinct_pivot_fields=self._index.stats.distinct_fields,
+ )
@property
def rule_count(self) -> int:
return len(self._rules)
- def _candidates(self, product: str) -> list[dict[str, Any]]:
- # Correctness-first routing: evaluate the whole corpus against every
- # event. Connector product names don't line up 1:1 with spec products
- # (``aws_cloudtrail`` vs ``aws``, ``crowdstrike_falcon`` vs ``edr``), so
- # any product-based pre-filter risks silently dropping a real match.
- # The matcher short-circuits on the first absent field, so a full pass
- # over ~800 rules is cheap in practice (a benign event touches almost
- # none of them past the first clause).
+ @property
+ def rules(self) -> list[dict[str, Any]]:
+ """The loaded corpus, in order.
+
+ Exposed so the index's losslessness test can replay every
+ fixture through the unindexed path and compare. A test that
+ reached into ``_rules`` would be asserting against a private
+ name, and the comparison is the only thing making the index
+ safe to ship.
+ """
return self._rules
+ def _candidates(self, fields: dict[str, Any]) -> list[dict[str, Any]]:
+ """Rules this event could possibly match, in corpus order.
+
+ Lossless by construction rather than by configuration: a rule is
+ only skipped when the event lacks a field the rule's own clause
+ cannot be satisfied without, which the index establishes by
+ running the real matcher against an empty event. Rules with no
+ such field are in every candidate list.
+
+ ``index_stats`` and the parity test
+ (``test_rule_index_is_lossless.py``) are what keep that true: the
+ test replays the whole corpus both ways over every fixture and
+ requires identical hits.
+ """
+ return self._index.candidates(fields)
+
+ @property
+ def index_stats(self):
+ """What the index did, for the log line and for the gate."""
+ return self._index.stats
+
@staticmethod
def _raw_fields(ocsf: dict[str, Any]) -> dict[str, Any]:
"""Recover the flat field namespace the specs match on.
@@ -239,7 +277,7 @@ class DetectionEngine:
fields = {**fields, **_extra_fields}
hits: list[DetectionHit] = []
- for rule in self._candidates(""):
+ for rule in self._candidates(fields):
try:
if matches(rule["match_when"], fields):
if overlay is not None:
diff --git a/services/fusion/app/services/rule_index.py b/services/fusion/app/services/rule_index.py
new file mode 100644
index 000000000..5ddff09ff
--- /dev/null
+++ b/services/fusion/app/services/rule_index.py
@@ -0,0 +1,156 @@
+"""An index that stops fusion running every rule against every event.
+
+Parity plan 6.9 / depth plan 4.4.
+
+Why not "index by log source", which is what the plan says
+---------------------------------------------------------
+Because the engine's own docstring already records why that cannot be the
+index: connector product names do not line up with the products the specs
+name — ``aws_cloudtrail`` against ``aws``, ``crowdstrike_falcon`` against
+``edr`` — and a pre-filter built on them silently drops real matches. A
+previous attempt at exactly that was tried and reverted. Shipping it again
+with a mapping table would mean every new connector is one missing table
+entry away from a detection that stops firing, with nothing failing.
+
+What is indexed instead
+-----------------------
+The fields a rule **requires**. ``match_when`` is an AND at the top level,
+so if any one of its clauses cannot be satisfied by an event that lacks a
+field, that field's presence is necessary for the rule to fire at all. A
+rule requiring ``Image`` cannot match an event with no ``Image``, whatever
+the product names say.
+
+That is a strictly stronger filter than log source *and* it is provably
+lossless, which log source is not. It also needs no mapping table, so a
+new connector cannot silently fall out of coverage.
+
+How "required" is decided
+-------------------------
+Not by reading the operator name. By **running the real matcher** against
+an empty event, once per clause at load time:
+
+ _check(field, op, expected, {}) is False => the field is required
+
+That is the definition, executed rather than restated. An operator that
+tolerates absence — ``neq`` against a missing field is true, ``not_in`` is
+true, ``eq: null`` is a presence *check* — answers True on the empty event
+and the field is correctly not treated as required. A matcher that grows a
+new operator is classified correctly the day it is added, because nothing
+here enumerates operators.
+
+Anything that raises, or that the shape of the clause makes unclear, is
+treated as **not** required. The failure directions are not symmetric:
+over-claiming a requirement drops a real detection silently, while
+under-claiming only costs the full pass for that rule.
+"""
+
+from __future__ import annotations
+
+from collections import defaultdict
+from dataclasses import dataclass
+from typing import Any
+
+from app.services.detection_matcher import _check, _split_op
+
+
+@dataclass(frozen=True)
+class IndexStats:
+ """What the index did, for the log line and for the gate."""
+
+ rules: int
+ indexed: int
+ always_evaluated: int
+ distinct_fields: int
+
+ @property
+ def indexed_fraction(self) -> float:
+ return self.indexed / self.rules if self.rules else 0.0
+
+
+def required_fields(match_when: dict[str, Any]) -> set[str]:
+ """Fields whose absence guarantees this rule cannot match.
+
+ Only the top level is considered. ``any_of`` and ``all_of`` are
+ skipped: a field inside an ``any_of`` is not required, because another
+ branch may satisfy it, and a nested ``all_of`` is only required if the
+ whole group is — a refinement that would buy little and could be
+ wrong, which is the one thing this must not be.
+ """
+ if not isinstance(match_when, dict):
+ return set()
+ required: set[str] = set()
+ for key, expected in match_when.items():
+ if key in {"any_of", "all_of"}:
+ continue
+ field, op = _split_op(key)
+ if not field:
+ continue
+ try:
+ satisfied_by_absence = _check(field, op, expected, {})
+ except Exception: # noqa: BLE001 — see the module docstring
+ # A clause the matcher cannot evaluate against an empty event
+ # is not evidence that the field is required. Treated as not
+ # required, which costs a full pass and loses nothing.
+ continue
+ if not satisfied_by_absence:
+ required.add(field)
+ return required
+
+
+class RuleIndex:
+ """Maps an event's field names to the rules that could possibly match.
+
+ One pivot field per rule, chosen as the **rarest** of its required
+ fields. Rarest rather than first: ``EventID`` is required by hundreds
+ of Windows rules and ``Provider_Name`` by a handful, so pivoting on
+ the first key encountered would put most of the corpus in one bucket
+ and index almost nothing in practice.
+ """
+
+ def __init__(self, rules: list[dict[str, Any]]) -> None:
+ self._rules = rules
+ self._by_field: dict[str, list[int]] = defaultdict(list)
+ #: Rules with no required field at all. Evaluated against every
+ #: event, because nothing about the event can rule them out.
+ self._always: list[int] = []
+
+ requirements = [required_fields(rule.get("match_when") or {}) for rule in rules]
+
+ frequency: dict[str, int] = defaultdict(int)
+ for fields in requirements:
+ for field in fields:
+ frequency[field] += 1
+
+ for position, fields in enumerate(requirements):
+ if not fields:
+ self._always.append(position)
+ continue
+ pivot = min(sorted(fields), key=lambda f: (frequency[f], f))
+ self._by_field[pivot].append(position)
+
+ self._stats = IndexStats(
+ rules=len(rules),
+ indexed=len(rules) - len(self._always),
+ always_evaluated=len(self._always),
+ distinct_fields=len(self._by_field),
+ )
+
+ @property
+ def stats(self) -> IndexStats:
+ return self._stats
+
+ def candidates(self, fields: dict[str, Any]) -> list[dict[str, Any]]:
+ """Rules that could match an event carrying these field names.
+
+ Returned in the corpus's own order. The full pass yields hits in
+ rule order and callers (and the alert the hits become) depend on
+ that, so an index that returned them bucket by bucket would change
+ behaviour while claiming only to change cost.
+ """
+ positions: set[int] = set(self._always)
+ by_field = self._by_field
+ for name in fields:
+ bucket = by_field.get(name)
+ if bucket is not None:
+ positions.update(bucket)
+ return [self._rules[i] for i in sorted(positions)]
diff --git a/services/fusion/tests/test_rule_index_is_lossless.py b/services/fusion/tests/test_rule_index_is_lossless.py
new file mode 100644
index 000000000..fcc005f0a
--- /dev/null
+++ b/services/fusion/tests/test_rule_index_is_lossless.py
@@ -0,0 +1,244 @@
+"""The rule index must not drop a detection (parity 6.9 / depth 4.4).
+
+This is the only thing that makes the index safe to ship. A pre-filter on
+this corpus has been tried once before and reverted for silently dropping
+real matches, and "silently" is the word that matters: a detection that
+stops firing produces no error, no log line and no failing test unless
+something is comparing the filtered path against the unfiltered one.
+
+So that comparison is the test. Every committed detection fixture is
+replayed through the real engine twice — once with the index and once
+with the index bypassed — and the hit lists must be identical, in the
+same order.
+
+A second property is checked on random events rather than fixtures,
+because fixtures are synthesised from the rules they test and therefore
+only ever exercise the matching case. The interesting direction is an
+event that matches *nothing*: that is where an over-eager index saves the
+most work and where a wrong one is invisible.
+"""
+
+from __future__ import annotations
+
+import json
+import random
+from pathlib import Path
+
+import pytest
+from app.services.detection_engine import DetectionEngine
+from app.services.detection_matcher import matches
+from app.services.rule_index import RuleIndex, required_fields
+
+REPO_ROOT = Path(__file__).resolve().parents[3]
+FIXTURE_ROOT = REPO_ROOT / "detections"
+
+
[email protected](scope="module")
+def engine() -> DetectionEngine:
+ return DetectionEngine()
+
+
+def _all_hits_unindexed(engine: DetectionEngine, fields: dict) -> list[str]:
+ """What the whole corpus would have said, in corpus order."""
+ return [rule["id"] for rule in engine.rules if _safe_match(rule, fields)]
+
+
+def _safe_match(rule: dict, fields: dict) -> bool:
+ try:
+ return bool(matches(rule["match_when"], fields))
+ except Exception:
+ # The engine swallows a raising rule too, so the comparison has to
+ # as well or it would report a difference the engine cannot have.
+ return False
+
+
+def _indexed_hits(engine: DetectionEngine, fields: dict) -> list[str]:
+ return [rule["id"] for rule in engine._candidates(fields) if _safe_match(rule, fields)]
+
+
+def _fixture_events(limit: int | None = None) -> list[dict]:
+ """Every committed positive fixture, as the flat field namespace."""
+ events: list[dict] = []
+ if not FIXTURE_ROOT.is_dir():
+ return events
+ for path in sorted(FIXTURE_ROOT.rglob("*.json")):
+ if "fixture" not in path.as_posix() and "fixtures" not in path.as_posix():
+ continue
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ continue
+ for candidate in _flatten_fixture(payload):
+ events.append(candidate)
+ if limit is not None and len(events) >= limit:
+ return events
+ return events
+
+
+def _flatten_fixture(payload) -> list[dict]:
+ """Pull event-shaped dicts out of whatever the fixture file holds."""
+ out: list[dict] = []
+ if isinstance(payload, dict):
+ for key in ("positive", "negative", "events", "event"):
+ value = payload.get(key)
+ if isinstance(value, dict):
+ out.append(value)
+ elif isinstance(value, list):
+ out.extend(item for item in value if isinstance(item, dict))
+ if not out and payload:
+ out.append(payload)
+ elif isinstance(payload, list):
+ out.extend(item for item in payload if isinstance(item, dict))
+ return out
+
+
+# ---------------------------------------------------------------------------
+
+
+#: Measured on this corpus, not chosen: 1,751 of 2,511 loaded rules carry
+#: at least one required field, which is 0.6974. The floor sits just under
+#: the measurement so the figure can only be ratcheted up, and so a change
+#: that moves it down has to say so in the same commit. A floor chosen
+#: comfortably below reality is a gate that can never fail, which this
+#: repository has measured the cost of on the performance workflow.
+MEASURED_INDEXED_FRACTION = 0.6974
+INDEXED_FRACTION_FLOOR = 0.69
+
+
+def test_the_corpus_is_actually_indexed(engine):
+ """An index that indexes nothing is a no-op wearing a name."""
+ stats = engine.index_stats
+ assert stats.rules > 500, f"only {stats.rules} rules loaded; the corpus did not load"
+ assert stats.indexed_fraction >= INDEXED_FRACTION_FLOOR, (
+ f"only {stats.indexed} of {stats.rules} rules carry a required field "
+ f"({stats.indexed_fraction:.4f}); the measurement this floor was set from was "
+ f"{MEASURED_INDEXED_FRACTION}"
+ )
+
+
+def test_every_fixture_gets_the_same_hits_both_ways(engine):
+ events = _fixture_events()
+ assert events, "no fixtures were found, so this test proves nothing"
+ differing: list[tuple[int, list[str], list[str]]] = []
+ for position, fields in enumerate(events):
+ indexed = _indexed_hits(engine, fields)
+ full = _all_hits_unindexed(engine, fields)
+ if indexed != full:
+ differing.append((position, full, indexed))
+ if len(differing) >= 5:
+ break
+ assert not differing, (
+ f"the index changed the verdict on {len(differing)} fixture(s); first: full={differing[0][1]} indexed={differing[0][2]}"
+ )
+
+
+def test_a_random_event_that_matches_nothing_also_agrees(engine):
+ """Fixtures are synthesised from the rules they test, so they only
+ exercise the matching case. The direction that matters for an index
+ is the event that matches nothing."""
+ rng = random.Random(20261011)
+ vocabulary = ["user", "src_ip", "action", "message", "host", "Image", "EventID", "CommandLine"]
+ for _ in range(200):
+ fields = {rng.choice(vocabulary): rng.choice(["alice", "198.51.100.4", "login", "ok", "7", ""]) for _ in range(rng.randint(1, 4))}
+ assert _indexed_hits(engine, fields) == _all_hits_unindexed(engine, fields), fields
+
+
+def test_an_event_with_no_fields_at_all_agrees(engine):
+ # The degenerate case the index's own definition is built on.
+ assert _indexed_hits(engine, {}) == _all_hits_unindexed(engine, {})
+
+
+# ---------------------------------------------------------------------------
+# The classification itself.
+# ---------------------------------------------------------------------------
+
+
+def test_a_positive_clause_makes_its_field_required():
+ assert required_fields({"Image_contains_any": ["cmd.exe"]}) == {"Image"}
+ assert required_fields({"user": "root"}) == {"user"}
+
+
+ "clause",
+ [
+ {"user_not_in": ["root"]},
+ {"user": None},
+ {"any_of": [{"user": "root"}]},
+ ],
+)
+def test_a_clause_satisfiable_without_the_field_does_not_require_it(clause):
+ # Each of these is true of an event that has no `user` at all. Treating
+ # the field as required would drop a rule that should have fired.
+ assert required_fields(clause) == set()
+
+
+def test_neq_requires_its_field_in_this_matcher_whatever_the_name_suggests():
+ """The reason the classification is executed rather than written down.
+
+ ``neq`` reads like a negation and would be in anyone's hand-written
+ list of absence-tolerant operators. This matcher's ``neq`` returns
+ False for a missing field on purpose — its own comment says a rule
+ using it must not fire on absence of data — so the field *is*
+ required, and a hand-maintained list would have got it wrong in the
+ direction that drops detections.
+
+ Writing this test is how that was found: the first version asserted
+ the opposite and failed.
+ """
+ assert required_fields({"user_neq": "root"}) == {"user"}
+
+
+def test_classification_runs_the_matcher_rather_than_naming_operators():
+ """The definition is executed, not restated.
+
+ A matcher that grows an operator is classified correctly the day it is
+ added. This asserts the property the implementation rests on: for
+ every required field, the real matcher says False on an empty event.
+ """
+ from app.services.detection_matcher import _check, _split_op # noqa: PLC0415
+
+ engine = DetectionEngine()
+ checked = 0
+ for rule in engine.rules:
+ clauses = rule.get("match_when") or {}
+ for field in required_fields(clauses):
+ # At least one clause on this field must refuse the empty
+ # event. A rule can carry several clauses on one field - a
+ # `contains_any` and a `not_contains_any` on `TargetName`,
+ # say - and only one of them has to be the reason the field
+ # is required. Requiring all of them was this test's own bug
+ # on the first run.
+ refusals = [
+ key
+ for key, expected in clauses.items()
+ if _split_op(key)[0] == field and _check(field, _split_op(key)[1], expected, {}) is False
+ ]
+ assert refusals, f"{rule['id']} treats {field} as required but no clause on it refuses an empty event"
+ checked += 1
+ assert checked > 100, f"only {checked} fields walked; the corpus did not load"
+
+
+def test_the_index_puts_unconstrained_rules_in_every_candidate_list():
+ rules = [
+ {"id": "needs-image", "match_when": {"Image": "cmd.exe"}},
+ # `not_in` is genuinely satisfied by absence in this matcher, so
+ # this rule has no required field and must be in every list.
+ {"id": "needs-nothing", "match_when": {"user_not_in": ["root"]}},
+ ]
+ index = RuleIndex(rules)
+ assert [r["id"] for r in index.candidates({})] == ["needs-nothing"]
+ assert [r["id"] for r in index.candidates({"Image": "x"})] == ["needs-image", "needs-nothing"]
+
+
+def test_candidates_come_back_in_corpus_order():
+ # The hits a caller gets are in rule order, and an index returning
+ # them bucket by bucket would change behaviour while claiming only to
+ # change cost.
+ rules = [
+ {"id": "a", "match_when": {"z_field": "1"}},
+ {"id": "b", "match_when": {"a_field": "1"}},
+ {"id": "c", "match_when": {"z_field": "2"}},
+ ]
+ index = RuleIndex(rules)
+ got = [r["id"] for r in index.candidates({"a_field": "1", "z_field": "1"})]
+ assert got == ["a", "b", "c"]