Add the tamper-evident audit chain, sink and authorized reader (Part A, #11) #52

Merged
amiryahaya merged 17 commits from feat/11-audit-trail into main 2026-10-23 11:57:07 +02:00
Owner

Refs #11 (Part A of two; does not close it, see "Not in this PR").

What this adds

  • crates/audit: typed, closed audit events and the AuditSink / AuditReader ports. No free-text field exists, so content cannot be put in by construction; denial events cannot carry a resource id; config-change events require actor and reason.
  • Migration 0009: a per-organization SHA-256 hash chain computed in PostgreSQL (audit_append, audit_verify, audit_checkpoint, audit_read; built-in sha256() under a per-organization advisory lock; database clock authoritative). rag_app loses every table privilege on audit_events and can only execute audit_append; a statement-level trigger (ENABLE ALWAYS) refuses UPDATE/DELETE/TRUNCATE; the startup guard rejects any extra privilege.
  • Document writers: registration writes its audit row through the sink in the same transaction; a refusal whose audit write fails now returns 503 (it was silently swallowed). Refusal reasons moved to the denial_code column; stored event_type/decision spellings are unchanged.
  • Reader: a separate rag_audit_reader role with its own startup guard and AUDIT_READER_DATABASE_URL; routes GET /api/v1/audit/events, /verify, /export authorized through the Enforcer with ReadAudit (and Export), never is_admin. Reads and exports are themselves audited before answering. Export is capped at 10,000 rows (413) and fails closed (503) if it cannot deliver the head it read. No development account gets either action by default.
  • Docs: new docs/security/audit.md (event fields, the chain and its limits, outage policy, reader model, "Deferred and open"); postgres.md, documents.md, authorization.md, conversations.md corrected and cross-linked. Plan: docs/superpowers/plans/2026-10-23-audit-trail-chain.md.

Claims and limits (please read)

  • The chain is a plain unkeyed hash, a synthetic-development placeholder. It detects alteration, mid-chain deletion and reordering that does not recompute the whole chain; tail truncation and full recomputation are detectable only against an externally held checkpoint. The database owner or a superuser can disable or drop the trigger and rewrite everything. No keyed MAC, anchoring, approved integrity profile, retention rule or dual control exists (OD-04, OD-08, ID-06, ID-10 are open). No production, classified-deployment or PQC claim.
  • rag_audit_reader can read any scope; per-organization isolation is enforced in the API layer (scope comes from the verified subject), not by the database.
  • Every authenticated refused document upload now writes an audit row and takes the organization's chain lock; rows are never pruned and there is no rate limit.
  • One stored row the reader cannot parse makes events/export return 503 for that organization (verify still works); a Part B design input.
  • The outage log test captures ERROR-level lines at the sink only, not an HTTP route's logs. The two audit PostgreSQL binaries each hold their own role lock and alter the cluster-global reader role, so they must not run as parallel test binaries.

Not in this PR (Part B / later)

Access-decision events from the Enforcer, the conversation AUDIT(#11) markers, admin events, a request-level correlation id (audit rows currently get a fresh one), recording of denied audit requests and of the early 404 exits in the document routes, producers for policy/marking/crypto/audit-config/feedback events (the kinds exist), retention/pruning, keyed MAC/anchoring.

Verification (head 6573933)

cargo fmt --check and cargo clippy --workspace --all-targets --locked -- -D warnings clean; cargo test --workspace --locked 161 passed, 0 failed; bash scripts/test-postgres.sh --local exits 0 with every suite green, including audit_postgres (20), audit_reader_postgres (27), audit_api_postgres (8). The coverage script was not run locally; CI will run it (new suites registered).

Known flakes, unrelated to this change: documents_registry_postgres::active_attributes_hides_quarantined_and_returns_latest_active failed once (the database container's clock reads ~150 ms ahead of the host and the test compares the two; it passed on reruns and on main), and a passkey login helper failed intermittently in three suites only while overlapping background runs held the cluster; the clean run did not reproduce it.

Synthetic data only.

🤖 Generated with Claude Code

Refs #11 (Part A of two; does not close it, see "Not in this PR"). ## What this adds - **`crates/audit`:** typed, closed audit events and the `AuditSink` / `AuditReader` ports. No free-text field exists, so content cannot be put in by construction; denial events cannot carry a resource id; config-change events require actor and reason. - **Migration 0009:** a per-organization SHA-256 hash chain computed in PostgreSQL (`audit_append`, `audit_verify`, `audit_checkpoint`, `audit_read`; built-in `sha256()` under a per-organization advisory lock; database clock authoritative). `rag_app` loses every table privilege on `audit_events` and can only execute `audit_append`; a statement-level trigger (`ENABLE ALWAYS`) refuses UPDATE/DELETE/TRUNCATE; the startup guard rejects any extra privilege. - **Document writers:** registration writes its audit row through the sink in the same transaction; a refusal whose audit write fails now returns 503 (it was silently swallowed). Refusal reasons moved to the `denial_code` column; stored `event_type`/`decision` spellings are unchanged. - **Reader:** a separate `rag_audit_reader` role with its own startup guard and `AUDIT_READER_DATABASE_URL`; routes `GET /api/v1/audit/events`, `/verify`, `/export` authorized through the `Enforcer` with `ReadAudit` (and `Export`), never `is_admin`. Reads and exports are themselves audited before answering. Export is capped at 10,000 rows (413) and fails closed (503) if it cannot deliver the head it read. No development account gets either action by default. - **Docs:** new `docs/security/audit.md` (event fields, the chain and its limits, outage policy, reader model, "Deferred and open"); `postgres.md`, `documents.md`, `authorization.md`, `conversations.md` corrected and cross-linked. Plan: `docs/superpowers/plans/2026-10-23-audit-trail-chain.md`. ## Claims and limits (please read) - The chain is a **plain unkeyed hash, a synthetic-development placeholder**. It detects alteration, mid-chain deletion and reordering that does not recompute the whole chain; tail truncation and full recomputation are detectable only against an externally held checkpoint. The database owner or a superuser can disable or drop the trigger and rewrite everything. No keyed MAC, anchoring, approved integrity profile, retention rule or dual control exists (OD-04, OD-08, ID-06, ID-10 are open). No production, classified-deployment or PQC claim. - `rag_audit_reader` can read any scope; per-organization isolation is enforced in the API layer (scope comes from the verified subject), not by the database. - Every authenticated refused document upload now writes an audit row and takes the organization's chain lock; rows are never pruned and there is no rate limit. - One stored row the reader cannot parse makes `events`/`export` return 503 for that organization (verify still works); a Part B design input. - The outage log test captures ERROR-level lines at the sink only, not an HTTP route's logs. The two audit PostgreSQL binaries each hold their own role lock and alter the cluster-global reader role, so they must not run as parallel test binaries. ## Not in this PR (Part B / later) Access-decision events from the `Enforcer`, the conversation `AUDIT(#11)` markers, admin events, a request-level correlation id (audit rows currently get a fresh one), recording of denied audit requests and of the early 404 exits in the document routes, producers for policy/marking/crypto/audit-config/feedback events (the kinds exist), retention/pruning, keyed MAC/anchoring. ## Verification (head `6573933`) `cargo fmt --check` and `cargo clippy --workspace --all-targets --locked -- -D warnings` clean; `cargo test --workspace --locked` 161 passed, 0 failed; `bash scripts/test-postgres.sh --local` exits 0 with every suite green, including `audit_postgres` (20), `audit_reader_postgres` (27), `audit_api_postgres` (8). The coverage script was not run locally; CI will run it (new suites registered). Known flakes, unrelated to this change: `documents_registry_postgres::active_attributes_hides_quarantined_and_returns_latest_active` failed once (the database container's clock reads ~150 ms ahead of the host and the test compares the two; it passed on reruns and on `main`), and a passkey login helper failed intermittently in three suites only while overlapping background runs held the cluster; the clean run did not reproduce it. Synthetic data only. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Migration 0009 adds per-scope hash-chain columns to audit_events and the
SECURITY DEFINER functions audit_append (the only write path; sha256 chain
under a per-scope advisory lock, clock_timestamp() for occurred_at),
audit_verify, audit_checkpoint and audit_read (capped at 500 rows). A
statement trigger refuses UPDATE/DELETE/TRUNCATE for every role, the owner
included. rag_app loses every privilege on audit_events and may execute
only audit_append; the new NOLOGIN rag_audit_reader role may execute only
the read/verify/checkpoint functions. The startup guard rejects any
audit_events privilege and EXECUTE on any other audit function. Legacy rows
keep NULL chain columns and stay outside the chain.

The harness learns rag_audit_reader; the rollback test in
documents_registry_postgres disables the append-only trigger on its
disposable database's admin connection for its DELETE cleanup.

Red by design until Task 4 moves the document writers to audit_append
(both suites go fully green with only the direct INSERT re-granted):
- documents_registry_postgres: 12 of 14 fail (direct INSERT -> 42501)
- documents_api_postgres: 17 of 18 fail (same cause)
All other PostgreSQL suites, including the new audit_postgres, pass.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
ResourceKind::Audit (group denied like conversations), RequestAccess::audit_resource
(lowest-ranked label, own organization), three Enforced routes gated by read_audit
(+ export), each call audited through the chained sink before answering, mounted only
with identity and AUDIT_READER_DATABASE_URL. No development account is granted the
audit actions by default.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Exports above EXPORT_MAX_ROWS (10,000) answer 413 before reading rows or writing
audit.export; an export whose rows do not end at the head it read is the uniform 503;
an organization named like the system scope is never a caller's scope (404). Docs
updated.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
docs(audit): trigger wording, identifier rules, disclosures and stale conversations note (#11)
Some checks failed
CI / Web checks (push) Successful in 44s
CI / Web checks (pull_request) Successful in 59s
CI / Rust checks (push) Successful in 14m56s
CI / Rust checks (pull_request) Failing after 25m28s
6573933dee
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
ci: give the Rust job 40 minutes (#11)
All checks were successful
CI / Web checks (pull_request) Successful in 45s
CI / Web checks (push) Successful in 1m43s
CI / Rust checks (pull_request) Successful in 17m13s
CI / Rust checks (push) Successful in 26m22s
9721b78000
The pull_request run of 6573933 was killed at the 25-minute limit while
every test had passed: the push and pull_request runs of one commit share a
runner and the PostgreSQL suites run twice (plain, then instrumented).
A lone run takes about 15 minutes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Sign in to join this conversation.
No description provided.