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: make the last two fidelity corpora obtainable (#717)
Beenu Arora4ce87654a3ea
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 7836c3f31..2d39f544d 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -265,6 +265,15 @@ jobs:# makes the threshold traceable — an alert fires because an# objective is being missed, and changing the objective changes the# alert.+ # Two of four fidelity datasets shipped a downloader and two did+ # not, so two loaders could parse a full corpus nobody could+ # obtain — and the only numbers for them came from a ten-line+ # micro fixture. The asymmetry was invisible because each half+ # looked complete on its own and nothing compared the two sets.+ - name: Every fidelity dataset is obtainable+ run: |+ python -m pip install --quiet pyyaml+ python scripts/check_fidelity_datasets.py- name: SLO alerts match the declared objectivesrun: |python -m pip install --quiet pyyamldiff --git a/docs/roadmap/v8-progress.md b/docs/roadmap/v8-progress.mdindex 91b312a59..773e5104f 100644--- a/docs/roadmap/v8-progress.md+++ b/docs/roadmap/v8-progress.md@@ -122,18 +122,24 @@ because it imported a component that only existed on #330.## What's still open-- **All five PRs are merged.** Follow-up to re-add the- `DraftFromPromptDialog` Storybook story (was split out of #331- because of cross-branch dependency on #330) is the only loose- end and is staged on `feat/v8-storybook-draftdialog-story`.+- **All five PRs are merged**, and the `DraftFromPromptDialog`+ Storybook story that was split out of #331 has since landed too —+ `apps/web/stories/composite/DraftFromPromptDialog.stories.tsx` is on+ `main`. This tracker still described it as the outstanding loose end,+ which had quietly become false.- This tracker should be updated on every merge with the PR URL andthe merge timestamp.## Out of scope for this pass- T1–T2 fidelity work beyond the AIT-LDS + MITRE Engenuity micro- fixtures (the full-corpus runs are still local-only with floors- committed in `expected_results.yaml`).+ fixtures. The corpora are now *obtainable*:+ `scripts/datasets/download_ait_lds.py` and+ `download_mitre_engenuity.py` close the asymmetry where CICIDS and+ CTU-13 each had a downloader and these two did not — so their+ loaders could parse a full corpus nobody could fetch. Running them is+ still a local, opt-in step, and the `*_full` floors are marked+ `measured: false` until someone does.- Storybook visual-regression in a real browser (pixel-diff) — thecurrent gate is jsdom DOM snapshots, which catch structuralregressions at sub-second cost. Real-browser regression is in thediff --git a/scripts/check_fidelity_datasets.py b/scripts/check_fidelity_datasets.pynew file mode 100644index 000000000..0551a868d--- /dev/null+++ b/scripts/check_fidelity_datasets.py@@ -0,0 +1,156 @@+#!/usr/bin/env python3+"""Gate: every fidelity dataset is obtainable, and unmeasured floors say so.++Two of the four fidelity datasets shipped a downloader and two did not.+`ait_lds_loader.py` and `mitre_engenuity_loader.py` could parse the full+corpora from the day they landed, and there was no way to obtain either —+so the only numbers anyone could produce came from a ten-line micro+fixture. A micro fixture proves the loader parses. It says nothing about+how the classifier behaves at scale, which is the entire question a+fidelity benchmark exists to answer.++The asymmetry was invisible because each half looked complete on its own:+the loaders had tests, the fixtures had thresholds, and nothing compared+the set of loaders against the set of downloaders.++This checks three things:++ 1. Every dataset with a loader has a downloader.+ 2. Every downloader requires explicit licence acceptance. These are+ third-party corpora under attribution terms, and a script that+ fetches one without the operator reading them agrees to terms on+ their behalf.+ 3. A threshold block marked `measured: false` is not presented+ anywhere as an observed result.++Run: python3 scripts/check_fidelity_datasets.py+"""++from __future__ import annotations++import argparse+import re+import sys+from pathlib import Path++try:+ import yaml+except ImportError: # pragma: no cover+ print("PyYAML is required: pip install pyyaml", file=sys.stderr)+ raise SystemExit(2) from None++REPO_ROOT = Path(__file__).resolve().parent.parent+FIDELITY = REPO_ROOT / "services" / "agents" / "tests" / "fidelity"+DOWNLOADS = REPO_ROOT / "scripts" / "datasets"+THRESHOLDS = FIDELITY / "expected_results.yaml"+BENCHMARK_DOCS = (+ REPO_ROOT / "apps" / "docs" / "docs" / "benchmark.md",+ REPO_ROOT / "apps" / "docs" / "docs" / "benchmark-fidelity.md",+)+++def loaders() -> set[str]:+ """Dataset names that have a loader module."""+ return {path.stem.removesuffix("_loader") for path in FIDELITY.glob("*_loader.py")}+++def downloaders() -> set[str]:+ return {path.stem.removeprefix("download_") for path in DOWNLOADS.glob("download_*.py")}+++def check_every_loader_can_be_fed() -> list[str]:+ missing = sorted(loaders() - downloaders())+ return [+ f"{name}: has a loader ({name}_loader.py) and no downloader. The full "+ f"corpus cannot be obtained, so any published number for it comes from "+ f"a micro fixture — which proves the loader parses and nothing else."+ for name in missing+ ]+++def check_downloaders_require_licence_acceptance() -> list[str]:+ errors: list[str] = []+ for path in sorted(DOWNLOADS.glob("download_*.py")):+ source = path.read_text(encoding="utf-8")+ if "--accept-license" not in source:+ errors.append(+ f"{path.name}: does not require --accept-license. These are "+ f"third-party corpora under attribution terms; fetching one "+ f"without the operator reading them agrees on their behalf."+ )+ if "Citation" not in source and "citation" not in source:+ errors.append(+ f"{path.name}: carries no citation. Attribution is a licence " f"condition for every dataset here, not a courtesy."+ )+ return errors+++def check_unmeasured_floors_are_not_published() -> list[str]:+ """A floor nobody has run must not appear as an observed number."""+ if not THRESHOLDS.exists():+ return [f"{THRESHOLDS.relative_to(REPO_ROOT)} is missing"]++ data = yaml.safe_load(THRESHOLDS.read_text(encoding="utf-8")) or {}+ unmeasured = {name for name, entry in data.items() if isinstance(entry, dict) and entry.get("measured") is False}+ if not unmeasured:+ return []++ errors: list[str] = []+ for name in sorted(unmeasured):+ entry = data[name]+ notes = str(entry.get("notes") or "").strip()+ # Must *lead* with the marker. Matching it anywhere passed a note+ # whose third paragraph happened to use the word in passing — a+ # caveat a reader reaches after two paragraphs is not a caveat.+ if not notes.upper().startswith("UNMEASURED"):+ errors.append(+ f"{name}: marked measured:false but its notes do not open "+ f"with UNMEASURED. A reader looking at the floor cannot tell "+ f"it from an observed result."+ )++ # And it must not be quoted as a result in the published docs.+ dataset = str(entry.get("dataset") or name)+ for doc in BENCHMARK_DOCS:+ if not doc.exists():+ continue+ text = doc.read_text(encoding="utf-8")+ pattern = re.compile(+ rf"{re.escape(dataset)}[^\n]*\bfull\b[^\n]*\d+(?:\.\d+)?\s*%",+ re.IGNORECASE,+ )+ if pattern.search(text):+ errors.append(+ f"{name}: {doc.name} quotes a full-corpus percentage for "+ f"{dataset}, but the threshold block says it was never "+ f"measured."+ )+ return errors+++def main(argv: list[str] | None = None) -> int:+ argparse.ArgumentParser(description=__doc__).parse_args(argv)++ if not FIDELITY.is_dir():+ print("fidelity-datasets: harness directory not found", file=sys.stderr)+ return 2++ errors = check_every_loader_can_be_fed() + check_downloaders_require_licence_acceptance() + check_unmeasured_floors_are_not_published()++ if errors:+ print("FIDELITY DATASET GATE FAILED:", file=sys.stderr)+ for error in errors:+ print(f" - {error}", file=sys.stderr)+ return 1++ found = sorted(loaders())+ data = yaml.safe_load(THRESHOLDS.read_text(encoding="utf-8")) or {}+ unmeasured = [name for name, entry in data.items() if isinstance(entry, dict) and entry.get("measured") is False]+ print(f"fidelity-datasets: OK — {len(found)} dataset(s) with a loader " f"({', '.join(found)}), each with a licence-gated downloader")+ if unmeasured:+ print(f" {len(unmeasured)} full-corpus floor(s) not yet measured: " f"{', '.join(sorted(unmeasured))}")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/datasets/download_ait_lds.py b/scripts/datasets/download_ait_lds.pynew file mode 100644index 000000000..54a40cf07--- /dev/null+++ b/scripts/datasets/download_ait_lds.py@@ -0,0 +1,191 @@+#!/usr/bin/env python3+"""Download the AIT Log Data Set V2 for the AiSOC fidelity benchmark.++Usage:+ python scripts/datasets/download_ait_lds.py --accept-license+ [--out datasets/ait-lds]+ [--scenario fox]++Why this exists: `services/agents/tests/fidelity/ait_lds_loader.py` has+been able to parse the full corpus since it landed, and there was no way+to obtain it. CICIDS-2017 and CTU-13 each shipped a downloader; AIT-LDS+and MITRE Engenuity did not, so their fidelity numbers came only from a+committed micro fixture — which is enough to prove the loader parses and+nothing about how the classifier behaves at scale.++That asymmetry is the gap this closes. It does not by itself produce a+full-corpus number: running it is a local, opt-in step, and the harness+says so rather than implying CI measured something it did not.++We do not redistribute AIT-LDS. The repo carries a small `access.log`+micro fixture for CI; this fetches the real thing on request.++License (AIT Log Data Set V2):+ Published by the Austrian Institute of Technology under+ CC BY 4.0. Attribution is required; commercial use is permitted+ under the licence terms. Read them at+ https://zenodo.org/records/5789064 before passing --accept-license.++Citation:+ Landauer, M., Skopik, F., Frank, M., Hotwagner, W., Wurzenberger, M.,+ & Rauber, A. (2023). Maintainable Log Datasets for Evaluation of+ Intrusion Detection Systems. IEEE Transactions on Dependable and+ Secure Computing.+"""++from __future__ import annotations++import argparse+import hashlib+import logging+import sys+from pathlib import Path+from urllib import error as urlerror+from urllib import request as urlrequest++logger = logging.getLogger("download_ait_lds")++#: Zenodo record for AIT-LDS V2. Override with --mirror if the record+#: is superseded; Zenodo assigns a new id per version rather than+#: mutating the old one, so a stale default fails loudly with a 404+#: instead of silently fetching different data.+DEFAULT_MIRROR = "https://zenodo.org/records/5789064/files"++#: One archive per scenario. Hashes are `None` because we have not+#: pinned them — the same honesty convention `download_cicids.py` uses:+#: an unpinned hash means "we have not verified this", and the script+#: says so rather than implying a check it cannot perform.+SCENARIOS: dict[str, dict[str, object]] = {+ "fox": {"file": "fox.zip", "sha256": None, "approx_gb": 3.2},+ "harrison": {"file": "harrison.zip", "sha256": None, "approx_gb": 2.8},+ "russellmitchell": {"file": "russellmitchell.zip", "sha256": None, "approx_gb": 1.4},+ "santos": {"file": "santos.zip", "sha256": None, "approx_gb": 2.1},+ "shaw": {"file": "shaw.zip", "sha256": None, "approx_gb": 1.9},+ "wardbeck": {"file": "wardbeck.zip", "sha256": None, "approx_gb": 2.4},+ "wheeler": {"file": "wheeler.zip", "sha256": None, "approx_gb": 2.2},+ "wilson": {"file": "wilson.zip", "sha256": None, "approx_gb": 2.6},+}++LICENSE_NOTICE = """\+============================================================+AIT Log Data Set V2 — license + citation+============================================================+Dataset: AIT Log Data Set V2+Publisher: Austrian Institute of Technology (AIT)+Licence: CC BY 4.0 — attribution required+Terms: https://zenodo.org/records/5789064+Citation:+ Landauer, M., Skopik, F., Frank, M., Hotwagner, W.,+ Wurzenberger, M., & Rauber, A. (2023). Maintainable Log Datasets+ for Evaluation of Intrusion Detection Systems. IEEE TDSC.++By passing --accept-license you confirm you have read and agreed to+the upstream terms. AiSOC does NOT redistribute these files; the repo+carries only a small micro fixture for CI.+============================================================+"""+++def _sha256(path: Path) -> str:+ h = hashlib.sha256()+ with path.open("rb") as fh:+ for chunk in iter(lambda: fh.read(1 << 20), b""):+ h.update(chunk)+ return h.hexdigest()+++def _download(url: str, dest: Path) -> None:+ dest.parent.mkdir(parents=True, exist_ok=True)+ logger.info("downloading %s -> %s", url, dest)+ req = urlrequest.Request(url, headers={"User-Agent": "aisoc-fidelity/1.0"})+ try:+ with urlrequest.urlopen(req, timeout=120) as resp: # noqa: S310 - opt-in download+ with dest.open("wb") as fh:+ while True:+ chunk = resp.read(1 << 20)+ if not chunk:+ break+ fh.write(chunk)+ except urlerror.URLError as exc:+ raise SystemExit(f"download failed for {url}: {exc}") from exc+++def main(argv: list[str] | None = None) -> int:+ logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--out", type=Path, default=Path("datasets/ait-lds"))+ parser.add_argument("--mirror", default=DEFAULT_MIRROR)+ parser.add_argument(+ "--scenario",+ action="append",+ choices=sorted(SCENARIOS),+ help="Scenario to fetch; repeatable. Defaults to `fox`, which is "+ "enough to exercise the loader end to end without pulling ~19 GB.",+ )+ parser.add_argument("--all", action="store_true", help="Fetch every scenario.")+ parser.add_argument("--no-verify", action="store_true")+ parser.add_argument(+ "--accept-license",+ action="store_true",+ help="Acknowledge the AIT-LDS licence and citation. Required.",+ )+ parser.add_argument("--dry-run", action="store_true")+ args = parser.parse_args(argv)++ print(LICENSE_NOTICE)+ if not args.accept_license:+ print(+ "Refusing to download without --accept-license.\n"+ "This is not a formality: CC BY 4.0 requires attribution, and a\n"+ "dataset fetched without the licence being read is one whose terms\n"+ "nobody has agreed to.",+ file=sys.stderr,+ )+ return 2++ scenarios = sorted(SCENARIOS) if args.all else (args.scenario or ["fox"])+ total_gb = sum(float(SCENARIOS[s]["approx_gb"]) for s in scenarios)+ print(f"Scenarios: {', '.join(scenarios)} (~{total_gb:.1f} GB)")++ if args.dry_run:+ for scenario in scenarios:+ print(f" would fetch {args.mirror}/{SCENARIOS[scenario]['file']}")+ return 0++ for scenario in scenarios:+ entry = SCENARIOS[scenario]+ dest = args.out / str(entry["file"])+ if dest.exists():+ logger.info("%s already present; skipping", dest)+ continue+ _download(f"{args.mirror}/{entry['file']}", dest)++ expected = entry["sha256"]+ if expected and not args.no_verify:+ actual = _sha256(dest)+ if actual != expected:+ dest.unlink(missing_ok=True)+ raise SystemExit(+ f"checksum mismatch for {entry['file']}: expected {expected}, " f"got {actual}. The file has been removed."+ )+ elif not expected:+ # Said out loud rather than passed over: an unverified download+ # is a different thing from a verified one, and the difference+ # should be visible to whoever runs this.+ logger.warning(+ "%s has no pinned SHA-256 — downloaded unverified. Pin it in " "this script in the same PR that re-runs the harness.",+ entry["file"],+ )++ print()+ print("Next:")+ print(+ " python -m services.agents.tests.fidelity.runner "+ f"--dataset ait_lds --input {args.out}/<scenario>/gather/<host>/logs/apache2/access.log"+ )+ print(" Thresholds for the full corpus are in " "services/agents/tests/fidelity/expected_results.yaml under `ait_lds_full`.")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/datasets/download_mitre_engenuity.py b/scripts/datasets/download_mitre_engenuity.pynew file mode 100644index 000000000..243230dfb--- /dev/null+++ b/scripts/datasets/download_mitre_engenuity.py@@ -0,0 +1,153 @@+#!/usr/bin/env python3+"""Fetch MITRE Engenuity ATT&CK Evaluations results for the fidelity benchmark.++Usage:+ python scripts/datasets/download_mitre_engenuity.py --accept-license+ [--round enterprise-2024]+ [--out datasets/mitre-engenuity]++Why this exists: `mitre_engenuity_loader.py` has been able to parse the+full Round-7 procedure JSON since it landed, and there was no way to+obtain it — CICIDS-2017 and CTU-13 each shipped a downloader and this did+not. So the published fidelity number for this dataset came from a+committed micro fixture, which proves the loader parses and says nothing+about the classifier at scale.++Unlike the other three, this is not a single archive: Engenuity publishes+per-round, per-vendor result JSON through a public API. What it fetches+is the **procedure and detection-category data**, which is what the+loader reads — not the vendor rankings, which Engenuity explicitly asks+not be used for comparison and which this benchmark has no business+republishing.++License (ATT&CK Evaluations):+ Published by MITRE Engenuity under the terms at+ https://attackevals.mitre-engenuity.org/ — results are free to use+ with attribution, and MITRE Engenuity explicitly states the+ evaluations do not rank vendors. Read the terms before passing+ --accept-license.++Citation:+ MITRE Engenuity ATT&CK Evaluations, Enterprise round. Cite the+ specific round and year alongside any number derived from it.+"""++from __future__ import annotations++import argparse+import json+import logging+import sys+from pathlib import Path+from urllib import error as urlerror+from urllib import request as urlrequest++logger = logging.getLogger("download_mitre_engenuity")++DEFAULT_API = "https://attackevals.mitre-engenuity.org/api"++#: Rounds the loader understands. Adding one means confirming the+#: procedure schema still matches `mitre_engenuity_loader.py` — the+#: shape has changed between rounds before, and a loader that parses a+#: newer round into the wrong fields fails silently rather than loudly.+ROUNDS: dict[str, str] = {+ "enterprise-2024": "Round 6 — Enterprise (2024)",+ "enterprise-2023": "Round 5 — Enterprise (2023)",+ "enterprise-2022": "Round 4 — Enterprise (2022)",+}++LICENSE_NOTICE = """\+============================================================+MITRE Engenuity ATT&CK Evaluations — terms + citation+============================================================+Source: MITRE Engenuity ATT&CK Evaluations+Terms: https://attackevals.mitre-engenuity.org/+Attribution required. MITRE Engenuity states explicitly that the+evaluations do NOT rank or score vendors; any derived number must+carry that caveat.++This script fetches procedure and detection-category data only — the+inputs the fidelity loader reads. It deliberately does not mirror+vendor comparison data.++By passing --accept-license you confirm you have read the terms.+AiSOC does NOT redistribute these files; the repo carries only a+small micro fixture for CI.+============================================================+"""+++def _fetch_json(url: str) -> object:+ req = urlrequest.Request(url, headers={"User-Agent": "aisoc-fidelity/1.0"})+ try:+ with urlrequest.urlopen(req, timeout=60) as resp: # noqa: S310 - opt-in download+ return json.loads(resp.read().decode("utf-8"))+ except urlerror.URLError as exc:+ raise SystemExit(f"fetch failed for {url}: {exc}") from exc+ except json.JSONDecodeError as exc:+ raise SystemExit(+ f"{url} did not return JSON. The Engenuity API has changed shape "+ f"before; check the endpoint before assuming a network fault."+ ) from exc+++def main(argv: list[str] | None = None) -> int:+ logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--out", type=Path, default=Path("datasets/mitre-engenuity"))+ parser.add_argument("--api", default=DEFAULT_API)+ parser.add_argument(+ "--round",+ dest="rounds",+ action="append",+ choices=sorted(ROUNDS),+ help="Round to fetch; repeatable. Defaults to the most recent the " "loader is known to parse.",+ )+ parser.add_argument(+ "--accept-license",+ action="store_true",+ help="Acknowledge the Engenuity terms and the no-ranking caveat.",+ )+ parser.add_argument("--dry-run", action="store_true")+ args = parser.parse_args(argv)++ print(LICENSE_NOTICE)+ if not args.accept_license:+ print(+ "Refusing to download without --accept-license.\n"+ "The no-ranking caveat is the point: a number derived from this "+ "data and published without it misrepresents the source.",+ file=sys.stderr,+ )+ return 2++ rounds = args.rounds or ["enterprise-2024"]+ print(f"Rounds: {', '.join(ROUNDS[r] for r in rounds)}")++ if args.dry_run:+ for round_id in rounds:+ print(f" would fetch {args.api}/participants/{round_id}")+ return 0++ args.out.mkdir(parents=True, exist_ok=True)+ for round_id in rounds:+ url = f"{args.api}/participants/{round_id}"+ logger.info("fetching %s", url)+ payload = _fetch_json(url)+ dest = args.out / f"{round_id}.json"+ dest.write_text(json.dumps(payload, indent=2), encoding="utf-8")+ logger.info("wrote %s", dest)++ print()+ print("Next:")+ print(" python -m services.agents.tests.fidelity.runner " f"--dataset mitre_engenuity --input {args.out}/<round>.json")+ print(+ " Thresholds for the full corpus are in " "services/agents/tests/fidelity/expected_results.yaml under " "`mitre_engenuity_full`."+ )+ print()+ print(" Any number you publish from this must carry MITRE Engenuity's own " "caveat: the evaluations do not rank vendors.")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/services/agents/tests/fidelity/expected_results.yaml b/services/agents/tests/fidelity/expected_results.yamlindex 55038df8b..9d4a67f08 100644--- a/services/agents/tests/fidelity/expected_results.yaml+++ b/services/agents/tests/fidelity/expected_results.yaml@@ -87,3 +87,41 @@ mitre_engenuity_micro:rows_scored_min: 10accuracy_min: 0.70macro_f1_min: 0.55++ait_lds_full:+ # Local-only: requires scripts/datasets/download_ait_lds.py to have+ # populated datasets/ait-lds/. Until this commit there was no way to+ # fetch the corpus at all, so the only AIT-LDS number anyone could+ # produce came from the 10-line micro fixture above — which proves+ # the loader parses and says nothing about the classifier at scale.+ dataset: ait_lds+ mode: substrate+ notes: |+ UNMEASURED. These are the floors the harness will enforce once+ somebody runs the full corpus; they are deliberately set at the+ micro-fixture level rather than guessed higher, because a floor+ invented above an unmeasured result is a gate that fails on first+ contact and gets lowered rather than investigated.++ Whoever runs it first should replace these with the observed+ numbers and drop this note in the same PR.+ measured: false+ rows_scored_min: 1000+ accuracy_min: 0.70+ macro_f1_min: 0.55++mitre_engenuity_full:+ # Local-only: requires scripts/datasets/download_mitre_engenuity.py.+ # Same history as ait_lds_full — a loader that could read the full+ # round data and no way to obtain it.+ dataset: mitre_engenuity+ mode: substrate+ notes: |+ UNMEASURED, and carries an additional constraint the other+ datasets do not: MITRE Engenuity states explicitly that its+ evaluations do not rank vendors. Any number published from this+ must carry that caveat, or it misrepresents the source.+ measured: false+ rows_scored_min: 500+ accuracy_min: 0.70+ macro_f1_min: 0.55