Skip to main content

Module audit

Module audit 

Source
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.

  • AuditLog is the capability (its layer provides it). AuditLog::append / append / record insert one AuditRecord {actor, tenant, action, entity, before, after, at} through the caller’s SqlTransaction, so the record commits or rolls back with the change it describes.
  • The actor and tenant are an AuditContext value: 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 ""). Record n stores hash = sha256(prev_hash ‖ canonical(record)) with prev_hash the hash of record n - 1 (GENESIS_HASH for the first), and the chain’s head row holds the last (seq, hash).
  • AuditLog::verify_chain_on / verify_chain stream 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", &params!["final", 7i64])
      .flat_map(move |_| log.append(&tx, &who, entry))
      .map(|_record| ())
  })
}

Structs§

AuditContext
Who acts, and for which tenant: the actor and tenant of the records appended with it.
AuditEntry
What happened: an action on an entity, with the entity’s state before and after it (JSON; None for a creation’s before or a deletion’s after).
AuditLog
Capability: where audit records go (DEFAULT_TABLE unless with_table).
AuditRecord
One stored audit record (a row of the audit table).
BrokenLink
The first broken link of a chain.
ChainReport
The outcome of verifying one chain.

Enums§

BreakKind
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_hash of a chain’s first record.
MIGRATIONS
The schema as (file name, script) migration pairs (0001_audit_log.up.sql / .down.sql), in the naming migrate::Migrator::from_files reads.
MIGRATIONS_TABLE
The tracking table of migrator() (feature migrate), so the audit migration’s version never collides with the application’s own.

Functions§

append
AuditLog::append with the AuditLog of the environment.
migrator
A Migrator for MIGRATIONS, tracked in MIGRATIONS_TABLE: run it next to the application’s migrator (migrator().run_on(client)).
record
AuditLog::append with the AuditLog, the AuditContext and the transaction (transaction_layer) of the environment.
verify_chain
AuditLog::verify_chain_on with the AuditLog and the SqlClientService of the environment.

Type Aliases§

AuditLogEnv
The minimal typed environment holding only AuditLog.