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(security): a buyer security pack, with a gate that keeps its claims true (depth 8.3) (#1210)

Beenu Arora41d31ea1855f
diff --git a/.github/workflows/security-pack.yml b/.github/workflows/security-pack.yml
new file mode 100644
index 000000000..9f6715b84
--- /dev/null
+++ b/.github/workflows/security-pack.yml
@@ -0,0 +1,55 @@
+name: Security pack
+
+# The buyer security pack (`docs/security/`) makes one promise: every
+# statement names the file or the CI job that makes it true. That promise
+# decays silently — a module is renamed, a workflow deleted, a heading
+# reworded, and the pack goes on reading like a document somebody verified.
+#
+# Four security documents in this repository once described controls that did
+# not exist. A link checker would not have caught all four, because a link can
+# resolve to a file whose contents do not support the sentence — but it catches
+# the cheapest half, which is the half that rots fastest.
+#
+# No path filter on `push`. A pack statement can be falsified by a change
+# nowhere near `docs/security/` — deleting a workflow the questionnaire cites
+# is the obvious case — so filtering on the pack's own paths would mean the
+# gate runs exactly when it is least needed.
+
+on:
+ pull_request:
+ push:
+ branches: [main]
+ workflow_dispatch:
+
+concurrency:
+ # Per commit on push, per pull request on PRs. Keyed on `github.ref` alone,
+ # a push to main cancels the run before it, which is how 259 of 1,000 push
+ # runs here were cancelled rather than graded.
+ group: security-pack-${{ github.event_name }}-${{ github.event.pull_request.number || github.sha }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+
+permissions:
+ contents: read
+
+jobs:
+ security-pack-links:
+ name: Every security-pack claim points at something real
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+
+ - uses: actions/setup-python@e9d6f990972a57673cdb72ec29e19d42ba28880f # v6
+ with:
+ python-version: "3.11"
+
+ # The self-test first. A gate nobody has seen fail is indistinguishable
+ # from one that cannot, and this one has eight cases: four that must
+ # fail, a stale-exemption case covering the other direction, a clean
+ # control, and a refusal to report an empty tree as verified.
+ - name: The gate detects its own regressions
+ run: python3 scripts/check_security_pack_links.py --self-test
+
+ - name: Every relative link, anchor and named gate resolves
+ run: python3 scripts/check_security_pack_links.py
diff --git a/CHANGELOG.md b/CHANGELOG.md
index eeaf4942b..b5012b265 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -45,6 +45,62 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
guard to admit a corpus breaks the test that says the old ones stay out.
(Depth plan 1.1)
+- **A buyer security pack a reviewer can actually use.** `docs/security/` held
+ three threat models and an advisory draft — good documents, and not the set
+ a procurement review asks for. It now also carries architecture and
+ data-flow diagrams, data handling per deployment mode, a completed security
+ questionnaire, and a sub-processor page, indexed at
+ `docs/security/README.md` and linked from `SECURITY.md`.
+
+ The pack's rule is that every statement names the file or the CI job that
+ makes it true, and that where a control is narrower than its heading sounds,
+ the limit is in the same paragraph. So it states plainly that
+ service-to-service traffic is plaintext inside the container network on the
+ default stack, that `/metrics` covers 5 of 19 services, and that the
+ prompt-injection guard scores 7.1% on held-out payloads against 98.1% on the
+ corpus it was hardened against — the unflattering number is the one that
+ matters. Ten gaps are collected in one table rather than left for a reviewer
+ to assemble from the prose.
+
+ `scripts/check_security_pack_links.py` keeps it from rotting: every relative
+ link, every anchor, and every gate the pack names *in prose rather than in a
+ link* must resolve, with a bidirectional exemption table so a gate recorded
+ as absent that later appears also fails. Eight self-test cases, four of them
+ injected regressions. Wired in `security-pack.yml` with no path filter,
+ because a pack statement is most often falsified by a change nowhere near
+ `docs/security/`. (#PR)
+
+### Fixed
+
+- **`docs/trust/data-flows.md` told a reader the opposite of the truth, twice
+ in one paragraph.** It said hosted egress is "**not** pseudonymized before
+ egress today ... a planned control rather than a shipped one" and then, in
+ the same paragraph, "Restored by parity 2.4" — a correction appended without
+ removing what it corrected. Parity 2.4 did wire the pseudonymizer at the
+ contract layer (`services/agents/app/llm/contract.py` calls
+ `egress_privacy.open_session`), so the page understated a shipped control on
+ the single question a buyer cares most about. Two further statements were
+ stale in the same direction: the Helm default-deny `NetworkPolicy` is
+ described as pending when `infra/helm/aisoc/templates/networkpolicy.yaml`
+ ships it, and the air-gapped CI proof is described as planned when
+ `container-egress.yml` runs it with a canary and a red run. All three
+ corrected, each now naming its gate, and each carrying the limit that goes
+ with it — the NetworkPolicy is opt-in because a CNI that does not enforce it
+ ignores it silently, and the sinkhole cannot observe a dial straight to an IP
+ literal. The matching "still outstanding" note in
+ `docs/audit/REALITY_REPORT.md` is closed with the same evidence. (#PR)
+
+- **ADR-0002 asserts a CI gate that has never existed**, and the security pack
+ repeated it before the new link gate caught it on its first run.
+ `scripts/audit_compliance_claims.py` is cited twice in
+ `docs/decisions/0002-compliance-claims.md` as already shipped and guarding
+ the "controls aligned to" framing; no such script is in the tree and no
+ workflow references it, a finding `docs/audit/REALITY_REPORT.md` already
+ recorded. The pack now states that the framing is a convention rather than a
+ gate, lists it as a gap, and the script is recorded in the link gate's
+ `KNOWN_ABSENT` table so that building it will fail the gate until the prose
+ is corrected. (#PR)
+
## [17.1.0] - 2026-10-07
### Security
diff --git a/ROADMAP.md b/ROADMAP.md
index ac9322d28..5ded93634 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -44,7 +44,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 **294 rows — 293 GATED / 1 PARTIAL / 0 NO GATE**. The one PARTIAL is "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 **295 rows — 294 GATED / 1 PARTIAL / 0 NO GATE**. The one PARTIAL is "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/SECURITY.md b/SECURITY.md
index 743000bc1..dafb353cd 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -2,6 +2,23 @@
AiSOC is security software, so we take vulnerabilities in our own stack seriously. This document explains how to report issues responsibly and what to expect from us.
+## Security pack
+
+If you are reviewing AiSOC rather than reporting a bug in it, start at
+[`docs/security/`](docs/security/README.md) — architecture and data-flow
+diagrams, the threat models, data handling per deployment mode, a completed
+security questionnaire, and what we can and cannot tell you about
+sub-processors.
+
+Every statement in that pack names the file or the CI job that makes it true,
+and the gaps are collected in one table rather than left for you to find.
+
+- Index: [`docs/security/README.md`](docs/security/README.md).
+- Architecture and data flow: [`docs/security/architecture-and-data-flow.md`](docs/security/architecture-and-data-flow.md).
+- Data handling by deployment mode: [`docs/security/data-handling.md`](docs/security/data-handling.md).
+- Security questionnaire, with the gap list: [`docs/security/questionnaire.md`](docs/security/questionnaire.md).
+- Sub-processors: [`docs/security/subprocessors.md`](docs/security/subprocessors.md).
+
## Threat models
- Agent + tool surface (prompt injection, tool abuse): [`docs/security/agent-threat-model.md`](docs/security/agent-threat-model.md).
diff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.md
index 04eb85b9c..ed1e36cf3 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: 293 rows
+The last row is the one worth reading first. It is the honest index: 294 rows
`GATED`, 1 `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 dfd5d5970..5958f376f 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -298,6 +298,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| A detection rule's author cannot approve it | `apps/docs/docs/operations/detection-lifecycle.md` | `ci.yml :: Python — Tests` (`services/api/tests/test_detection_separation_of_duties.py`) | core | GATED | `proposed_by_id` was written at creation and compared against nothing, on the one surface that writes executable code into the detection engine — every other governed surface separates the two. Rejecting your own proposal stays allowed, because that is withdrawing it, and a proposal with no author is not blocked or the shipped catalogue would be unapprovable |
| An inbound translation refuses what it cannot carry | `apps/docs/docs/migration/from-splunk.md`, `README.md` | `ci.yml :: Run aisoc-migrate tests` (`packages/aisoc-migrate/tests/test_inbound.py`) | core | GATED | A translator that produces something for every input is worse than one that refuses: an almost-right detection sits in the catalogue, fires on the wrong thing, and nobody checks it against the original. Graded on the 2,005 real quarantined Splunk rules, and the suite asserts that **1,711 of the 1,734 usable results are partial** — so the 86.5% headline cannot be read as a finished migration |
| A behavioural rate reports unmeasured when its own signal never occurred | `apps/docs/docs/benchmark.md` | `ci.yml :: Python — Tests` (`services/agents/tests/adversarial/test_vacuous_rates_refuse.py`) | core | GATED | The first live run published "unsafe action proposal rate 0.0% (0/54)", which reads as the agent resisting every payload and meant it proposed nothing at all — all three rates shared the pair count as a denominator. Verdict flip was a real 9.3% on the same pairs, which is why they cannot share one. Negative controls in both directions: verdict flip must keep reporting, and a suppressed rate must return as soon as its signal appears |
+| The buyer security pack states only controls the tree has, and names the file or job behind each one | `docs/security/README.md`; `SECURITY.md` | `security-pack.yml :: security-pack-links` (`check_security_pack_links.py` — every relative link, every in-document and cross-document anchor computed the way GitHub computes heading slugs, and every gate the pack names in prose rather than in a link, since that is where a citation usually sits and where a plain link checker cannot see it. Eight self-test cases: four injected regressions, a clean control, a refusal to report an empty tree as verified, and a **stale-exemption** case for the other direction — a gate the pack records as absent that later appears means the pack now understates a control, which is the quieter half of the same defect) | core | GATED | Scope stated rather than implied: this proves a citation **resolves**, not that the cited file supports the sentence, and external URLs are deliberately out of scope because fetching them would make the check depend on GitHub's rate limiter — which is how the docs link job ended up with `fail: false` and eight wrong-org 404s surviving it. Built because it immediately earned itself: on first run it caught this pack repeating ADR-0002's assertion that `scripts/audit_compliance_claims.py` exists, which it never has |
| A pending approval is offered on every channel the deployment configured | `apps/docs/docs/operations/notifications.md` | `ci.yml :: Python — Tests` (api, `test_delivery_5_2.py::TestApprovalDelivery` — every channel skipped with the setting that would enable it, an unsigned link refused, a bot answering `posted: false` not recorded as a delivery, and a bot that is down not taking the approval with it) + `scripts/check_route_auth.py` (the Teams notify route is a recorded in-band-credential entry naming its verifier) | full | GATED | Push was the only channel that ever fired. `send_approval_email` had **one reference in the tree, its own definition**, while the verifier, the renderer and the `/approvals/email/decide` route had all shipped waiting for a link nothing sent; `services/teams-bot` was in no compose file and had no route that could post a card. Each channel delivers only when configured and an unconfigured one reports `skipped` with the setting, which is the difference between "we chose not to" and "it broke" |
| A stored report schedule produces a report, and says whether it was delivered | `apps/docs/docs/operations/notifications.md` (scheduled reports) | `ci.yml :: Python — Tests` (api, `test_delivery_5_2.py::TestCronMatching` — nine match cases, six unparseable expressions that raise rather than matching everything, a schedule falling between two five-minute polls, an already-run schedule not firing twice, and a week-long outage collapsing into one report) | core | GATED | `report_templates.cron_schedule` was storable, editable and **read by nothing**, so a tenant could set a schedule, see it saved and never receive anything. Asking "does the current minute match" would have checked 08:57 and 09:02 and never 09:00; the matcher asks over the interval since the last run. Migration 098 adds `delivery_status`, because `delivered_at` alone cannot tell "no relay configured" from "the relay refused" from "not run yet" |
| An outbound event webhook is signed, retried, and its failures are visible | `apps/docs/docs/operations/notifications.md` (outbound webhooks) | `ci.yml :: Python — Tests` (api, `test_delivery_5_2.py::TestWebhookSignature` and `::TestWebhookDelivery` — signature round-trip through the real client, a modified body and a re-stamped timestamp both refused, five malformed headers refused without raising, the 4xx/5xx split, the ladder ending in the dead-letter view, byte-identical bodies across attempts, and an undecryptable secret killing the delivery rather than sending it unsigned) | core | GATED | AiSOC could be told things and could tell nobody anything: `grep -rln outbound_webhook` over `services/` and `apps/` returned nothing. The signature is the shape Stripe, GitHub and Slack use, because a scheme nobody recognises is a scheme nobody verifies. The retry queue and the dead-letter list are one table at different points on one ladder, so there is no window where a delivery is in neither |
@@ -305,8 +306,8 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
## Summary
-- Total: 294
-- GATED: 293
+- Total: 295
+- GATED: 294
- PARTIAL: 1
- NO GATE: 0
diff --git a/docs/audit/REALITY_REPORT.md b/docs/audit/REALITY_REPORT.md
index cce8c9ce2..8ec026ae3 100644
--- a/docs/audit/REALITY_REPORT.md
+++ b/docs/audit/REALITY_REPORT.md
@@ -60,10 +60,17 @@ Phase 0 of the world-class program (`AISOC_CURSOR_PROMPT_V2.md`). This document
## Overclaims (ranked)
1. **"No data exfiltration / runs entirely on your infrastructure."** The default investigation path uses a cloud LLM (`ANTHROPIC_API_KEY` / `OPENAI_API_KEY`) and reasons over raw evidence. There is no PII pseudonymization (`services/agents/app/privacy/` does not exist), so usernames, hostnames, internal IPs, file paths, and command lines are sent verbatim to a third-party provider. The claim is only true in the local-model / air-gapped configuration, which is not the default and has no egress-blocked CI proof. Fix in Phase 1.4 + Phase 2.
- **Partly closed.** `services/agents/app/privacy/` now exists (`redactor.py`,
- with `services/agents/tests/test_privacy_redactor.py`), and
- [`docs/trust/data-flows.md`](../trust/data-flows.md) describes the redactor as
- the shipped default. The egress-blocked CI proof is still outstanding.
+ **Closed.** Three steps, and the middle one is the lesson. First
+ `services/agents/app/privacy/redactor.py` landed with a unit test — but
+ **no LLM call site invoked it**, so `docs/trust/data-flows.md` described a
+ planned control as shipped. Parity 2.4 then wired it at the contract layer
+ (`services/agents/app/llm/contract.py` calls `egress_privacy.open_session`,
+ the one place all sixteen agent call sites pass through) and re-gated the
+ claim on a *call-path* test rather than a function test — which immediately
+ found a bare username going out in the clear. The egress-blocked CI proof
+ is `.github/workflows/container-egress.yml`, with a canary and a red run so
+ a green result is not the same as a blind probe. See
+ [`docs/security/data-handling.md`](../security/data-handling.md).
2. **"6000+ imported detection rules."** ~5921 of 6113 imported rules live under `_quarantine/` (`enabled: false`) because their upstream query language (SPL / YARA-L / CAR pseudocode) does not execute on the engine. The coverage heatmap (`scripts/build_marketplace.py::coverage_block`) counts MITRE tags on rule metadata, not rules that fire. Fix in Phase 4 Tier 3 + Phase 10.
**Closed in v11.2.0.** Published counts now lead with the executable figure beside the library one (2,603 of 6,991), and 1,770 Sigma rules were translated into the matcher's own language after each was replayed through its real connector and the real engine and watched to fire. The blocker was never the quarantine flag: Windows events nest their payload under `System`/`EventData`, one level below the namespace the matcher reads, so no Windows rule could fire whatever its `enabled:` said.
3. **"Detection-as-Code ... CI rejects any candidate that regresses MITRE accuracy."** True in letter, misleading in spirit: the gate never evaluates the proposed rule (see Circular Gates). Fix in Phase 4.
diff --git a/docs/security/README.md b/docs/security/README.md
new file mode 100644
index 000000000..e2d0b57d2
--- /dev/null
+++ b/docs/security/README.md
@@ -0,0 +1,79 @@
+# Security pack
+
+For a reviewer doing diligence on AiSOC. Six documents, in the order a
+security questionnaire usually walks them.
+
+| Document | Answers |
+|---|---|
+| [Architecture and data flow](architecture-and-data-flow.md) | What the components are, which trust boundaries they sit across, and where every class of data goes. |
+| [Data handling by deployment mode](data-handling.md) | What leaves your perimeter under each of the four ways AiSOC can be run, and what is retained where. |
+| [Platform threat model](platform-threat-model.md) | STRIDE over the platform, with the credential vault as the top asset. |
+| [Agent and tool threat model](agent-threat-model.md) | STRIDE over the prompt and tool boundaries, both of which take attacker-influenced input. |
+| [Connector least privilege](connector-least-privilege.md) | The minimum vendor scope each connector needs. |
+| [Security questionnaire](questionnaire.md) | Standard control questions, answered, with the gap list stated rather than omitted. |
+| [Sub-processors](subprocessors.md) | What this repository can and cannot establish about the hosted service. |
+
+## The one rule these documents follow
+
+**Every statement names the file or the CI job that makes it true, and where a
+control is narrower than its heading sounds, the limit is in the same
+paragraph.**
+
+That rule exists because this project has broken it. Four security documents
+once described controls that did not exist in the tree: AES-256-GCM backup
+encryption where the script only gzipped and uploaded, envelope encryption
+cited as the mitigation for a database dump while `EnvelopeCipher` had zero
+callers, one unbroken distributed trace with neither end of the Kafka spine
+instrumented, and per-tenant retention marked GATED by a test that asserted
+only that the purge SQL parses. Each was corrected, and then implemented.
+
+So a claim here without a link beside it is a bug in this pack, and
+[reporting one](../../SECURITY.md) is welcome.
+
+## Verifying any of this yourself
+
+Nothing here asks to be taken on trust. The repository is the evidence:
+
+```bash
+git clone https://github.com/beenuar/AiSOC
+cd AiSOC
+
+# Which CI job proves which product claim — 293 rows, every one naming a gate.
+python3 scripts/check_claim_gate_matrix.py
+
+# The authorization surface, counted rather than described.
+python3 scripts/check_route_auth.py # every route authenticates, or is listed with a reason
+python3 scripts/check_route_authz.py # every state-changing route authorizes, or is listed
+python3 scripts/check_one_permission_model.py --check
+
+# Nothing is pointed at the internet by default.
+python3 scripts/check_default_egress.py
+
+# Every gate named in this pack is actually wired to a workflow.
+python3 scripts/check_gate_coverage.py
+```
+
+[`docs/audit/CLAIM_TO_GATE_MATRIX.md`](../audit/CLAIM_TO_GATE_MATRIX.md) is the
+long form: one row per published claim, each naming the job that fails when the
+claim stops being true. Rows marked `PARTIAL` name their own gap.
+
+## What this pack is not
+
+- **Not an audit report.** No third-party audit has been commissioned against
+ AiSOC. The reasoning, the trigger condition and the sequencing are recorded
+ in [ADR-0002](../decisions/0002-compliance-claims.md).
+ That ADR also asserts a CI check that **does not exist** — see
+ [the questionnaire](questionnaire.md#governance-and-assurance), which states
+ the real position. Surfacing that is this pack's own rule working: the
+ sentence was written from the ADR and caught by
+ `scripts/check_security_pack_links.py` before it shipped.
+- **Not a penetration-test report.** None has been commissioned. What exists
+ instead is a public advisory history: **16 advisories published** at the
+ time of writing, covering findings from both external reports and internal
+ audits, each with the fix and the regression guard. See
+ [the questionnaire](questionnaire.md#vulnerability-management) and the
+ [advisory list](https://github.com/beenuar/AiSOC/security/advisories).
+- **Not a statement about a deployment you have not seen.** Most of these
+ controls are properties of the software. Whether your operator configured
+ them is a question about your deployment, and
+ [the data-handling page](data-handling.md) says which is which.
diff --git a/docs/security/architecture-and-data-flow.md b/docs/security/architecture-and-data-flow.md
new file mode 100644
index 000000000..86661e6b0
--- /dev/null
+++ b/docs/security/architecture-and-data-flow.md
@@ -0,0 +1,170 @@
+# Architecture and data flow
+
+What the components are, where the trust boundaries fall, and where each class
+of data goes. The two STRIDE models
+([platform](platform-threat-model.md), [agent](agent-threat-model.md)) analyse
+the threats; this page is the map they analyse.
+
+Every component named below is a directory in this repository or a service in
+[`docker-compose.yml`](../../docker-compose.yml). The service counts are not
+prose — `scripts/check_profile_service_counts.py` fails when a published
+figure disagrees with the compose file, and it reports **core 16, full 22**.
+
+## Deployment topology
+
+```mermaid
+flowchart TB
+ subgraph Vendors["Your vendors — outside the boundary"]
+ EDR["EDR / SIEM / cloud / IAM / SaaS"]
+ LLMP["Hosted model provider, only if configured"]
+ TI["Threat-intel feeds you enable"]
+ end
+
+ subgraph Perimeter["Your infrastructure"]
+ subgraph Edge["Edge"]
+ WEB["web — Next.js console"]
+ RT["realtime — WebSocket / SSE"]
+ ING["ingest — OCSF normalisation"]
+ end
+
+ subgraph Core["Application"]
+ API["api — FastAPI, owns the vault and the tenant session"]
+ FUS["fusion — correlate, promote, detect"]
+ AG["agents — triage and investigation"]
+ ACT["actions — response executors"]
+ CONN["connectors — scheduled polling"]
+ end
+
+ subgraph Stores["Data stores"]
+ PG[("Postgres — alerts, cases, audit, vault ciphertext")]
+ KAF[["Kafka — the event spine"]]
+ RD[("Redis — cache, queues, rate limits")]
+ CH[("ClickHouse — event lake, full profile")]
+ NEO[("Neo4j — entity graph, full profile")]
+ QD[("Qdrant — vectors, full profile")]
+ end
+
+ OLL["ollama — the bundled local model"]
+ end
+
+ EDR -->|"poll or webhook"| CONN --> ING --> KAF --> FUS
+ EDR -->|"webhook"| ING
+ FUS --> PG
+ FUS --> CH
+ FUS --> KAF
+ KAF --> AG
+ AG --> API
+ AG -.->|"only when configured"| LLMP
+ AG --> OLL
+ API --> PG
+ API --> RD
+ API --> ACT --> EDR
+ API --> TI
+ WEB --> API
+ RT --> KAF
+ WEB --> RT
+```
+
+Six of these are optional: `clickhouse`, `neo4j`, `opensearch`, `ueba`,
+`honeytokens` and `purple-team` carry a compose `profiles:` key and do not
+start under `make up`. The lake, the graph and the vector store are therefore
+absent on a default install, and so is any data in them.
+
+## Trust boundaries, and what crosses each
+
+| Boundary | Crosses it | Control | Where |
+|---|---|---|---|
+| Browser → API | A session JWT or an API key | One authentication funnel resolves every credential type and records the verified principal | [`deps.py::get_current_user`](../../services/api/app/api/v1/deps.py) |
+| Vendor → ingest | Attacker-influenceable telemetry | Authenticated ingest; OCSF normalisation; schema validation with poison events to a dead-letter queue | [`services/ingest`](../../services/ingest), [`dlq.py`](../../services/fusion/app/services/dlq.py) |
+| Telemetry → model prompt | Attacker-influenceable strings | Per-run nonce evidence fence, injection guard, structured-output re-validation | [agent threat model](agent-threat-model.md) |
+| Model → tool call | A verdict and a proposed action | Capability contract, confidence × impact approval matrix, autonomy tier | [`services/actions`](../../services/actions) |
+| Service → service | A shared service token | The token, **plus** the tenant as a header verified against the `tenants` table; a service naming no tenant is refused | [`deps.py`](../../services/api/app/api/v1/deps.py) |
+| Tenant → tenant | Nothing, by design | Row-level security on Postgres plus query-layer predicates; a per-store scope for each of the other five | [below](#tenant-isolation-per-store) |
+| API → vendor | A decrypted connector credential | Vault decryption at point of use; least-privilege scopes | [`credential_vault.py`](../../services/api/app/security/credential_vault.py), [least privilege](connector-least-privilege.md) |
+
+## The event path, end to end
+
+A single event's journey, and what is written where:
+
+1. **Arrival.** A connector polls a vendor on a schedule, or the vendor posts
+ to an ingest webhook. Credentials for the poll are decrypted from the vault
+ at that moment.
+2. **Normalisation.** `services/ingest` maps the vendor payload to OCSF and
+ stamps the tenant. The vendor's original payload is preserved under
+ `raw_event`.
+3. **The spine.** The normalised event is produced to Kafka. The tenant
+ travels in the envelope.
+4. **Fusion.** `services/fusion` archives to the lake if the lake is running,
+ evaluates the detection corpus, and promotes what qualifies into an alert
+ row in Postgres. Correlation groups alerts into incidents.
+5. **Triage.** `services/agents` consumes fused alerts and triages each one.
+ This is the only step that can involve a model, and
+ [what reaches the model depends on the mode](data-handling.md).
+6. **Response.** Any action is a capability with a declared risk,
+ reversibility and approval tier. The default posture requires a human.
+7. **Record.** Every agent decision is appended to the Investigation Ledger,
+ and every mutating API call to a hash-chained audit log.
+
+## Tenant isolation, per store
+
+Postgres row-level security covers one of six stores, so each of the other
+five needed its own answer. The suite that holds them is
+[`tests/isolation/`](../../tests/isolation/), in two layers: an offline half
+asserting each read path *constructs* a scope, and a live half that seeds two
+tenants into real containers and asserts a read as A returns zero B rows.
+
+| Store | Scope | Gate |
+|---|---|---|
+| Postgres | Row-level security (133 `CREATE POLICY` statements) **and** query-layer `tenant_id` predicates | `scripts/check_tenant_query_predicates.py`, `isolation-live.yml` |
+| ClickHouse | `lake_sql.rewrite_for_tenant` injects the predicate and **fails closed** if it does not survive rendering | `lake-isolation.yml` |
+| Neo4j | A `tenant_id` property filter on every node of every path | `isolation-live.yml` |
+| Redis | A `tenant:{id}:` key prefix | `isolation-live.yml` |
+| Kafka | The tenant in the envelope, filtered downstream | `isolation-live.yml` |
+| Qdrant | `tenant_id` in the point payload plus a mandatory query filter | `isolation.yml` |
+
+Two limits worth stating. **Row-level security only binds a role that does not
+bypass it** — the services connect as a DML-only `aisoc_app` role rather than
+the owner, and `scripts/check_runtime_db_role.py` holds that. And **public
+feed intelligence is deliberately global**: scoping targets tenant-private
+data, not a CISA KEV entry every tenant should see.
+
+## Where credentials live
+
+Connector credentials are the top asset, because compromising AiSOC
+compromises everything it connects to.
+
+```mermaid
+flowchart LR
+ Op["Operator enters a credential"] --> API["API — the only writer"]
+ API --> V["CredentialVault"]
+ V -->|"vault:v1: Fernet"| PG[("Postgres ciphertext")]
+ V -->|"vault:v2: envelope"| PG
+ V -. "v2 only" .-> KMS["KEK in KMS — never leaves"]
+ CONN["connectors — read path only"] --> PG
+```
+
+The API service holds the encrypt/decrypt authority. `services/connectors`
+ships a vendored read-path `decrypt_dict()` so the poll scheduler can decrypt
+without owning the write path, and those vendored copies must **refuse** a
+`vault:v2:` token rather than hand ciphertext onward as if it were a
+credential.
+
+Under `vault:v1:` (the default), a database dump is bounded by
+`AISOC_CREDENTIAL_KEY` alone. That is why `vault:v2:` exists: with
+`AISOC_CREDENTIAL_ENVELOPE=aws` the key-encryption key never leaves KMS, so a
+dump yields wrapped data keys and ciphertext that are useless without KMS
+`decrypt`. Per-secret data keys also bound the blast radius — one compromised
+data key exposes one secret, not the vault. Details and the rotation procedure
+are in the [platform threat model](platform-threat-model.md#key-rotation-tested).
+
+## What the console can reach
+
+The console calls the API and nothing else. It holds no credential material,
+and the one response in the product that returns a secret — minting a workload
+identity — returns it once and stores only a digest.
+
+A note on build-time configuration, because it has bitten this project: Next
+inlines `NEXT_PUBLIC_*` at build time, so a published console image cannot be
+repointed by an environment variable at run time. The container entrypoint
+re-resolves its upstream addresses from the live environment and serves one
+authoritative answer at `/api/runtime-config` instead.
diff --git a/docs/security/data-handling.md b/docs/security/data-handling.md
new file mode 100644
index 000000000..09338fde9
--- /dev/null
+++ b/docs/security/data-handling.md
@@ -0,0 +1,170 @@
+# Data handling by deployment mode
+
+What leaves your perimeter, what is stored, and for how long — answered per
+mode, because the answers genuinely differ and a single answer for all of them
+would be wrong three times out of four.
+
+[`docs/trust/data-flows.md`](../trust/data-flows.md) is the short version of
+the egress question. This page is the whole data lifecycle.
+
+## The four modes
+
+| Mode | How it is started | Who runs the infrastructure | Who runs the model |
+|---|---|---|---|
+| **Self-hosted, bundled model** | `make up` | You | You — `ollama` in your own stack |
+| **Self-hosted, hosted model** | `make up`, then configure a provider in the console | You | A third party you choose and contract with |
+| **Air-gapped** | `infra/compose/docker-compose.airgap.yml` | You | You, with no route off the host |
+| **Managed** | Operated for you | The maintainers | See [sub-processors](subprocessors.md) |
+
+The default is the first. `make up` needs no account, no key and no GPU: it
+ships `llama3.2:3b-instruct-q4_K_M` and triage produces a real verdict from a
+real model with real token counts. That matters for this page because **the
+default configuration makes no model call off your infrastructure at all.**
+
+## Egress, per mode
+
+### What never leaves, in every mode
+
+- **No telemetry to the AiSOC project.** There is no phone-home and no
+ "model improvement" callback. This is enforced, not asserted:
+ `scripts/check_default_egress.py` reads every service's declared settings
+ defaults and fails on a public host that no air-gap guard covers — 25 URL
+ defaults across 11 settings modules, 23 private and 2 allow-listed with a
+ reason. `tests/test_no_default_egress.py` puts a socket guard in front of
+ each service's import and ASGI startup, because the static gate cannot see a
+ URL built at run time.
+- **Your stores.** Postgres, Kafka, Redis, and the optional ClickHouse, Neo4j
+ and Qdrant are containers in your own stack. Nothing replicates them
+ outward.
+
+A third control covers what the first two structurally cannot: the static gate
+is blind to run-time URLs and the socket guard is blind to paths startup does
+not reach. [`container-egress.yml`](../../.github/workflows/container-egress.yml)
+starts images built from the commit under test on a Docker network created
+`--internal`, with a DNS sinkhole as their only resolver, and classifies every
+name they ask for. It carries a canary — a container wired identically that
+*must* be seen by the sinkhole — because zero observations is what a correct
+run and a blind probe both look like.
+
+### Self-hosted with the bundled model
+
+Nothing leaves for triage. The model runs in the `ollama` container beside
+everything else.
+
+Two things still leave if you enable them, both on purpose and both yours to
+turn off:
+
+- **Connector polling** reaches the vendors you connected. That is the
+ product.
+- **Threat-intel feeds** you enable. The one that is on by default is the
+ CISA Known Exploited Vulnerabilities catalog — a public, authoritative feed
+ that needs no API key and receives nothing from you but the request.
+
+### Self-hosted with a hosted model
+
+Evidence reaches the provider you configured, **pseudonymized**.
+
+This is the paragraph that was wrong for a long time, so it is worth being
+exact about what changed. The reversible pseudonymizer
+([`services/agents/app/privacy/redactor.py`](../../services/agents/app/privacy/redactor.py))
+existed and was unit-tested, and **no LLM call site invoked it** — so the
+documentation described a planned control as a shipped one. It is now applied
+at the contract layer
+([`services/agents/app/llm/contract.py`](../../services/agents/app/llm/contract.py)
+calls `egress_privacy.open_session`), which is the one place all sixteen agent
+call sites already pass through.
+
+| What is replaced | With |
+|---|---|
+| Internal IPs, internal hostnames | `IP_3`, `HOST_2` |
+| Usernames, email addresses | `USER_1` |
+| File paths, secrets | opaque per-run tokens |
+| **Public threat indicators** | **nothing — preserved deliberately**, or the agent cannot reason about them |
+
+Tokens are per-run and in-memory. The model reasons over tokens; the ledger
+and console re-hydrate real values locally.
+
+The gate is [`test_egress_pseudonymization.py`](../../services/agents/tests/test_egress_pseudonymization.py),
+and it is worth noting *how* it is written: it drives `safe_ainvoke` and
+inspects what a fake provider actually received, rather than calling the
+redactor directly. Testing the path rather than the function immediately found
+a real gap the unit test could not — a bare username in prose
+(`running as priya.raghavan`) went out in the clear, because usernames were
+only redacted in the `DOMAIN\user` form or under a user-ish key.
+
+**You can turn it off.** If you do, raw evidence reaches the provider. Use
+that only under a signed zero-retention agreement.
+
+### Air-gapped
+
+`infra/compose/docker-compose.airgap.yml` ships the local model and expects no
+route off the host. This is the only mode in which "no evidence leaves" is
+unconditionally true, and it is the mode the container-egress job exercises.
+
+### Managed
+
+The maintainers operate the infrastructure. See
+[sub-processors](subprocessors.md), which says plainly what this repository can
+and cannot establish about that arrangement.
+
+## What is stored, and where
+
+| Data | Store | Notes |
+|---|---|---|
+| Alerts, cases, users, tenants | Postgres | Row-level security plus query-layer predicates |
+| Connector credentials | Postgres, as ciphertext | Never in the clear; see [the vault](platform-threat-model.md) |
+| Audit log | Postgres | Hash-chained, and a `BEFORE UPDATE OR DELETE` trigger ([migration 004](../../services/api/migrations/004_audit_log.sql)) refuses both |
+| Investigation Ledger | Postgres | Every agent step, with the prompt and response |
+| Raw events | ClickHouse | **Full profile only.** Absent on a default install |
+| Entity graph | Neo4j | Full profile only |
+| Embeddings | Qdrant | Full profile only |
+| Cache, queues, rate limits | Redis | Tenant-prefixed keys |
+| In-flight events | Kafka | Tenant in the envelope; retention is your broker's setting |
+
+## Encryption
+
+| | State | Where |
+|---|---|---|
+| Connector credentials | **Fernet AES-128-CBC + HMAC-SHA256** by default (`vault:v1:`), or envelope encryption with a KMS-held key (`vault:v2:`) | [`credential_vault.py`](../../services/api/app/security/credential_vault.py), [`envelope_cipher.py`](../../services/api/app/security/envelope_cipher.py) |
+| Backups | **AES-256-GCM**, chunked with a per-chunk nonce and additional authenticated data binding the chunk index and the final flag, so a reordered or truncated archive is refused | [`scripts/backup_crypt.py`](../../scripts/backup_crypt.py) |
+| Everything else at rest | Your disk encryption | A property of your infrastructure, not of this software |
+| In transit, browser to edge | Your TLS terminator | Not shipped; the compose stack serves plain HTTP and expects a reverse proxy |
+| In transit, service to service | **Plaintext inside the container network** on the default compose stack | Stated rather than implied. Deployments needing mutual TLS between services should supply it at the platform layer |
+
+The backup row is specific because it used to be false: the script gzipped and
+uploaded while the documentation claimed AES-256-GCM. Two things make the claim
+real now. `openssl enc` **refuses AEAD ciphers**, which is why the encryption
+is a Python script on `cryptography` rather than a shell one-liner. And
+`Backup → destroy → restore (Postgres via S3)` is a **required** status check
+that seeds real data, encrypts, destroys, restores, measures recovery time and
+proves a bit-flipped archive is refused.
+
+## Retention and deletion
+
+- **Per-tenant retention** is implemented in
+ [`services/api/app/services/retention.py`](../../services/api/app/services/retention.py).
+ The purge worker ships **default off and dry-run first**, deliberately: a
+ deletion job that starts deleting on upgrade is a worse failure than one
+ that has to be switched on.
+- **Tenant deletion** is
+ [`services/api/app/services/tenant_deletion.py`](../../services/api/app/services/tenant_deletion.py).
+ It exists because 14 tenant-scoped tables had no foreign-key cascade, so
+ deleting a tenant orphaned institutional memory and compliance evidence
+ rather than removing it.
+- **Kafka retention** is your broker's configuration, not ours.
+- **The audit log is append-only by design**, which is in tension with a
+ deletion request and is the right tension to have. The hash chain is what
+ makes the log evidence; a log that can be edited to satisfy a request is not
+ one.
+
+## Subject-access and portability
+
+There is an audit export surface
+([`services/api/app/services/audit_export.py`](../../services/api/app/services/audit_export.py))
+producing CSV and HTML bundles, and a report builder for case material.
+
+What does **not** exist is a dedicated data-subject-request endpoint.
+[ADR-0002](../decisions/0002-compliance-claims.md) records the intent and its
+open question; no such route is in the tree today, and
+[the questionnaire](questionnaire.md#privacy-and-data-subject-rights) lists it
+as a gap rather than describing it as a feature.
diff --git a/docs/security/questionnaire.md b/docs/security/questionnaire.md
new file mode 100644
index 000000000..4b66fea1f
--- /dev/null
+++ b/docs/security/questionnaire.md
@@ -0,0 +1,363 @@
+# Security questionnaire
+
+Standard control questions, answered for the **software**. Where the answer
+depends on how an operator deployed it, that is said. Where the answer is no,
+it says no — a questionnaire with no gaps in it has not been filled in
+honestly, and [the gap list](#the-gap-list) at the end collects every one.
+
+Every "yes" names the file or the CI job behind it. A reviewer who wants to
+check rather than read should start with
+[the verification commands](README.md#verifying-any-of-this-yourself).
+
+---
+
+## Governance and assurance
+
+**Do you hold SOC 2, ISO 27001 or equivalent certification?**
+**No.** No third-party audit has been commissioned.
+[ADR-0002](../decisions/0002-compliance-claims.md) records the decision, the
+trigger condition (a Type I audit in the first quarter with both a revenue
+threshold and an enterprise design partner for whom it is
+procurement-blocking) and the sequencing. Marketing surfaces say "controls
+aligned to" rather than naming a framework unqualified.
+
+**That convention is a convention, not a gate.** ADR-0002 states that
+`scripts/audit_compliance_claims.py` "already exists" and fails the build on
+an unqualified framework name. **It does not exist, and no workflow references
+it** — a finding
+[`docs/audit/REALITY_REPORT.md`](../audit/REALITY_REPORT.md) already records
+under "Referenced-but-missing CI guard". Listed [below](#the-gap-list).
+
+**Has a penetration test been performed?**
+**No external test has been commissioned.** What exists instead is a public
+advisory history — 16 advisories published, from both external reports and
+internal audits, each with its fix and a regression guard. Private
+vulnerability reporting is enabled; the process and response windows are in
+[`SECURITY.md`](../../SECURITY.md).
+
+**Do you have a documented secure development lifecycle?**
+Yes, and it is unusually literal here: every published product claim maps to a
+CI job in [`docs/audit/CLAIM_TO_GATE_MATRIX.md`](../audit/CLAIM_TO_GATE_MATRIX.md)
+(290 rows), and `scripts/check_claim_gate_matrix.py` enforces a ratchet of
+zero ungated rows. 28 status checks are required on `main`, listed in
+[`.github/required-checks.json`](../../.github/required-checks.json) and
+cross-checked against the live branch protection.
+
+**How do you know a required check actually graded a commit?**
+Because that failed here and was measured. Over the last 30 commits before the
+fix, only 336 of 660 required-check × commit pairs had been graded and **0 of
+22 required checks had graded all 30** — 28 workflows keyed `concurrency` on
+`github.ref`, so a push to `main` cancelled the run before it. There is now a
+required check named `No workflow can discard a push to main`, and another,
+`No required check can skip its own assertions`, for the adjacent failure
+where a job runs only its "nothing changed" step and reports success.
+
+---
+
+## Identity and access
+
+**How do users authenticate?**
+Email and password with bcrypt, OIDC or SAML single sign-on
+([`sso_connections.py`](../../services/api/app/api/v1/endpoints/sso_connections.py)),
+or WebAuthn passkeys
+([`passkeys.py`](../../services/api/app/api/v1/endpoints/passkeys.py)). Access
+tokens expire in 30 minutes and refresh tokens in 7 days by default.
+
+**Is multi-factor authentication enforced?**
+**Not today.** WebAuthn passkeys exist and work, which is a passwordless
+*sign-in* factor rather than an enforced second factor, and there is no
+policy that requires MFA per role or per tenant. This is a gap, listed
+[below](#the-gap-list).
+
+**How is authorization decided?**
+One path. `CurrentUser.require_permission` in
+[`deps.py`](../../services/api/app/api/v1/deps.py) is the only permission
+check in the service, and `scripts/check_one_permission_model.py` enforces
+that it stays the only one. Two shipped side by side once — 275 routes read a
+hardcoded map while 27 read the database the console's RBAC screen writes to,
+so an operator could grant a permission, watch it appear in the UI, and have
+275 of 302 routes ignore it.
+
+**Can a user grant themselves more access than they hold?**
+No, and the property is enforced on the *granter* rather than enumerated per
+route: [`role_grants.py`](../../services/api/app/core/role_grants.py) refuses
+any grant of a role, scope or permission the caller does not itself hold, and
+refuses the wildcard roles to everyone. An allow-list per route was the
+tempting repair and the wrong one — four other routes had the same defect, and
+the fifth written next year would have been a new advisory
+([GHSA-pm3f-h6gc-rvgp](https://github.com/beenuar/AiSOC/security/advisories/GHSA-pm3f-h6gc-rvgp)).
+
+**Does every endpoint require authentication?**
+Yes or listed. `scripts/check_route_auth.py` is default-deny over every route
+under `services/`: a route with no auth dependency must appear in one of three
+tables with its reason, and the gate fails both on an unexplained route and on
+a stale exemption that no longer matches one. `services/mesh` is public by
+design (Ed25519 plus k-anonymity; a bearer token would break federation rather
+than secure it) and is recorded as such.
+
+**Does every endpoint that changes state check a permission?**
+Most, and the rest are counted rather than hidden.
+`scripts/check_route_authz.py` reports the ratio and holds a ceiling that can
+only fall. Its own docstring calls the number "not a target, a debt balance".
+
+**Is there just-in-time privileged access?**
+**No.** A role is held permanently or not at all, so an analyst who needs a
+permission once either holds it every day or waits for somebody who does.
+Migration `087_enterprise_iam.sql` created a `privilege_grants` table for
+exactly this and **nothing reads it**, which is worse than the table not
+existing: a row written into it confers nothing while reading as though it
+does. Listed as a gap [below](#the-gap-list).
+
+**How do services authenticate to each other?**
+With a shared service token, and **the tenant is a mandatory header verified
+against the `tenants` table**. A service naming no tenant is refused rather
+than resolving to an unscoped read — every cross-tenant leak in this codebase
+has taken the other shape, a scope that was absent rather than narrow and a
+read that treated absent as "no filter".
+
+The weakness of one shared token is real and worth stating: it cannot be
+attributed to a particular service, cannot be scoped so the ingest pipeline
+carries less authority than the agents worker, and cannot be rotated without
+restarting everything at once. A `workload_identities` table exists for that
+and, like `privilege_grants`, has no reader. Both are in the gap list.
+
+This area had a worse defect that is fixed: the API once posted to the
+connectors service with **no `Authorization` header at all** from two modules,
+and the resulting 401 read to an operator as the customer's own SIEM rejecting
+us. `scripts/check_service_token_wiring.py` is the guard.
+
+---
+
+## Tenant isolation
+
+**How is one customer's data kept from another's?**
+Per store, because Postgres row-level security covers one of six.
+[The table is here](architecture-and-data-flow.md#tenant-isolation-per-store).
+Two layers of test: an offline half asserting each read path constructs a
+scope, and a live half seeding two tenants into real containers and asserting
+a read as A returns zero B rows — after first asserting both rows exist
+unscoped, so a scoped pass cannot be vacuous.
+
+**Does the application connect to the database as a superuser?**
+No, and that detail is load-bearing: RLS was decorative until it was fixed,
+because a superuser ignores every policy even under `FORCE ROW LEVEL
+SECURITY`. Services connect as a DML-only `aisoc_app` role, held by
+`scripts/check_runtime_db_role.py`.
+
+**Can a caller choose which tenant they act for?**
+No. The tenant comes from the authenticated principal, or for a service caller
+from a header the model cannot influence.
+`scripts/check_route_tenant_scope.py` fails on a route that takes a tenant
+identifier without an auth dependency, and on one that accepts a tenant
+without intersecting it with the caller's scope.
+
+---
+
+## Encryption
+
+**At rest?**
+Connector credentials are encrypted by the application in every deployment —
+Fernet by default, or envelope encryption with a KMS-held key-encryption key.
+Backups are AES-256-GCM, chunked, with the chunk index and final flag bound as
+additional authenticated data so a reordered or truncated archive is refused.
+Disk-level encryption for the datastores is a property of your infrastructure.
+[Full table](data-handling.md#encryption).
+
+**In transit?**
+Browser-to-edge TLS is your terminator's job; the compose stack serves plain
+HTTP behind a reverse proxy. **Service-to-service traffic inside the container
+network is plaintext on the default stack** — stated rather than implied, and
+a deployment needing mutual TLS between services should supply it at the
+platform layer.
+
+**Key management and rotation?**
+Rotation under envelope mode is a *re-wrap*, not a re-encrypt: the data key is
+unwrapped with its original key-encryption key and re-wrapped with the current
+one, and the secret body is never touched. Gated by
+`services/api/tests/test_envelope_cipher.py`. The residual risk is stated in
+the [platform threat model](platform-threat-model.md#residual-risk): the
+running API must be able to decrypt, so a live KMS `decrypt` permission on
+that host remains a compromise path.
+
+---
+
+## Logging, audit and monitoring
+
+**Is there an audit trail, and can it be tampered with?**
+Every mutating API call writes a row carrying the actor, and the rows are
+hash-chained so truncation, reordering or rewriting is detectable. A
+`BEFORE UPDATE OR DELETE` trigger
+([migration 004](../../services/api/migrations/004_audit_log.sql)) refuses the
+normal SQL path; the chain catches what a trigger cannot, including an
+operator who can disable triggers.
+
+**Could an unauthenticated caller write to it?**
+They could, and that is fixed and gated.
+[GHSA-w4r8-969c-67p2](https://github.com/beenuar/AiSOC/security/advisories/GHSA-w4r8-969c-67p2):
+the audit middleware decoded the bearer token with signature verification
+disabled, so a self-crafted JWT got 401 from the route and still planted an
+actor of the attacker's choosing into any known tenant's chain. It now audits
+only the principal authentication verified, and
+[`audit-forgery-live.yml`](../../.github/workflows/audit-forgery-live.yml)
+proves it against real Postgres with a negative control that reintroduces the
+vulnerability and requires the suite to go red.
+
+**Are AI decisions auditable?**
+Yes — the Investigation Ledger records every agent step with its prompt,
+response and tools used, and `aisoc_explain_step` over MCP returns them.
+
+**Is there monitoring?**
+Partially, and the gap is published rather than papered over. **5 of 19**
+services expose `/metrics`; `scripts/audit_prometheus_targets.py` names the
+14 that do not, in its own output, so the gap is a line of the gate's report
+rather than something a reader has to go looking for. Service-level objective
+alerts are generated only for scraped services, so none can be permanently
+dead.
+
+---
+
+## Vulnerability management
+
+**How are dependencies managed?**
+Every Python service installs from a committed `poetry.lock`; the pip
+fallbacks were deleted, because a fallback that resolves a different version
+set means the image boots on software nobody tested.
+`scripts/check_dependency_pins.py` holds the toolchain equal across fourteen
+declaration sites, and `No two install paths disagree` is a required check.
+
+**What scans run?**
+CodeQL across three languages, with
+[`codeql-alert-gate.yml`](../../.github/workflows/codeql-alert-gate.yml)
+failing on any open alert at **any** severity including `note` — and refusing
+a vacuous pass: an unanalysed ref, a declared language with no analysis, an
+analysis older than ten days, or an analysis belonging to a different commit
+than the run's all fail. `Zero open CodeQL alerts`, `Secret scan (gitleaks)`,
+`Trivy filesystem`, and the two ratcheted infrastructure-as-code scans are
+required checks.
+
+**Why is Semgrep not a required check?**
+Because it is non-deterministic on this repository and that was measured: four
+pull requests on one base, within thirteen minutes, over an identical
+2,267-file corpus with an identical rule set, split 102/40 and 101/39.
+Requiring it would red roughly one pull request in twenty for a reason no
+author can act on. The sharper consequence is that a ratchet over a scanner
+that can lose a finding at random **fails open**, so the decision not to
+require it is recorded in three places, each naming the condition under which
+requiring it becomes reasonable.
+
+**Supply chain?**
+Releases publish an SPDX SBOM, sign images keylessly with cosign, and attach
+SLSA provenance (`provenance: mode=max`) — see
+[`release.yml`](../../.github/workflows/release.yml). Plugin installs verify
+signed Ed25519 manifests against an allow-list and pin image digests at
+install time, re-verifying on every load.
+
+---
+
+## Resilience
+
+**Are backups tested?**
+Yes, and this is the row to copy if you only check one.
+`Backup → destroy → restore (Postgres via S3)` is a **required** status check
+that seeds real data, encrypts it, destroys the database, restores it,
+measures recovery time and proves a bit-flipped archive is refused. It is
+required because "we take backups" and "we have restored one" are different
+claims.
+
+**What happens to a message that cannot be processed?**
+A poison event goes to a dead-letter queue
+([`dlq.py`](../../services/fusion/app/services/dlq.py)) with a replay path,
+rather than stopping the consumer. Consumers distinguish permanent from
+transient faults and say which — a consumer detached from its topic while
+`/health` returns 200 is indistinguishable from an idle one, which is exactly
+what made one such bug invisible for a long time.
+
+---
+
+## AI-specific controls
+
+**What stops prompt injection from driving a response action?**
+A layered answer, and the honest number is published with it. Telemetry is
+wrapped in a per-run nonce fence the attacker cannot predict; a guard scans
+for instruction-shaped content and demotes the case to manual review on a
+high-severity hit; model output is re-validated against a schema, so a coerced
+free-text verdict is not authoritative; and every tool call is governed by a
+capability contract with an approval tier.
+
+**And the numbers?** On the field-native corpus the guard went from 66.7% to
+98.1% detection, and on the prose corpus from 0.852 to 0.96 recall with false
+positives still at 0.00. Those are the flattering ones. The one that matters
+is that **held-out payloads moved only 3.6% to 7.1%** — the hardening fitted
+the corpus far more than it closed the threat, and it is published *because*
+it is unflattering. An MIT-licensed guard in a public repository
+means white box is the correct threat model. Per-family flip rates are
+published too, including `fake_tool_output` at 1.0 flip and 0.0 catch,
+recorded at that value rather than patched.
+
+**Can the model execute an action on its own?**
+Not by default. The shipped posture is copilot with human approval. Where
+autonomy is enabled, the tier is per tenant and per capability, risk and
+reversibility are declared on the *verb* rather than the vendor, and a
+capability whose effect cannot be verified is not eligible for automatic
+execution — "unverifiable means not autonomous" demoted two capabilities that
+had claimed it.
+
+**Is customer data used to train models?**
+No. The project neither trains nor fine-tunes on customer data and has no
+mechanism to receive it. What a provider you configure does with what you send
+is between you and them, which is why the pseudonymizer sits at the contract
+layer.
+
+**Can the model choose its own tenant?**
+No, and this one is worth naming because it is easy to get wrong: an MCP tool
+that declares a `tenant_id` argument and forwards it is a latent cross-tenant
+read even when unexploitable. The tenant comes from the principal or from a
+header, and the parameter is deleted rather than validated.
+
+---
+
+## Privacy and data-subject rights
+
+**Where is personal data processed?**
+Wherever you run it. See [sub-processors](subprocessors.md) — for self-hosted
+the answer is "your infrastructure and the vendors you chose", and for the
+hosted service that page says plainly what this repository cannot establish.
+
+**Is there a data-subject-request workflow?**
+**No dedicated endpoint exists.** Audit export and tenant deletion exist and
+are linked from [data handling](data-handling.md#retention-and-deletion), but
+a subject-request route is not in the tree. ADR-0002 names it as an open
+question. Listed as a gap below.
+
+**Is there a published GDPR posture?**
+**No.** ADR-0002 committed to `docs/compliance/gdpr.md` "alongside this ADR"
+and it does not exist. Listed as a gap below.
+
+---
+
+## The gap list
+
+Collected so a reviewer does not have to assemble it from the prose above.
+Each is a real absence, not a caveat.
+
+| Gap | State today | Where it is recorded |
+|---|---|---|
+| **Enforced MFA** | Passkeys exist as a sign-in factor; no per-role or per-tenant enforcement policy | This page |
+| **Just-in-time elevation** | `privilege_grants` exists as schema with no reader; a row in it confers nothing | This page |
+| **Attribute conditions on a permission** | `permission_conditions` exists as schema with no reader; a row in it denies nothing | This page |
+| **Per-service internal credentials** | `workload_identities` exists as schema with no reader; the one shared token is unattributable, unscopable and effectively unrotatable | This page |
+| **SOC 2 / ISO 27001** | Not commissioned; "controls aligned to" framing held by convention | [ADR-0002](../decisions/0002-compliance-claims.md) |
+| **The gate ADR-0002 claims guards that framing** | `scripts/audit_compliance_claims.py` does not exist and no workflow references it | [`REALITY_REPORT.md`](../audit/REALITY_REPORT.md) |
+| **Penetration test** | Not commissioned; 16 published advisories instead | [`SECURITY.md`](../../SECURITY.md) |
+| **Hosted-service sub-processor list** | Does not exist; ADR-0002 promised one that never landed | [Sub-processors](subprocessors.md) |
+| **GDPR posture document** | `docs/compliance/gdpr.md` promised by ADR-0002, absent | [Sub-processors](subprocessors.md) |
+| **Data-subject-request endpoint** | Not in the tree | This page |
+| **Service-to-service TLS** | Plaintext inside the container network on the default stack | [Data handling](data-handling.md#encryption) |
+| **`/metrics` coverage** | 5 of 19 services; the other 14 named in the gate's own output | `scripts/audit_prometheus_targets.py` |
+| **Prompt-injection guard on held-out payloads** | 7.1%. Published because it is the honest number | [Agent threat model](agent-threat-model.md#residual-risk) |
+| **Connector scope conformance gate** | The least-privilege document is enforced in review, not by CI | [Least privilege](connector-least-privilege.md#audit) |
+
+If a control you need is absent from both the answers and this table, it is
+more likely that nobody asked than that it is deliberately omitted —
+[open an issue](https://github.com/beenuar/AiSOC/issues) and it will be
+answered the same way: with the file, or with "no".
diff --git a/docs/security/subprocessors.md b/docs/security/subprocessors.md
new file mode 100644
index 000000000..f34a3f105
--- /dev/null
+++ b/docs/security/subprocessors.md
@@ -0,0 +1,114 @@
+# Sub-processors
+
+> **Status: incomplete, deliberately.** There is no verified sub-processor
+> list for the hosted service in this repository, and this page does not
+> invent one. What follows is (1) the answer for self-hosted deployments,
+> which is complete and checkable, and (2) a clearly-marked placeholder for
+> the hosted service, with exactly what is missing and who can supply it.
+
+## Self-hosted: there are none, by construction
+
+If you run AiSOC yourself, **the project processes none of your data and
+operates no infrastructure in the path**. There is no phone-home, no telemetry
+to the AiSOC project, and no model-improvement callback. That is enforced by
+three independent controls rather than asserted —
+[`scripts/check_default_egress.py`](../../scripts/check_default_egress.py),
+`tests/test_no_default_egress.py` and
+[`container-egress.yml`](../../.github/workflows/container-egress.yml) — and
+the detail is in [data handling](data-handling.md#what-never-leaves-in-every-mode).
+
+The processors in a self-hosted deployment are therefore **the ones you
+choose**:
+
+| You choose | It receives | Your control |
+|---|---|---|
+| Your cloud or hardware | Everything | Yours entirely |
+| Each vendor you connect | API calls from the connector you configured, under the credential you issued | [Least-privilege scopes](connector-least-privilege.md) |
+| A model provider, **only if you configure one** | Pseudonymized evidence, or raw if you turn pseudonymization off | [Per-mode egress](data-handling.md#egress-per-mode) |
+| Each threat-intel feed you enable | A request. The only default is the public CISA KEV catalog, which receives nothing from you | Disable it |
+
+A contract with any of those is between you and them. The project is not a
+party to it and cannot be.
+
+## Hosted service: what this repository cannot establish
+
+The maintainers operate a managed offering. A sub-processor list for it is a
+legal artefact describing the processing arrangements actually in force, and
+**it cannot be derived from source code.** This page will not guess at one.
+
+### What the repository does say, and why that is not an answer
+
+Two documents describe hosted infrastructure:
+
+- [`apps/docs/docs/operations/managed-instance.md`](../../apps/docs/docs/operations/managed-instance.md)
+ describes an invite-only managed beta, naming Fly.io for compute, Fly
+ managed Postgres, Fly managed Redis, and Cloudflare for TLS termination.
+- [`docs/managed-mode.md`](../managed-mode.md) describes the
+ provision-from-`main` pipeline, and the machinery is still in the tree at
+ `infra/fly/managed/` and
+ [`managed-auto-provision.yml`](../../.github/workflows/managed-auto-provision.yml).
+
+Three reasons that is documentation and not a sub-processor list:
+
+1. **A deployment description is not a processing agreement.** A
+ sub-processor list states who processes personal data, for what purpose, in
+ which jurisdiction, and under which contract. None of that is in a compose
+ file or a Terraform module.
+2. **It cannot be verified as current from here.** Infrastructure changes
+ without a commit, and a hosting arrangement that moved would leave these
+ pages reading exactly as they do now. A reader has no way to tell a current
+ page from a stale one, and neither does this one.
+3. **The list is certainly longer than the hosting vendor.** Payment
+ processing, transactional email, error tracking, analytics and support
+ tooling are all plausible, each is a real sub-processor if present, and
+ **naming any of them without confirmation would be the fabrication this
+ page exists to avoid.**
+
+### The gap, stated
+
+[ADR-0002](../decisions/0002-compliance-claims.md) committed to publishing a
+GDPR posture at `docs/compliance/gdpr.md` — controller/processor mapping, a
+DPA template, a data-subject-request workflow and **a sub-processor list** —
+"alongside this ADR".
+
+**Neither `docs/compliance/gdpr.md` nor `docs/compliance/README.md` exists in
+the tree.** The single occurrence of the word "sub-processor" anywhere in this
+repository is the ADR line promising the list. That is recorded here as an
+open commitment rather than quietly dropped, which is the whole point of
+checking an ADR's deliverables against the tree.
+
+### What has to happen, and by whom
+
+This is a maintainer action, not a code change. Completing it needs:
+
+- [ ] The current hosting, database and cache providers for the managed
+ service, confirmed rather than inferred from `infra/`.
+- [ ] Every other vendor that touches customer data in that path — payments,
+ email, error tracking, analytics, support.
+- [ ] For each: purpose, data categories, processing location, and the DPA or
+ standard contractual clauses in force.
+- [ ] A change-notification commitment, since a sub-processor list without one
+ is a snapshot rather than a control.
+- [ ] The GDPR posture document ADR-0002 committed to, of which this list is
+ one section.
+
+Until those are supplied, **a prospective customer of the hosted service
+should ask for the list directly and not infer it from this repository.**
+Self-hosting removes the question entirely, which is the honest
+recommendation while this page is in the state it is in.
+
+## Models are the sub-processor people forget
+
+Worth separating out, because it is the one most often missed in an AI
+product's diligence.
+
+**On the default self-hosted install there is no model sub-processor at all.**
+`make up` ships `llama3.2:3b-instruct-q4_K_M` and runs it in your own stack —
+no account, no key, no GPU. Triage produces a real verdict from a real model
+with real token counts.
+
+A hosted model provider becomes a sub-processor only when **you** configure
+one, and then it is your contract. What it receives in that case is
+pseudonymized at the contract layer unless you turn that off; the mechanism,
+the token scheme and the deliberate exception for public threat indicators are
+in [data handling](data-handling.md#self-hosted-with-a-hosted-model).
diff --git a/docs/trust/data-flows.md b/docs/trust/data-flows.md
index cfa8a31b8..c7a8d4ded 100644
--- a/docs/trust/data-flows.md
+++ b/docs/trust/data-flows.md
@@ -1,49 +1,109 @@
# Data flows and egress
-Phase 1.4 of the world-class program. This page states exactly what leaves your
-perimeter under each configuration, so the README's "runs on your
-infrastructure" claim is precise rather than aspirational.
+This page states exactly what leaves your perimeter under each configuration,
+so the README's "runs on your infrastructure" claim is precise rather than
+aspirational.
+
+The full lifecycle — what is stored, for how long, and how it is encrypted —
+is in [`docs/security/data-handling.md`](../security/data-handling.md). This
+page is the egress question on its own.
## What never leaves
-- AiSOC sends **no telemetry to the AiSOC project** and makes no "model
- improvement" callbacks. There is no phone-home. (Gated: Phase 12 trust
- surface adds a no-telemetry CI assertion.)
-- Your database, object storage, graph, cache, and Kafka spine stay on your
- infrastructure.
-
-## The one egress that exists: your chosen LLM
-
-The investigation agent calls an LLM you configure. There are three modes:
-
-1. **Local model (fully air-gapped).** Point `AISOC_LLM_*` at Ollama / vLLM /
- llama.cpp. No evidence leaves your network at all. This is the only mode in
- which the "no data leaves" claim is unconditionally true.
-2. **Hosted LLM with redaction (default).** When you configure a cloud provider
- (hosted providers), evidence is **not** pseudonymized before egress today. The reversible
- pseudonymizer exists and is unit-tested, but no LLM call site invokes it, so this
- paragraph describes a planned control rather than a shipped one. Restored by parity 2.4.
- The mechanism, for reference, is
- `services/agents/app/privacy/redactor.py`: internal IPs, emails, file paths,
- secrets, internal hostnames, and usernames are replaced with opaque,
- per-run, in-memory tokens (`USER_1`, `HOST_2`, `IP_3`). The LLM reasons over
- tokens; the ledger and console re-hydrate real values locally. Public threat
- indicators (external domains/IPs) are preserved so the agent can reason about
- them. Gated: `services/agents/tests/test_privacy_redactor.py` asserts zero
- raw customer PII survives redaction.
-3. **Hosted LLM without redaction (opt-out).** If you disable redaction, raw
- evidence reaches the provider. Use only with a provider under a signed
- zero-retention agreement.
+- **No telemetry to the AiSOC project.** There is no phone-home and no
+ "model improvement" callback. Three controls hold it, because each is blind
+ where the others see: `scripts/check_default_egress.py` reads every
+ service's declared settings defaults and fails on a public host no air-gap
+ guard covers; `tests/test_no_default_egress.py` puts a socket guard in front
+ of each service's import and ASGI startup, catching URLs built at run time
+ that the static gate cannot see; and
+ [`container-egress.yml`](../../.github/workflows/container-egress.yml) runs
+ images built from the commit under test on a `--internal` Docker network
+ with a DNS sinkhole as their only resolver.
+- **Your stores.** Database, object storage, graph, cache and the Kafka spine
+ stay on your infrastructure.
+
+## The one egress that exists: your chosen model
+
+The investigation agent calls a model. There are three ways to configure it.
+
+### 1. Local model — the default, and fully air-gapped
+
+`make up` ships `llama3.2:3b-instruct-q4_K_M` and runs it in the `ollama`
+container beside everything else. No account, no key, no GPU, and **no
+evidence leaves your network at all**. This is the only mode in which the "no
+data leaves" claim is unconditionally true, and it is what a default install
+does.
+
+`infra/compose/docker-compose.airgap.yml` is the same thing with no route off
+the host.
+
+### 2. Hosted model, pseudonymized — what you get if you configure a provider
+
+Evidence is pseudonymized before egress.
+
+**This paragraph used to be false, and the correction is worth keeping.** The
+reversible pseudonymizer (`services/agents/app/privacy/redactor.py`) existed
+and was unit-tested, and **no LLM call site invoked it** — so this page
+described a planned control as a shipped one. It is now applied at the
+contract layer: `services/agents/app/llm/contract.py` calls
+`egress_privacy.open_session`, which is the one place all sixteen agent call
+sites already pass through.
+
+Internal IPs, emails, file paths, secrets, internal hostnames and usernames
+are replaced with opaque, per-run, in-memory tokens (`USER_1`, `HOST_2`,
+`IP_3`). The model reasons over tokens; the ledger and console re-hydrate real
+values locally. **Public threat indicators — external domains and IPs — are
+preserved deliberately**, because an agent that cannot see the indicator
+cannot reason about it.
+
+Gated by `services/agents/tests/test_egress_pseudonymization.py`, which drives
+`safe_ainvoke` and inspects what a fake provider actually received rather than
+calling the redactor directly. Testing the path rather than the function
+immediately found a gap the unit test could not: a bare username in prose
+(`running as priya.raghavan`) was going out in the clear, because usernames
+were only redacted in the `DOMAIN\user` form or under a user-ish key. The
+suite also pins the deliberate exception above, and carries a test that
+disables the control and requires the leak assertion to fail, so it cannot
+pass vacuously.
+
+### 3. Hosted model, raw — opt-out
+
+If you disable pseudonymization, raw evidence reaches the provider. Use only
+with a provider under a signed zero-retention agreement.
## Egress allowlist
-The only outbound destinations under normal operation are the LLM provider you
-configure and the threat-intel feeds you enable. A rendered Kubernetes
-`NetworkPolicy` that enforces this allowlist ships with the Helm chart (Phase 1.4
-continuation / Phase 2); until then, restrict egress at your network layer.
+Under normal operation the only outbound destinations are the model provider
+you configure, the vendors you connected, and the threat-intel feeds you
+enable. The only feed on by default is the public CISA Known Exploited
+Vulnerabilities catalog, which needs no API key and receives nothing from you
+but the request.
+
+A default-deny Kubernetes `NetworkPolicy` ships with the Helm chart at
+[`infra/helm/aisoc/templates/networkpolicy.yaml`](../../infra/helm/aisoc/templates/networkpolicy.yaml).
+`helm.yml` asserts that it denies by default and that `169.254.169.254/32` —
+the cloud metadata endpoint — is excluded from every allowed CIDR.
+
+One limit, stated: it is **opt-in**, because a CNI that does not enforce
+NetworkPolicy ignores it silently, and a control that can be silently ignored
+must not be presented as one that is always on. On a cluster whose CNI does
+not enforce it, or outside Kubernetes, restrict egress at your network layer.
+
+## Air-gapped verification
+
+[`container-egress.yml`](../../.github/workflows/container-egress.yml) is the
+CI proof that mode 1 is genuinely air-gapped rather than only documented.
+
+It carries two controls, because zero observations is what a correct run and a
+blind probe both look like — and the API's unconfigured startup legitimately
+records zero, since it dials Postgres on loopback and needs no DNS:
-## Air-gapped verification (planned gate)
+- a **canary** container wired with the identical network and `--dns` flags
+ that *must* be seen by the sinkhole;
+- a **red run** against an image that deliberately resolves a public name,
+ which the gate must fail on.
-Phase 1.4 continuation adds a CI job that runs a full investigation with network
-egress blocked and asserts success on the local-model path — proving mode 1 is
-genuinely air-gapped, not just documented.
+One limit, stated: a dial straight to a public IP literal asks no DNS, so it
+is *prevented* by the `--internal` network and statically checked by
+`check_default_egress.py`, but it is not *observed* by the sinkhole.
diff --git a/scripts/check_security_pack_links.py b/scripts/check_security_pack_links.py
new file mode 100644
index 000000000..f6d2ba98c
--- /dev/null
+++ b/scripts/check_security_pack_links.py
@@ -0,0 +1,333 @@
+#!/usr/bin/env python3
+"""Every claim in the security pack still points at something real.
+
+The pack (`docs/security/`) makes one promise: each statement names the file
+or the CI job that makes it true. That promise decays silently. A module is
+renamed, a workflow is deleted, a heading is reworded — and the pack goes on
+reading like a document somebody verified, because a markdown link that
+resolves to nothing looks exactly like one that resolves.
+
+This project has shipped the failure that motivates it. Four security
+documents described controls that did not exist in the tree: AES-256-GCM
+backup encryption where the script only gzipped, envelope encryption cited as
+the mitigation for a database dump while `EnvelopeCipher` had zero callers, an
+unbroken distributed trace with neither end of the Kafka spine instrumented,
+and per-tenant retention marked GATED by a test asserting only that the purge
+SQL parses. A link checker would not have caught all four — a link can resolve
+to a file whose contents do not support the sentence — but it catches the
+cheapest half, which is the half that rots fastest.
+
+What is checked
+---------------
+1. **Every relative link resolves.** A path to a module, a workflow, a
+ migration or a sibling page must exist on disk.
+2. **Every in-document and cross-document anchor resolves**, computed the way
+ GitHub computes heading slugs. A section renamed in one file leaves a dead
+ `#anchor` in the three pages that cited it, and nothing else notices.
+3. **Every gate the pack names exists**, matched on `scripts/<name>.py` and
+ `<workflow>.yml` wherever they appear in prose — including inside backticks,
+ which is how they are usually written and where a plain link checker cannot
+ see them.
+
+What is deliberately not checked
+--------------------------------
+External URLs. Fetching them here would make a required check depend on the
+network and on GitHub's rate limiter, which is how `fail: false` and
+`--accept 403,429` ended up in the docs link job and why eight wrong-org 404s
+survived it. The pack's external links are fetched by hand when they land;
+this gate is the deterministic, offline half.
+
+Usage::
+
+ python3 scripts/check_security_pack_links.py
+ python3 scripts/check_security_pack_links.py --self-test
+
+Exit codes: 0 clean, 1 findings, 2 the scan itself could not run.
+"""
+
+from __future__ import annotations
+
+import argparse
+import pathlib
+import re
+import sys
+from dataclasses import dataclass, field
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
+
+from gate_toolkit import SELF_TEST_FLAG, repo_root, self_test_main # noqa: E402
+
+PACK = "docs/security"
+
+#: Also covered, because they are the pack's two closest neighbours and are
+#: linked from it: the egress statement and the policy that points at it.
+ALSO = ("docs/trust/data-flows.md", "SECURITY.md")
+
+#: Gates the pack names **in order to say they do not exist**, each with the
+#: reason. A questionnaire that lists its gaps has to be able to name them.
+#:
+#: Bidirectional, like the hostname allow-list and for the same reason: an
+#: entry here is not a permanent licence. If the named script appears, this
+#: gate fails and demands the entry go — because the pack's sentence saying
+#: it is absent has just become false, and a document that understates a
+#: control is a document a reviewer has to re-verify by hand.
+KNOWN_ABSENT: dict[str, str] = {
+ "scripts/audit_compliance_claims.py": (
+ "docs/decisions/0002-compliance-claims.md asserts this gate exists and it never has. "
+ "The pack names it to record that, and docs/audit/REALITY_REPORT.md lists the same "
+ "finding. Delete this entry when the gate is built."
+ ),
+}
+
+_LINK = re.compile(r"\[[^\]]*\]\(([^)\s]+)\)")
+_HEADING = re.compile(r"^#{1,6}\s+(.*)$")
+#: A gate named in prose rather than linked. Both forms appear in the pack.
+_SCRIPT = re.compile(r"`?(scripts/[a-z0-9_]+\.py)`?")
+_WORKFLOW = re.compile(r"`([a-z0-9][a-z0-9-]*\.yml)`")
+
+
+@dataclass
+class Report:
+ findings: list[str] = field(default_factory=list)
+ files: int = 0
+ links: int = 0
+ anchors: int = 0
+ gates: int = 0
+
+
+def _slug(heading: str) -> str:
+ """GitHub's heading-to-anchor rule, as far as this pack needs it."""
+ text = re.sub(r"`([^`]*)`", r"\1", heading).strip().lower()
+ text = re.sub(r"[^\w\s-]", "", text)
+ return re.sub(r"\s+", "-", text).strip("-")
+
+
+def _anchors(path: pathlib.Path) -> set[str]:
+ out: set[str] = set()
+ for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
+ match = _HEADING.match(line)
+ if match:
+ out.add(_slug(match.group(1)))
+ return out
+
+
+def _exists_anywhere(root: pathlib.Path, name: str) -> bool:
+ """Whether a bare filename matches any file in the tree.
+
+ Cached per root because the pack names a handful of them and walking the
+ tree once beats walking it per name. `node_modules` and `.git` are
+ skipped: a name that only matches inside a dependency is not evidence
+ that this repository ships it.
+ """
+ cache = _BASENAMES.setdefault(root, set())
+ if not cache:
+ skip = {".git", "node_modules", ".venv", "__pycache__"}
+ for path in root.rglob("*"):
+ if any(part in skip for part in path.parts):
+ continue
+ if path.is_file():
+ cache.add(path.name)
+ return name in cache
+
+
+_BASENAMES: dict[pathlib.Path, set[str]] = {}
+
+
+def _documents(root: pathlib.Path) -> list[pathlib.Path]:
+ found = sorted((root / PACK).glob("*.md"))
+ for extra in ALSO:
+ candidate = root / extra
+ if candidate.is_file():
+ found.append(candidate)
+ return found
+
+
+def inspect(root: pathlib.Path) -> Report:
+ report = Report()
+ anchor_cache: dict[pathlib.Path, set[str]] = {}
+
+ for doc in _documents(root):
+ report.files += 1
+ rel = doc.relative_to(root).as_posix()
+ body = doc.read_text(encoding="utf-8", errors="replace")
+
+ for target in _LINK.findall(body):
+ if target.startswith(("http://", "https://", "mailto:")):
+ continue
+ report.links += 1
+ path_part, _, fragment = target.partition("#")
+
+ if path_part:
+ resolved = (doc.parent / path_part).resolve()
+ if not resolved.exists():
+ report.findings.append(f"{rel}: link to {target!r} resolves to nothing")
+ continue
+ else:
+ resolved = doc
+
+ if not fragment:
+ continue
+ report.anchors += 1
+ if resolved.suffix != ".md":
+ continue
+ if resolved not in anchor_cache:
+ anchor_cache[resolved] = _anchors(resolved)
+ if fragment not in anchor_cache[resolved]:
+ report.findings.append(f"{rel}: anchor {target!r} names no heading in {resolved.name}")
+
+ # Gates named in prose. A pack that cites a gate deleted last month
+ # is the same lie as one that cites a module deleted last month, and
+ # the citation is usually in backticks rather than in a link.
+ for script in set(_SCRIPT.findall(body)):
+ report.gates += 1
+ if script in KNOWN_ABSENT:
+ continue
+ if not (root / script).is_file():
+ report.findings.append(f"{rel}: names {script}, which does not exist")
+ for name in set(_WORKFLOW.findall(body)):
+ if (root / ".github" / "workflows" / name).is_file():
+ report.gates += 1
+ continue
+ # Not every backticked `*.yml` is a workflow claim — the pack
+ # names `docker-compose.yml` and several chart values files. A
+ # name that exists as a file *somewhere* is one of those; a name
+ # that exists nowhere is a workflow that has been renamed or
+ # deleted, which is the case worth failing on.
+ if _exists_anywhere(root, name):
+ continue
+ report.gates += 1
+ report.findings.append(f"{rel}: names the workflow {name}, which exists nowhere in the tree")
+
+ # The other direction. An exemption that has stopped being true is a
+ # document now understating a control, which is the quieter half of the
+ # same defect and the half nobody goes looking for.
+ for script, reason in sorted(KNOWN_ABSENT.items()):
+ if (root / script).is_file():
+ report.findings.append(
+ f"KNOWN_ABSENT lists {script} as not existing, and it now does. The pack says so in prose; "
+ f"correct the prose and delete the entry. Recorded reason: {reason}"
+ )
+
+ return report
+
+
+def _verdict(report: Report) -> int:
+ # A gate that passes while inspecting nothing launders the claim it is
+ # supposed to hold, so an empty scan is a hard error rather than a pass.
+ if report.files == 0 or report.links == 0:
+ print(
+ f"check_security_pack_links: read {report.files} file(s) and {report.links} link(s) — "
+ "refusing to report a pack with nothing in it as verified",
+ file=sys.stderr,
+ )
+ return 2
+ if report.findings:
+ print("check_security_pack_links: FAIL", file=sys.stderr)
+ for finding in report.findings:
+ print(f" {finding}", file=sys.stderr)
+ return 1
+ print(
+ f"check_security_pack_links: OK — {report.files} document(s); "
+ f"{report.links} relative link(s), {report.anchors} anchor(s) and "
+ f"{report.gates} named gate(s) all resolve."
+ )
+ return 0
+
+
+#: What a scratch copy needs for the pack's links to resolve. Not the whole
+#: repository: `detections/` alone is thousands of files, and a self-test slow
+#: enough to skip is a self-test nobody runs.
+#:
+#: The clean-copy case below is what keeps this list honest. If the pack grows
+#: a link into a tree that is not here, that case fails — so the list cannot
+#: silently fall behind and quietly turn every probe into a no-op.
+_SCRATCH_TREES = ("docs", "scripts", ".github", "services", "infra", "apps", "tests", "packages")
+_SCRATCH_FILES = ("SECURITY.md", "docker-compose.yml", "README.md", "CHANGELOG.md")
+_SCRATCH_IGNORE = ("node_modules", "__pycache__", ".venv", "dist", ".next", "build")
+
+
+def _scratch(root: pathlib.Path, base: pathlib.Path) -> None:
+ import shutil
+
+ ignore = shutil.ignore_patterns(*_SCRATCH_IGNORE)
+ for tree in _SCRATCH_TREES:
+ source = root / tree
+ if source.is_dir():
+ shutil.copytree(source, base / tree, ignore=ignore, symlinks=True, ignore_dangling_symlinks=True)
+ for name in _SCRATCH_FILES:
+ source = root / name
+ if source.is_file():
+ shutil.copy(source, base / name)
+
+
+def self_test() -> int:
+ import tempfile
+
+ root = repo_root()
+ extra: list[tuple[str, bool]] = [("the real pack passes", not inspect(root).findings)]
+
+ def probe(description: str, mutate) -> None: # noqa: ANN001
+ with tempfile.TemporaryDirectory(prefix="aisoc-pack-links-") as tmp:
+ base = pathlib.Path(tmp)
+ _scratch(root, base)
+ mutate(base)
+ extra.append((description, bool(inspect(base).findings)))
+
+ def break_link(base: pathlib.Path) -> None:
+ target = base / PACK / "README.md"
+ target.write_text(target.read_text() + "\n[dead](../../services/api/app/nope_does_not_exist.py)\n")
+
+ def break_anchor(base: pathlib.Path) -> None:
+ target = base / PACK / "README.md"
+ target.write_text(target.read_text() + "\n[dead](questionnaire.md#no-such-heading)\n")
+
+ def break_gate(base: pathlib.Path) -> None:
+ target = base / PACK / "README.md"
+ target.write_text(target.read_text() + "\nHeld by `scripts/check_not_a_real_gate.py`.\n")
+
+ def break_workflow(base: pathlib.Path) -> None:
+ target = base / PACK / "README.md"
+ target.write_text(target.read_text() + "\nRun by `not-a-real-workflow.yml`.\n")
+
+ def stale_exemption(base: pathlib.Path) -> None:
+ """The other direction: an exemption that has stopped being true."""
+ for script in KNOWN_ABSENT:
+ created = base / script
+ created.parent.mkdir(parents=True, exist_ok=True)
+ created.write_text("# the gate the pack says does not exist, now existing\n")
+
+ probe("detects a link to a file that does not exist", break_link)
+ probe("detects an anchor that names no heading", break_anchor)
+ probe("detects a named gate script that does not exist", break_gate)
+ probe("detects a named workflow that does not exist", break_workflow)
+ probe("detects a stale KNOWN_ABSENT entry whose script now exists", stale_exemption)
+
+ # The direction it must not fire in. This case does double duty: it proves
+ # the gate accepts a clean tree, and it proves `_SCRATCH_TREES` still
+ # covers everything the pack links into — without which every probe above
+ # would pass on a flood of unrelated findings and prove nothing.
+ with tempfile.TemporaryDirectory(prefix="aisoc-pack-links-ok-") as tmp:
+ base = pathlib.Path(tmp)
+ _scratch(root, base)
+ clean = inspect(base)
+ if clean.findings:
+ print(" the scratch copy is missing a tree the pack links into:", file=sys.stderr)
+ for finding in clean.findings[:10]:
+ print(f" {finding}", file=sys.stderr)
+ extra.append(("accepts an unmodified copy", not clean.findings))
+
+ return self_test_main(pathlib.Path(__file__).name, [], extra)
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--check", action="store_true", help="accepted for symmetry with the other gates")
+ parser.add_argument(SELF_TEST_FLAG, action="store_true", dest="self_test")
+ args = parser.parse_args()
+ if args.self_test:
+ return self_test()
+ return _verdict(inspect(repo_root()))
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())