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.

docs(8.1): ADR-0011 and the claim row for a truncatable audit chain

Beenu Arora35b7ba498a9b
diff --git a/ROADMAP.md b/ROADMAP.md
index 8e0bf2111..0ed1c578e 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -45,7 +45,7 @@ A proof-first, security-first program to make every README claim gate-backed, cl
- **Phase D (breadth):** D1 eight connectors (QRadar/Exabeam/Securonix/Devo/Netskope/Windows-Sysmon/Zeek-Suricata/syslog-CEF) · D2 AI/LLM-usage audit connector + `llm-*` detections + hot/cold lake tiering · D3 live-vendor mock-server smoke.
- **Phase E (prove it):** E1 CI-gated benchmark scoreboard tied to a deterministic live-agent MITRE-accuracy run.
-The claim-to-gate matrix stands at **302 rows — 299 GATED / 3 PARTIAL / 0 NO GATE**. Three rows are PARTIAL. "The retention window a tenant chooses is the one the lake honours" stays PARTIAL until a live ClickHouse test watches a row survive past the old 90-day boundary. "Cloud-native collection" stays PARTIAL until a capture recorded from a live Event Hub replaces the fixture synthesised from the Avro specification. And "SSO completes a sign-in": fix pass 4.1 drove both handlers end to end against real Postgres and real signed assertions, and it stays PARTIAL until the containerised-IdP leg of `sso-live.yml` has been observed to pass, because the identity providers in that suite are trust material this repository authors. Every other product claim is backed by a failing test, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).
+The claim-to-gate matrix stands at **303 rows — 300 GATED / 3 PARTIAL / 0 NO GATE**. Three rows are PARTIAL. "The retention window a tenant chooses is the one the lake honours" stays PARTIAL until a live ClickHouse test watches a row survive past the old 90-day boundary. "Cloud-native collection" stays PARTIAL until a capture recorded from a live Event Hub replaces the fixture synthesised from the Avro specification. And "SSO completes a sign-in": fix pass 4.1 drove both handlers end to end against real Postgres and real signed assertions, and it stays PARTIAL until the containerised-IdP leg of `sso-live.yml` has been observed to pass, because the identity providers in that suite are trust material this repository authors. Every other product claim is backed by a failing test, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. The last two rested on the live-agent eval workflow, which this file said had simply never run: the real reason was that its live path imported a class that exists nowhere in `services/agents`, so its first dispatch failed in 92 seconds and every later one would have. With that fixed the workflow measures, and the groundedness floor is **0.40 over a deterministic 10-incident slice**, derived from ten runs across two environments rather than chosen — seven local runs returning 0.5561 to four decimal places, three GitHub-runner runs returning 0.5821, 0.5329 and 0.5933. Every one is a locally-served `qwen2.5:0.5b`; no hosted provider has been exercised and the floor describes none. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).
## v4.0 — Shipped
diff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.md
index 1dd2f4f30..fb5e360ec 100644
--- a/apps/docs/docs/compliance/evidence-pack.md
+++ b/apps/docs/docs/compliance/evidence-pack.md
@@ -33,7 +33,7 @@ and says so.
| Prompt-injection resistance | Three adversarial corpora: 32 payloads scanned in isolation and 71 incident pairs whose payloads are placed in attacker-controllable fields, both against a clean twin with a recall floor and a false-positive ceiling, plus 34 held-out pairs authored after the guard was frozen and carrying no floor at all, on which the guard measures 7.1% | `services/agents/tests/adversarial/` |
| Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |
-The last row is the one worth reading first. It is the honest index: 299 rows
+The last row is the one worth reading first. It is the honest index: 300 rows
`GATED`, 3 `PARTIAL`, and a ratchet that refuses to let a row sit at
`NO GATE`. Re-read the figure from the table rather than from here — a count
copied into prose goes stale in silence, which is why
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index fcb3a56e6..1e1c4fbf1 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -70,6 +70,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| The rule-management surface lists the rules the detection engine actually runs, and disabling one reaches the engine | `apps/docs/docs/console/rule-library.md`; [#1273](https://github.com/beenuar/AiSOC/issues/1273) | `ci.yml :: python-lint` (`sync_packaged_detection_rulesets.py --self-test` then `--check`: the three compiled artefacts and the three Python-resident windowed rules must exist byte-identical inside the API's Docker build context, checked in both directions so a file only on the packaged side fails too) + `validate-detections.yml` (the same check, on the workflow a corpus change triggers) + `ci.yml :: Python — Tests` (api, `test_builtin_rule_catalogue.py` — the catalogue's rule-id set is asserted **equal** to the union of ids fusion's own `_load_ruleset()`, `load_window_rules()` and `load_sequence_rules()` return, run in a subprocess because both services name their top-level package `app`; the console route is driven through a real ASGI app and must report 2,586; and disabling a built-in is followed by handing the stored row to fusion's real `build_overlay`, loaded by path, which must report it suppressed) + web type-check and `DetectionsView.honesty.test.tsx` | core | GATED | Both API routes and the MCP tool read the Postgres `detection_rules` table and nothing in production writes a built-in row — `tenant_id` is `NOT NULL` in every migration, so the platform-wide row they look for cannot exist. The constraint that shaped the fix is packaging: the API image is built from `services/api`, so `services/fusion/app/data/` was never reachable and a handler change alone would pass in a checkout and fail in every container. Built-ins are not seeded into Postgres; the artefact stays the single source of truth for what runs and a tenant row materialises on first write, keyed on `provenance->>'source_id'`, which is what the overlay already joins on |
| Detections can be backtested over historical lake data before promotion | README (detection engineering) | `ci.yml` api job (`test_backtest.py` — bounded/allow-listed SQL construction with injection-sanitised source filter, lake-row→event mapping with JSON payload expansion, exact would-fire count + hit-rate + samples; `test_backtest_gate.py` — opt-in `AISOC_BACKTEST_MAX_HIT_RATE` /decide gate) + web type-check (rule-editor backtest panel) + `isolation-live.yml` (`tests/isolation/test_backtest_lake_live.py` — the real `fetch_lake_events` against ClickHouse 23.8, table built from `clickhouse/001_init.sql` and rows seeded through the production `lake_writer.event_to_row`) | full | GATED (the gap this row used to name was wrong: nothing ran the live fetch, and the tenant-scoping path existed twice — `detection_rules.py` carried its own near-identical copy, now deleted, with a test asserting exactly one definition survives. The live path exposed a defect no unit could: the writer stores OCSF `raw_data` into a column named `raw_payload` and `rows_to_events` expanded neither, so the payload expansion its docstring promises had never run on a real lake row. `services/api/app/services/backtest.py` was also absent from the workflow's path filter, so a change to the function under test did not trigger the job) | — |
| The retention window a tenant chooses is the one the lake honours, and a legal hold outranks it | `services/api/app/services/retention.py`; `services/api/clickhouse/001_init.sql`; depth plan 4.3 | `ci.yml :: python-lint` (`check_retention_window.py --self-test` then the gate: the table TTL, the tiering DELETE and `MAX_LAKE_DAYS` are held to one number at or above 400 days, a `MODIFY TTL` migration exists so an existing volume converges — `001_init.sql` runs only on a fresh one — and the purge worker reads the holds in force, decides through `may_purge`, and reports what it withheld. Eight injected violations, one per rule) + `ci.yml` api job (`test_retention_legal_hold.py`, 13 cases driving the worker against recording doubles. **Half of them are the positive control**, because a purge stuck closed withholds everything on every deployment and passes every "did the hold work" assertion perfectly: a tenant with no hold is asserted to still lose its aged rows, and a hold on one tenant is asserted not to freeze another. Proven against the pre-fix worker, where five fail) | core | PARTIAL (the lake half is static: ClickHouse enforces a table TTL during merges and no test in CI watches a row survive past day 90 on a real server, so what is gated is that the three numbers agree and that the migration exists, not that ClickHouse honoured it. The purge half is gated against doubles rather than live Postgres and ClickHouse. And a hold currently stops the whole tenant's sweep rather than only its own subjects, because both purges are bulk statements — recorded as follow-up rather than approximated) | a live-store retention test |
+| The audit retention window a tenant configures is enforced, and the surviving chain still verifies | `docs/decisions/0011-truncating-a-hash-chained-audit-log.md`; `services/api/app/workers/retention_purge.py`; depth plan 8.1 | `audit-retention-live.yml :: audit-retention-live` (`tests/isolation/test_audit_retention_live.py`, 12 cases against real Postgres as the DML-only `aisoc_app` role: the window removes the rows past it, the checkpoint agrees with the rows it describes from both sides, the remainder replays clean from the anchor, a direct DELETE and a hand-set purge flag are both refused by privilege, and the checkpoint is itself immutable. The job reads the DELETE privilege out of the catalogue, refuses a run that skipped a case, and carries a negative control that ignores the anchor and requires the suite to go red) | core | GATED | `retention_policies.audit_days` was storable since the table existed and purged by nothing, because `audit_log` is an append-only hash chain: delete the oldest rows and `verify_chain_breaks`, which replays from `prev_hash = NULL`, reports a mismatch at index 0 — an intact chain reads as tampered with, which is the worst outcome for a control whose only job is to tell those apart. Migration `111` adds `audit_retention_truncate`, a `SECURITY DEFINER` function that writes a checkpoint (the cutoff, the window, the count, the hash of the last row removed and the predecessor the oldest survivor names) and only then deletes, in one transaction; the verifier re-anchors on it. The application role holds **no DELETE on `audit_log`**, so the function is the only path rather than the intended one — the trigger's transaction-local setting is a second control, but a custom GUC can be set by anybody. **Does not unblock tenant deletion**: `audit_log`'s trigger from migration `101` refuses the cascade from `tenants` too, so `DELETE FROM tenants` raises for any tenant that has written a row. Pre-existing, tracked separately, and the checkpoint table deliberately does not repeat it |
| Detections can be authored in Python (`def rule(event)`) with a fixture gate | README (detection engineering) | `python-detections.yml` (`aisoc_detections.runner` fails a blind rule that misses a positive or a noisy one that fires on a negative; every bundled detection must ship ≥1 positive + ≥1 negative case) + `test_framework.py` (fail-closed evaluate, metadata validation) | core | GATED | - |
| AI Detection Builder: NL → rule + AUTO-generated fixtures → non-circular eval-gate → governed proposal | README (detection engineering) | `ci.yml` api job (`test_ai_detection_builder.py` — fixtures are DERIVED from the generated rule's own selection, not invented, and genuinely pass the non-circular gate: fires on the positive, quiet on the negative) | core | GATED | - |
| No-code / simple detection builder compiles to a valid rule | README (detection engineering) | `ci.yml` web type-check + lint (`SimpleRuleBuilder.tsx` `buildSigma` compiles field/operator/value rows to Sigma, dropped into the governed editor) | core | GATED | - |
@@ -313,8 +314,8 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
## Summary
-- Total: 302
-- GATED: 299
+- Total: 303
+- GATED: 300
- PARTIAL: 3
- NO GATE: 0
diff --git a/docs/decisions/0011-truncating-a-hash-chained-audit-log.md b/docs/decisions/0011-truncating-a-hash-chained-audit-log.md
new file mode 100644
index 000000000..4803c9e20
--- /dev/null
+++ b/docs/decisions/0011-truncating-a-hash-chained-audit-log.md
@@ -0,0 +1,122 @@
+# ADR-0011: truncating a hash-chained audit log, without making an intact chain look tampered with
+
+- **Status:** accepted
+- **Date:** 2026-10-11
+- **Related:** migration `043` (the hash chain), migration `101` (the one legal mutation, pinned to `actor_id`), migration `111` (this decision)
+- **Implements:** depth plan 8.1, the remainder of parity 4.4
+
+## Context
+
+`retention_policies.audit_days` has been storable since the table existed and
+was purged by nothing. The retention worker said so in its own module
+docstring, and said why:
+
+> 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 it in one place beat a purge that silently errored every tick. It still
+left an operator who configured `audit_days` with a setting the product
+ignored, and an erasure request with no mechanism behind it.
+
+The difficulty is specific and worth stating precisely, because it is what
+rules out the obvious implementation. `verify_chain_breaks` replays a tenant's
+rows oldest-first starting from `prev_hash = NULL`. Delete the oldest rows and
+the new first row names a predecessor that no longer exists, so the replay
+reports `prev_hash mismatch` at index 0. A chain that is perfectly intact then
+reads as tampered with — which is the worst available outcome for a control
+whose only job is to tell those two apart, because the false alarm is
+indistinguishable from the real thing and the next one gets ignored.
+
+## Decision
+
+Removal goes through one `SECURITY DEFINER` function, `audit_retention_truncate`,
+which writes a **checkpoint** and then deletes, in a single transaction. The
+checkpoint records the cutoff that was applied, the window that produced it,
+how many rows went, the hash of the last row removed, and the predecessor the
+oldest survivor names. Verification re-anchors on that checkpoint:
+`verify_chain_breaks` and `verify_chain` take an optional `anchor_prev_hash`,
+defaulting to `None`, which is the genesis case every untruncated tenant
+still gets.
+
+Three consequences follow, and each is a deliberate choice rather than a
+detail of the implementation.
+
+**The removal becomes a fact rather than an absence.** A plain `DELETE` leaves
+an auditor inferring that rows are missing from a gap in `chain_index`. A
+checkpoint states what went, when, and under which policy — "everything before
+13 July went" and "a 90-day window was in force" answer different questions,
+and an auditor asks the second.
+
+**The checkpoint can be checked against itself.** `last_removed_hash` is read
+from the removed side and `first_retained_prev_hash` from the surviving side.
+On an untampered chain the two are equal. Storing one would have been enough
+to re-anchor the replay; storing both means a checkpoint that disagrees with
+itself is evidence in its own right.
+
+**The function is the only path, enforced by privilege and not by convention.**
+The application role has no `DELETE` on `audit_log` at all. The trigger's
+transaction-local `app.audit_retention_purge` setting is a second control, but
+a custom GUC can be set by anybody, so on its own it would be a comment rather
+than a mechanism; Postgres checks the privilege before the trigger runs, so a
+caller who guesses the setting's name is refused one layer below the one they
+were aiming at. `SET search_path` is pinned on the function, because a
+definer-rights function whose caller controls `search_path` can be pointed at
+an `audit_log` the caller owns.
+
+## Alternatives rejected
+
+**Delete and accept the broken verification.** Cheapest, and it destroys the
+only property the chain has. A verifier that reports a break on every
+truncated tenant trains its reader to ignore it.
+
+**Re-chain the survivors — recompute hashes from a new genesis.** Rewriting
+`prev_hash` and `entry_hash` on rows that were not changed is exactly the
+operation the chain exists to detect, and it would need the immutability
+trigger relaxed for `UPDATE` as well as `DELETE`. It also destroys the
+evidence: after re-chaining, a tenant whose rows were tampered with and then
+"retained" verifies clean.
+
+**Move old rows to an archive table instead of deleting them.** This answers
+retention and not erasure — the rows are still in the database, so it does not
+satisfy a request to remove them, which is the half the operator was asking
+for. It can be built later on top of this: the checkpoint is what makes the
+remaining chain verifiable either way.
+
+**A soft-delete flag.** Same objection, plus every reader now has to remember
+the predicate, and the one that forgets reports deleted rows as present.
+
+## What this does not do
+
+**It does not unblock tenant deletion.** `audit_log`'s immutability trigger,
+from migration `101`, refuses every `DELETE` including the cascade from
+`tenants`. So `DELETE FROM tenants` raises for any tenant that has ever
+written an audit row, which is every tenant, and `tenant_deletion.py` inherits
+that. The behaviour predates this decision and relaxing a shipped immutability
+control belongs in its own change with its own ADR; it is tracked separately.
+
+The checkpoint table added here does **not** repeat the shape. Its foreign key
+declares `ON DELETE CASCADE` and the trigger permits exactly that cascade,
+told apart from a direct `DELETE` by whether the parent tenant is still
+present — PostgreSQL runs a cascade as an AFTER trigger on the parent, so the
+tenant row is already gone by the time the child's BEFORE trigger runs, while
+a caller deleting checkpoints directly still has their tenant. The exception is
+narrow and expensive on purpose: erasing the record of a truncation costs the
+entire tenant, every alert, case and credential with it, which is not
+selective erasure in any useful sense.
+
+**It does not decide the window.** `audit_days` is a per-tenant policy with no
+default, and absence of a policy means no truncation. A backfilled default
+would silently start deleting audit history on upgrade.
+
+## How this is kept true
+
+`.github/workflows/audit-retention-live.yml` runs
+`tests/isolation/test_audit_retention_live.py` against real Postgres, as the
+DML-only `aisoc_app` role rather than the owner — as the owner the suite would
+pass with the privilege half removed. The workflow reads the `DELETE`
+privilege straight out of the catalogue, refuses a run that skipped its cases,
+and carries a negative control that ignores the checkpoint anchor and requires
+the suite to go red.
diff --git a/docs/decisions/README.md b/docs/decisions/README.md
index 163ed6ca9..d1116df91 100644
--- a/docs/decisions/README.md
+++ b/docs/decisions/README.md
@@ -24,6 +24,7 @@ ADRs are immutable once accepted. If a decision changes, write a new ADR that su
| [ADR-0008](./0008-scim-trust-boundary.md) | SCIM is a third-party write surface into identity, and is scoped by its credential | accepted | 2026-09-27 |
| [ADR-0009](./0009-auto-close-without-an-earned-grant.md) | Whether a tenant with no closure policy may auto-close | proposed | 2026-10-04 |
| [ADR-0010](./0010-entity-and-session-context-in-core.md) | Entity and session context in CORE is a Postgres store; Neo4j stays in `full` | accepted | 2026-10-11 |
+| [ADR-0011](./0011-truncating-a-hash-chained-audit-log.md) | Truncating a hash-chained audit log without making an intact chain look tampered with | accepted | 2026-10-11 |
## Authoring conventions