Record access decisions, conversation creates and admin changes in the audit chain (Part B, #11) #53

Merged
amiryahaya merged 20 commits from feat/11b-decision-events into main 2026-10-23 16:30:07 +02:00
Owner

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

What this adds

Part B records, in the audit chain from Part A (#52), the events Part A deferred. Plan: docs/superpowers/plans/2026-10-23-audit-decision-events.md.

  • Access decisions. Enforcer::new takes a required AuditSink. RequestAccess::permits stays synchronous and tallies each decision by (resource kind, action, outcome); every protected route calls access.finish(result) before it builds a response, which writes one aggregated access.decision row per key in one transaction (AuditSink::record_all). Enforcer::resource/search_scope record inline. Permit rows carry returned_count, Deny rows decision_count; denials never carry a resource id; absent, foreign, forbidden and malformed ids each cost one write of the same shape. A sink failure on an authenticated request is the uniform 503 and nothing is served. Skip rules avoid double writes: upload decisions (registration/refusal rows), audit-route and conversation-create permits on success (their own rows), and a replayed upload writes one explicit permit row.
  • Correlation id. One id per request, minted in the Enforcer (not returned to clients); registration, refusal, decision and audit-read rows of a request share it. Admin routes mint their own.
  • Conversation create is audited in the same transaction as the INSERT, with the new conversation id (no marking, labels or title); an audit failure creates nothing.
  • Admin changes (group, invitation, approval, recovery approval, suspension, bootstrap) are mirrored into the chain in the same transaction as the change (kind admin.change, reason derived on the server, actor's organization). identity_events stays; new nullable identity_events.correlation_id (migration 0011) links the trails.
  • Migration 0010: closes the SQL code sets so they equal the Rust enums (a test fails if an enum variant has no SQL entry), adds the decision_count metadata key, and the audit reader now tolerates an unknown stored row (event: None, rendered unreadable) instead of failing the whole page.
  • Docs: docs/security/audit.md ("Access decision events", limits, deferrals) and the operations guides corrected (stale statements about audit and unmounted admin routes fixed).

Claims and limits (please read)

  • The chain is still a plain unkeyed hash, a synthetic-development placeholder (see #52). The database owner or a superuser can rewrite it; tail truncation is detectable only against an external checkpoint.
  • Not recorded (documented gaps): anonymous, bad-session and no-organization requests (no organization to chain under; recording to __system__ would let unauthenticated callers flood one global chain), session/policy-source failures, requests that make no decision (an empty list page, query-parsing 400s), admin read endpoints, passkey/login/registration/recovery-code events, and denied audit requests only where no organization is known.
  • Behavior changes with the sink down: denials and permitted 400/413 responses on audit routes become the uniform 503; conversation create, list and history fail closed; bootstrap fails (503/Unavailable) if the migration role does not own audit_append. With a working sink, no response bytes or headers change.
  • Rows are per (kind, action, outcome), not per decision; the over-cap export 413 writes two permit rows. returned_count counts permitted decisions (history counts the conversation plus each permitted message, including one the source check later withholds).
  • One write is deliberately swallowed: the Deny unavailable row for a request already answered 503 (loader or context failure).
  • Every authenticated protected request now takes the organization's chain lock and an extra pool connection; the identity advisory lock is held while an admin change waits for the audit lock. Throughput bound is an estimate, not measured. No rate limit, no retention (OD-08 open), no keyed MAC/anchoring (OD-04/ID-10), no dual control (ID-06).

Not in this PR

Producers for policy/marking/crypto/audit-config/feedback events (the event kinds exist), retention/pruning, keyed MAC/anchoring, dual control, rate limiting, a response-visible correlation id, recording of anonymous requests, and an end-to-end test that admin.change rows appear through the audit read/export API and that the admin route's correlation id reaches the audit row.

Verification (head bd1b0a0)

cargo fmt --check and cargo clippy --workspace --all-targets --locked -- -D warnings clean; cargo test --workspace --locked 181 passed, 0 failed. PostgreSQL suites (bash scripts/test-postgres.sh --local): I did not get one uninterrupted green local run on the final head. The first full run stopped in audit_decisions_postgres (3 of 15 tests failed in fixture setup at migrate(...); 15/15 twice standalone afterwards); a second full run passed 16 of 17 suites and failed 1 of 6 in revocation_postgres at the passkey login helper (6/6 on a later rerun). The implementers' per-round full runs on earlier heads were green. The local Docker Postgres holds ~2,000 leaked rag_test_* databases (a test that panics leaks its database), which slows setup and is probably the cause; CI is the check that matters. The coverage script was not run locally.

Known local flakes unrelated to this change: the Docker VM clock jitters ±100 ms against the host (registry created_at assertion now tolerates 5 s), passkey/webauthn helper tests, audit_postgres::twenty_concurrent_appends, and one unexplained admin_postgres 403 (likely mixed application/database clocks around valid_from).

Synthetic data only; no production, classified-deployment, assurance or PQC claim.

🤖 Generated with Claude Code

Refs #11 (Part B of two; does not close it, see "Not in this PR"). ## What this adds Part B records, in the audit chain from Part A (#52), the events Part A deferred. Plan: `docs/superpowers/plans/2026-10-23-audit-decision-events.md`. - **Access decisions.** `Enforcer::new` takes a required `AuditSink`. `RequestAccess::permits` stays synchronous and tallies each decision by (resource kind, action, outcome); every protected route calls `access.finish(result)` before it builds a response, which writes one aggregated `access.decision` row per key in one transaction (`AuditSink::record_all`). `Enforcer::resource`/`search_scope` record inline. Permit rows carry `returned_count`, Deny rows `decision_count`; denials never carry a resource id; absent, foreign, forbidden and malformed ids each cost one write of the same shape. A sink failure on an authenticated request is the uniform 503 and nothing is served. Skip rules avoid double writes: upload decisions (registration/refusal rows), audit-route and conversation-create permits on success (their own rows), and a replayed upload writes one explicit permit row. - **Correlation id.** One id per request, minted in the `Enforcer` (not returned to clients); registration, refusal, decision and audit-read rows of a request share it. Admin routes mint their own. - **Conversation create** is audited in the same transaction as the INSERT, with the new conversation id (no marking, labels or title); an audit failure creates nothing. - **Admin changes** (group, invitation, approval, recovery approval, suspension, bootstrap) are mirrored into the chain in the same transaction as the change (kind `admin.change`, reason derived on the server, actor's organization). `identity_events` stays; new nullable `identity_events.correlation_id` (migration 0011) links the trails. - **Migration 0010:** closes the SQL code sets so they equal the Rust enums (a test fails if an enum variant has no SQL entry), adds the `decision_count` metadata key, and the audit reader now tolerates an unknown stored row (`event: None`, rendered `unreadable`) instead of failing the whole page. - **Docs:** `docs/security/audit.md` ("Access decision events", limits, deferrals) and the operations guides corrected (stale statements about audit and unmounted admin routes fixed). ## Claims and limits (please read) - The chain is still a **plain unkeyed hash, a synthetic-development placeholder** (see #52). The database owner or a superuser can rewrite it; tail truncation is detectable only against an external checkpoint. - **Not recorded (documented gaps):** anonymous, bad-session and no-organization requests (no organization to chain under; recording to `__system__` would let unauthenticated callers flood one global chain), session/policy-source failures, requests that make no decision (an empty list page, query-parsing 400s), admin read endpoints, passkey/login/registration/recovery-code events, and denied audit requests only where no organization is known. - **Behavior changes with the sink down:** denials and permitted 400/413 responses on audit routes become the uniform 503; conversation create, list and history fail closed; bootstrap fails (503/Unavailable) if the migration role does not own `audit_append`. With a working sink, no response bytes or headers change. - Rows are per (kind, action, outcome), not per decision; the over-cap export 413 writes two permit rows. `returned_count` counts permitted decisions (history counts the conversation plus each permitted message, including one the source check later withholds). - One write is deliberately swallowed: the Deny `unavailable` row for a request already answered 503 (loader or context failure). - Every authenticated protected request now takes the organization's chain lock and an extra pool connection; the identity advisory lock is held while an admin change waits for the audit lock. Throughput bound is an estimate, not measured. No rate limit, no retention (OD-08 open), no keyed MAC/anchoring (OD-04/ID-10), no dual control (ID-06). ## Not in this PR Producers for policy/marking/crypto/audit-config/feedback events (the event kinds exist), retention/pruning, keyed MAC/anchoring, dual control, rate limiting, a response-visible correlation id, recording of anonymous requests, and an end-to-end test that `admin.change` rows appear through the audit read/export API and that the admin route's correlation id reaches the audit row. ## Verification (head `bd1b0a0`) `cargo fmt --check` and `cargo clippy --workspace --all-targets --locked -- -D warnings` clean; `cargo test --workspace --locked` 181 passed, 0 failed. PostgreSQL suites (`bash scripts/test-postgres.sh --local`): **I did not get one uninterrupted green local run on the final head.** The first full run stopped in `audit_decisions_postgres` (3 of 15 tests failed in fixture setup at `migrate(...)`; 15/15 twice standalone afterwards); a second full run passed 16 of 17 suites and failed 1 of 6 in `revocation_postgres` at the passkey login helper (6/6 on a later rerun). The implementers' per-round full runs on earlier heads were green. The local Docker Postgres holds ~2,000 leaked `rag_test_*` databases (a test that panics leaks its database), which slows setup and is probably the cause; CI is the check that matters. The coverage script was not run locally. Known local flakes unrelated to this change: the Docker VM clock jitters ±100 ms against the host (registry `created_at` assertion now tolerates 5 s), passkey/webauthn helper tests, `audit_postgres::twenty_concurrent_appends`, and one unexplained `admin_postgres` 403 (likely mixed application/database clocks around `valid_from`). Synthetic data only; no production, classified-deployment, assurance or PQC claim. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Migration 0010 replaces audit_append/audit_read in place: explicit IN lists for event_type,
decision, action, resource_kind, denial_code and change_reason (a test compares them with the
Rust enums) and the decision_count metadata key. AuditRecord.event is Option: unknown codes
no longer fail the page; the API renders such a row as seq, row_hash and "unreadable".

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>
Enforcer::new now takes the chained AuditSink (required, every call site
wired). Enforcer::resource and search_scope write one access.decision row
before returning: a permit names the document, an absent resource is a
denial with no id exactly like a forbidden one, a failed write is the
uniform 503, and a loader failure's best-effort unavailable row is the only
write whose failure is ignored. AuditSink::record_all writes many events;
the PostgreSQL sink does it in one transaction.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
RequestAccess::finish writes the request's tallied decisions as one
access.decision row per (kind, action, outcome) in one transaction, under
the subject's organization and the request's correlation id, before the
answer leaves; a failed write replaces the result (success or refusal) with
the route's uniform 503. Keys their own event records are skipped (upload,
permitted audit reads, permitted conversation create). deny() records a
pre-decision denial (malformed or absent target) once; note_target() names
the one conversation of a history permit. Unflushed decisions log a
payload-free decisions_unflushed line on drop, and the route inventory
fails for a file that begins without finishing. Conversation, document and
audit routes are wired; the list/history/context markers are removed.

audit_api_postgres expectations are rewritten for the new denial rows;
audit_decisions_postgres is new and registered in both scripts.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
A permitted audit call or conversation create that ends in a 400, 413 or
503 has no audit.* or create row, so its permits are now written by
finish; the skip applies only to an answered (Ok) result. With the sink
down an over-cap export is therefore the uniform 503. Inline resource and
search rows use the decision context's request id as correlation id, so a
SearchGrant joins its row. The route inventory ignores comments.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Group creation, invitation, account approval, recovery approval, account suspension and the
operator bootstrap append one admin.change / changed row with record_in, after the identity
event and before commit, in the actor's organization chain. A failed append returns
IdentityError::Unavailable and rolls the identity change back. The row carries the actor, the
policy version the IdentityService was built with, a correlation id and a server-derived
reason (provisioning, correction, revocation); no target, free text, address or account id.
Migration 0011 adds identity_events.correlation_id to link the two trails. Repository methods
and IdentityService wrappers take the correlation id; admin routes mint it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The needles were the document-upload payload's ALPHA and mission-1, not the member's real
marking, so the check could pass vacuously. They now come from the stored conversations'
security_attributes (read through the admin pool), must be non-empty, and none may appear in
any column or metadata of the create rows.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Creating a member now writes admin.change rows. The audit API tests assert on the chain from
their own first event, so they create members before seeding and drop the setup rows while the
chain holds nothing else.

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>
docs(audit): replayed upload permit row, no-decision requests, identity status corrections (#11)
All checks were successful
CI / Web checks (push) Successful in 43s
CI / Web checks (pull_request) Successful in 1m7s
CI / Rust checks (pull_request) Successful in 17m53s
CI / Rust checks (push) Successful in 36m24s
bd1b0a04fd
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Sign in to join this conversation.
No description provided.