Files
AiSOC/scripts/connector_normalize_worker.py
T
Beenu AroraandBeenu Arora 9891c46e1e feat(detections): raise the executable corpus from 833 to 2,603 rules (#898)
* feat(detections): raise the executable corpus from 833 to 2,603 rules

The library has held ~7,000 ATT&CK-mapped rules while 833 executed. The
blocker was concrete: a Windows event nests its payload one level below
anything the engine flattens, so CommandLine and Image - the two most-used
fields in the Sigma corpus - read None and no Windows rule could fire.

- windows_event.normalize() lifts System and EventData, where envelope
  knowledge belongs. The engine and matcher are untouched, so the existing
  833 rules are provably unaffected: all 1,756 fixtures replay to identical
  native verdicts, now a standing test.
- sigma_compiler translates imported Sigma to match_when or refuses with a
  reason. Case sensitivity and missing-field semantics drive most refusals;
  1,770 ship, 1,362 are refused and counted.
- Every shipped rule is replayed, as a vendor-shaped event, through the real
  connector and the real engine. --prove-gate reverts the connector and
  requires all 1,687 Windows rules to stop firing, so the proof can fail.
- 76 enabled-but-never-loaded rules are marked disabled with a reason, and
  the truth table now fails on any new one.

* fix(ci): resync the marketplace index, and make a comment's promised test real

Four CI failures from the parent commit:

- The compiled-ruleset gate imports the connector package, which reaches
  cryptography through gcp_cloud_audit. Added to the workflow's install.
- marketplace/index.json carried enabled: true for the 76 rules this branch
  marks disabled, so the generated index disagreed with the corpus.
- A docstring still named check_rule_fireability.py, which was renamed to
  compile_sigma_ruleset.py before it landed.
- scripts/measure_triage_reliability.py says its production constants 'are
  asserted against it in tests/test_triage_reliability_harness.py'. That file
  did not exist - the comment-paths gate has been failing on main since #896 -
  so the constants could drift from the call site and the published 44/50 to
  50/50 figure would quietly describe a configuration nobody runs. Writing the
  test makes the claim true rather than deleting the claim.

* fix(ci): bound cryptography in the detections workflow, and raise instead of falling through

- The dependency-pin gate refuses an unbounded cryptography: the Fernet token
  format and the Ed25519 plugin signatures are behaviour shared across
  services, so an unbounded install means a build running software nobody
  tested. Bounded to >=46,<51 to match the other fifteen paths.
- The harness test reached pytest.fail() as its last statement, which mypy and
  CodeQL both read as a path returning None beside paths returning a value
  (py/mixed-returns, union-attr). Raising AssertionError says the same thing
  in a form both understand, and pulling the regex match into one helper
  removes the second unguarded .group() call.

* fix(detections): count quarantine by what the engine loads, not by directory

Two published figures still read a file path where the engine is the source
of truth, and the Sigma compiler made both of them wrong in the same way -
1,724 rules now execute while their files remain under _quarantine/.

- generate_corpus_stats.py read only the native ruleset, so it reported 833
  against a truth table correctly saying 2603 and failed. That is the gate
  it exists to be, aimed at the stale side of the comparison.
- build_marketplace.py derived 'quarantined' from _quarantine/ membership,
  publishing 5937 quarantined when 4213 is the number that cannot fire.

Both now ask the engine. The marketplace figure matches the truth table's
quarantine count exactly, which is the cross-check that would have caught
this had either one been derived the same way.

* fix(detections): the last two published figures that read one ruleset

project_stats.py counted only the native ruleset, so it reported 833 against
a README correctly saying 2603 and failed the golden-pipeline gate. llms.txt
regenerated for the same reason.

The two scripts still reading detection_ruleset.json alone are deliberate:
export_detection_ruleset.py writes it, and check_detection_fields.py is
scoped to native rules because imported ones are held to the stronger
replay proof instead - both say so where a reader will find it.

---------

Co-authored-by: Beenu Arora <beenu@MacBook-Pro-3.local>
2026-09-26 11:06:25 -07:00

88 lines
3.5 KiB
Python

#!/usr/bin/env python3
"""Run raw vendor payloads through a real connector's ``normalize()``.
A separate process because ``services/connectors`` and ``services/fusion`` both
ship their code under the package name ``app``, so only one of them can be
importable at a time. Shelling out keeps the fireability proof running against
the **real** connector rather than a copy of its mapping — a test that
reimplements the thing it is testing is the failure mode this repository keeps
finding, so the extra process is the cheaper side of that trade.
Reads JSON lines of ``{"emitter": "...", "raw": {...}}`` on stdin and writes
JSON lines of ``{"ok": true, "normalized": {...}}`` or ``{"ok": false,
"error": "..."}`` on stdout, one per input line and in the same order.
``--no-lift`` constructs the connector's pre-fix behaviour, where a Windows
event's ``System``/``EventData`` containers stayed nested. The fireability gate
uses it to prove it is not vacuous: rules that depend on the lift must stop
firing when it is removed.
"""
from __future__ import annotations
import argparse
import inspect
import json
import sys
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "services" / "connectors"))
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--no-lift", action="store_true", help="simulate the pre-fix connector")
args = parser.parse_args()
from app.connectors import _CONNECTOR_CLASSES # noqa: PLC0415
by_id = {cls.connector_id: cls for cls in _CONNECTOR_CLASSES}
instances: dict[str, object] = {}
def instantiate(cls: Any) -> Any:
"""Build a connector whose ``normalize()`` can run.
``normalize()`` is pure, but some connectors read configuration set in
``__init__`` (the CloudTrail one stamps the region onto each record).
Placeholders come from the constructor signature rather than a
per-connector table, so a new connector needs no change here.
"""
kwargs: dict[str, Any] = {}
for name, param in inspect.signature(cls.__init__).parameters.items():
if name == "self" or param.kind in {param.VAR_POSITIONAL, param.VAR_KEYWORD}:
continue
if param.default is not inspect.Parameter.empty:
continue
kwargs[name] = False if param.annotation is bool else f"proof-{name}"
try:
return cls(**kwargs)
except Exception: # noqa: BLE001 — fall back to a bare instance
return cls.__new__(cls)
for line in sys.stdin:
line = line.strip()
if not line:
continue
try:
req = json.loads(line)
emitter = req["emitter"]
cls = by_id.get(emitter)
if cls is None:
raise KeyError(f"no connector registered as {emitter!r}")
if emitter not in instances:
instances[emitter] = instantiate(cls)
normalized = cls.normalize(instances[emitter], req["raw"])
if args.no_lift and isinstance(normalized.get("raw_event"), dict):
normalized["raw_event"] = req["raw"]
print(json.dumps({"ok": True, "normalized": normalized}, default=str))
except Exception as exc: # noqa: BLE001 — reported per line, never fatal
print(json.dumps({"ok": False, "error": f"{type(exc).__name__}: {exc}"}))
sys.stdout.flush()
return 0
if __name__ == "__main__":
raise SystemExit(main())