Expand description
Audit log (feature audit): who changed what, appended inside the caller’s
transaction and hash-chained so that edits to stored records are detectable.
AuditLogis the capability (itslayerprovides it).AuditLog::append/append/recordinsert oneAuditRecord{actor, tenant, action, entity, before, after, at}through the caller’sSqlTransaction, so the record commits or rolls back with the change it describes.- The actor and tenant are an
AuditContextvalue: explicit, or a capability of the environment (set per request, e.g. from the authenticated principal). This crate does not depend on any auth crate. - Every tenant has its own chain (records without a tenant share the chain
""). Recordnstoreshash = sha256(prev_hash ‖ canonical(record))withprev_hashthe hash of recordn - 1(GENESIS_HASHfor the first), and the chain’s head row holds the last(seq, hash). AuditLog::verify_chain_on/verify_chainstream a chain in order and report the first broken link (BrokenLink: the record, what was expected and what is stored).
§Concurrency
An append first upserts the chain’s head row (INSERT … ON CONFLICT DO UPDATE … RETURNING),
which row-locks it until the caller’s transaction ends, then reads the previous (seq, hash)
from it, inserts the record and moves the head. Concurrent appends to one chain therefore
queue on that row lock and each links to the committed head before it: the chain never forks
(UNIQUE (chain, seq) backs this up). Appends to different tenants do not wait for each
other. A rolled-back transaction releases the lock and leaves the head untouched.
Append in READ COMMITTED transactions (the PostgreSQL default). Under REPEATABLE READ or
SERIALIZABLE, an append racing another one fails with a serialization failure (SQLSTATE
40001) instead of waiting; rerun it with
retry_serialization_failures.
§Canonical form
The hashed bytes are prev_hash (32 bytes) followed by the record as JSON with object keys
sorted at every level and no whitespace: {"action","actor","after","at","before","entity", "seq","tenant"}, where at is microseconds since the Unix epoch (what TIMESTAMPTZ stores)
and a missing before / after / tenant is null. at is the database’s now() (the
transaction’s start time). The record id is not hashed (the database assigns it).
§What the chain detects
An edited record (its hash no longer matches), a removed or inserted record (the next
record’s prev_hash or seq no longer follows), and records removed from the end (the chain
no longer reaches its head row). Someone who can rewrite the whole chain and its head can
hide that: anchor ChainReport::head outside the database (a log line, a signed
checkpoint) to detect it.
§Schema
MIGRATIONS holds the PostgreSQL migration (migrations/audit/ in this crate, tables
audit_log and audit_log_head); with feature migrate, migrator() runs it with its own
tracking table. AuditLog::with_table uses another table (create it from a copy of the
migration).
use std::sync::Arc;
use id_effect::Effect;
use id_effect_sql::audit::{AuditContext, AuditEntry, AuditLog};
use id_effect_sql::{SqlClient, SqlError, params, with_transaction};
/// Renames invoice 7 and records it, in one transaction.
fn rename(db: Arc<dyn SqlClient>, log: AuditLog, who: AuditContext) -> Effect<(), SqlError> {
with_transaction(db, move |tx| {
let entry = AuditEntry::new("invoice.rename", "invoice:7")
.with_before(serde_json::json!({ "name": "draft" }))
.with_after(serde_json::json!({ "name": "final" }));
tx.execute("UPDATE invoices SET name = $1 WHERE id = $2", ¶ms!["final", 7i64])
.flat_map(move |_| log.append(&tx, &who, entry))
.map(|_record| ())
})
}Structs§
- Audit
Context - Who acts, and for which tenant: the
actorandtenantof the records appended with it. - Audit
Entry - What happened: an
actionon anentity, with the entity’s statebeforeandafterit (JSON;Nonefor a creation’sbeforeor a deletion’safter). - Audit
Log - Capability: where audit records go (
DEFAULT_TABLEunlesswith_table). - Audit
Record - One stored audit record (a row of the audit table).
- Broken
Link - The first broken link of a chain.
- Chain
Report - The outcome of verifying one chain.
Enums§
- Break
Kind - How a chain is broken (
BrokenLink::kind).
Constants§
- DEFAULT_
TABLE - The default audit table (its chain heads are in
audit_log_head). - GENESIS_
HASH - The
prev_hashof a chain’s first record. - MIGRATIONS
- The schema as
(file name, script)migration pairs (0001_audit_log.up.sql/.down.sql), in the namingmigrate::Migrator::from_filesreads. - MIGRATIONS_
TABLE - The tracking table of
migrator()(featuremigrate), so the audit migration’s version never collides with the application’s own.
Functions§
- append
AuditLog::appendwith theAuditLogof the environment.- migrator
- A
MigratorforMIGRATIONS, tracked inMIGRATIONS_TABLE: run it next to the application’s migrator (migrator().run_on(client)). - record
AuditLog::appendwith theAuditLog, theAuditContextand the transaction (transaction_layer) of the environment.- verify_
chain AuditLog::verify_chain_onwith theAuditLogand theSqlClientServiceof the environment.
Type Aliases§
- Audit
LogEnv - The minimal typed environment holding only
AuditLog.