There is a difference between a log and an audit trail, and it is not about format.

A log exists for debugging: lose a line and nothing happens. An audit trail exists as evidence: it answers the question of who accessed what and when, with legal consequences attached. And evidence that can be rewritten is not evidence.

This article is about what it takes for that table to be evidence rather than a list of good intentions. I built it on PostgreSQL 18.4 and attacked it from the inside, with the permissions a normal development team holds. It fell three times.

Why updated_at is not an audit trail

The usual starting point: a business table with updated_at, and perhaps updated_by. That tells you the current state and who left it that way. It tells you nothing about the sequence.

With a mutable table you cannot answer any of this: who read it without modifying it, how many times, in what order it passed through three intermediate states, or what was there before the last write. And read access — which leaves no trace at all in the mutable model — is precisely what matters most when the data is sensitive. Viewing somebody else’s medical record changes not a single row.

The second approach, which is a serious attempt, is the mirror table with triggers: every UPDATE on the business table inserts a row into its history table. Better, and still insufficient on two counts. It only captures writes, so reads still go unrecorded. And the history table is an ordinary table: it can be modified exactly like the original.

Which leads to the design I want to argue for: a dedicated, append-only event log where the unit is the event and not the state change.

CREATE TABLE audit_events (
  id          bigserial PRIMARY KEY,
  occurred_at timestamptz NOT NULL DEFAULT clock_timestamp(),
  tenant_id   uuid NOT NULL,
  actor_id    uuid NOT NULL,
  action      text NOT NULL,
  subject     text NOT NULL,
  payload     jsonb NOT NULL DEFAULT '{}'::jsonb
);

One small detail with consequences: clock_timestamp() rather than now(). now() returns the transaction start time, so ten events inserted in the same transaction share an identical timestamp and their real order is lost. clock_timestamp() advances within the transaction.

Attack 1: the grants

The first level is obvious and correct: the application role can only insert.

GRANT INSERT, SELECT ON audit_events TO app_runtime;

And it works:

INSERT   -> INSERT 5
UPDATE   -> ERROR: permission denied for table audit_events
DELETE   -> ERROR: permission denied for table audit_events
TRUNCATE -> ERROR: permission denied for table audit_events

Now the same attempt as the table’s owner, which is the role that runs migrations and usually the one sitting in the deployment credentials:

UPDATE   -> UPDATE 1
value now: rewritten

Rewritten. No resistance.

This has the same shape as the Row Level Security finding from the first article on this blog: grants protect against the application role, and the table owner lives above them. The practical consequence is the same too: the application must connect as a role that is not the owner, and the owner role belongs in a separate secret used only by the migration process.

Attack 2: the trigger

The natural next step is a trigger rejecting any mutation:

CREATE FUNCTION deny_mutation() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN RAISE EXCEPTION 'audit_events is append-only'; END $$;

CREATE TRIGGER no_update BEFORE UPDATE OR DELETE ON audit_events
  FOR EACH ROW EXECUTE FUNCTION deny_mutation();
CREATE TRIGGER no_truncate BEFORE TRUNCATE ON audit_events
  FOR EACH STATEMENT EXECUTE FUNCTION deny_mutation();

And now it does stop the owner:

UPDATE   -> ERROR: audit_events is append-only
DELETE   -> ERROR: audit_events is append-only
TRUNCATE -> ERROR: audit_events is append-only

For about twenty seconds, which is how long it took me to write this:

ALTER TABLE audit_events DISABLE TRIGGER no_update;
UPDATE audit_events SET action = 'bypassed' WHERE id = 1;
ALTER TABLE audit_events ENABLE TRIGGER no_update;
UPDATE 1
value now: bypassed

The first two statements are enough to alter the record; the third only puts the trigger back so nobody notices.

The owner of a table can disable its own triggers. That is not a PostgreSQL flaw: it is exactly what ownership means.

I also tried setting session_replication_role = replica, which disables every trigger for the session without touching the table. There is good news there: the owner role cannot change that parameter — permission denied to set parameter — you need to be superuser. But a superuser does it and the trigger never fires.

The honest conclusion from the second attack: the trigger is not a security mechanism, it is an accident mechanism. It prevents the UPDATE without a WHERE on a Tuesday afternoon. It prevents nobody who intends to modify the record.

Attack 3: the hash chain

This is where most designs declare themselves secure. Each row stores the previous row’s hash in prev_hash, and its own hash covers every one of its fields plus that link:

CREATE FUNCTION event_hash(e audit_events) RETURNS bytea
LANGUAGE sql IMMUTABLE AS $$
  SELECT sha256(convert_to(jsonb_build_array(
           e.id, e.tenant_id, e.actor_id, e.action, e.subject,
           e.occurred_at AT TIME ZONE 'UTC', e.payload, encode(e.prev_hash, 'hex')
         )::text, 'UTF8'))
$$;

Verification checks two things per row: that its hash matches its fields, and that its prev_hash is the hash of the previous row by id (for the first row, the genesis value).

Both are needed, and I know because the first version of this artifact had neither. It hashed four fields concatenated with no separator and checked each row against its own prev_hash. When I re-verified it on PostgreSQL 18.4, it caught one tampering out of five: changing occurred_at, changing the payload, deleting a row, or moving the boundary between two fields ('read' || 'patient:3' is the same bytes as 'readpatient:' || '3') all came back broken: 0. A chain that does not cover every field and does not check the link between rows is decoration.

With the corrected version, over five fixed events, every tampering that leaves the hashes alone shows up:

untampered                    -> rows: 5 · broken: 0
row 3, subject changed        -> rows: 5 · broken: 1
row 3, occurred_at changed    -> rows: 5 · broken: 1
row 3, payload changed        -> rows: 5 · broken: 1
row 3, field boundary moved   -> rows: 5 · broken: 1
row 3 deleted                 -> rows: 4 · broken: 1

The problem is what somebody with write access does next. Recomputing the whole chain is a nine-line function:

row 3, action -> hidden       -> rows: 5 · broken: 1
... and chain recomputed      -> rows: 5 · broken: 0

id | action
 1 | read
 2 | read
 3 | hidden      <- altered
 4 | export
 5 | read

Chain intact. Record altered. Internal verification reports everything is fine.

And this is not a defect of my implementation: it is a property of any hash chain whose verifier lives inside the same system the attacker controls. The chain proves internal consistency, and internal consistency can be manufactured.

What does work: the external anchor

The only thing that turns the chain into evidence is publishing its head beyond the reach of whoever can rewrite the table. A daily email to a mailbox the database team does not control, a record with another provider, a signature from a timestamping service. The mechanism matters less than the property: whoever tampers with the log must not be able to tamper with the anchor.

The same exercise, with an anchor:

head published (id 5): 005dd1882902e906e74ec897…
(row 3 is altered and the entire chain is recomputed)
internal verification -> rows: 5 · broken: 0
head now:              c622092651023532400096e6…
-> the hash at id 5 is no longer the published one: DETECTED

Internal verification still reports full integrity. Comparing against the anchor dismantles it. The same happens if instead of altering row 3 I delete it and recompute: rows: 4 · broken: 0, anchor differs.

One detail of how the comparison works: not the current head against the published one, since every legitimate event afterwards changes it, but the hash stored today at the anchored id against the one that was published.

And here is the part I find most useful in all of this, because it changes what can be promised: an anchor does not prevent tampering, it makes tampering detectable. Those are different things and worth not conflating in an audit. Yesterday’s published head bounds the damage: because the hash covers every field and the link to the previous row, altering or deleting any row up to the anchored id either breaks the chain, if it is not recomputed, or changes the hash at the anchored id, if it is. Anything after it, until the next publication, is not covered: I alter and recompute a row written after the anchor and verification answers rows: 6 · broken: 0, anchor intact. Nothing detects it.

From which it follows that anchor frequency is a design decision with a direct consequence: the window of undetectable tampering is exactly the interval between two publications.

3 of 3internal defenses defeated by the table owner
2 statementsthe cost of disabling the trigger and altering the record
1 anchorwhat makes detectable what cannot be prevented

Erasure versus immutability

The legal objection, which always arrives: an immutable record collides head-on with the right to erasure. If I cannot delete a row, how do I satisfy a deletion request?

The answer is not to delete the row: it is to destroy the ability to read it. Crypto-shredding: encrypt the sensitive content with one key per subject and, when it has to be erased, destroy that key:

def write_event(subject: str, payload: str) -> dict:
    nonce = os.urandom(12)
    ct = AESGCM(key_for(subject)).encrypt(nonce, payload.encode(), subject.encode())
    return {"subject": subject, "nonce": nonce, "ct": ct}

And the erasure request is one line: destroy that subject’s key.

before erasure:
  patient:1 -> diagnosis viewed by dr. X
  patient:2 -> record exported

after destroying patient:1's key:
  patient:1 -> key destroyed: the event exists, its content does not
  patient:2 -> record exported

rows still in the log: 2
hash chain recomputed from the rows: head identical before and after erasure

The script recomputes a hash chain over what is actually stored (the ciphertext, not the plaintext) before and after destroying the key, and the head is the same. No row was deleted or modified, so the chain and the anchor still hold. What disappeared is one subject’s content.

And that forces a specific design of the event: the payload is encrypted per subject, and the fields you need to query the log stay in the clear. tenant_id, actor_id, action, subject and the timestamp remain readable; the sensitive detail goes inside the encrypted envelope. After erasure you can still prove an access happened, who performed it and when, without being able to say to exactly which data.

What not to record

The design mistake I have seen most often, and the easiest one to make with good intentions: putting the data into the event “for context”. The result is that the audit log becomes the largest store of sensitive data in the system, without the original table’s protections, without a retention policy, and with laxer read permissions because “it’s only the log”.

My rule: the event records references and facts, not contents. subject: patient:12345 yes; the diagnosis, no. action: export yes; the exported CSV, no. If an incident investigation needs the content, the place to reconstruct it is the business table and its history, not the access log.

Querying it without killing the database

An audit log grows fast and only gets read when somebody asks. I loaded 2 million events through the real table, with the trigger computing the hash chain row by row: 10 tenants, 200 actors and 50,000 subjects drawn independently, from a fixed seed. The table takes 411 MB with its payload and its two hash columns. I measured the query an investigation actually runs: who accessed this subject, in this tenant. Five runs of each, in two sessions:

without an index:  40-45 ms         ·  52,632 buffers (about 37,000 from outside shared_buffers)
with an index:     0.005-0.058 ms   ·  Index Scan, 1 search

With the index, the slow run is always the first one, with the pages not yet cached; the rest stay between 0.005 and 0.020 ms. For comparison, a SELECT 1 costs between 0.001 and 0.004 ms. Somewhere between 700 and 9,000 times faster depending on the cache: the range is wide, the order of magnitude is not in question. The index is (tenant_id, subject, occurred_at DESC), which serves both the filter and the ordering.

Its cost is not negligible, and this is the number to bring to the conversation:

table: 411 MB · index: 113 MB

The index weighs 27% of the table, on top of the 43 MB of the primary key. On a log that grows indefinitely, that is a budget decision rather than a detail. Which is why the alternative earns its place: a materialized projection per subject, covering what gets asked most.

projection: 63 MB with its primary key · 490,885 rows · query in 0.004-0.037 ms

A little over half the index’s size, with the same order of response time for the frequent question. The difference is that the projection answers “how many accesses there were and when the last one was”, whereas the index answers anything. My split: projection for the dashboard, the index only if detailed investigations are genuinely frequent, and for everything else a slow, accepted query against an archived partition.

All of the above measured on PostgreSQL 18.4 (128 MB of shared_buffers, parallel sequential scan with 2 workers), with cryptography 48.0.0 and Python 3.12.10.

When not to

If your system holds no third-party data and nobody will ever ask you for an access trail, this is permanent infrastructure for a requirement that does not exist. A well-structured application log will do.

And if what you need is debugging rather than auditing, likewise: an append-only log with a hash chain and an external anchor is awkward to operate precisely because it cannot be corrected. You cannot fix the events a bug wrote badly. That rigidity is the feature, and it only feels worth paying for when the table is evidence.

Closing

Of the three internal defenses typically built over an audit log, none survives whoever owns the table. Grants do not apply to them, they disable the trigger themselves, and they recompute the hash chain.

That does not make the three useless: it means they protect against the accident and not the deliberate act, and that we should stop selling them as the second. The only thing that changes the nature of the problem is publishing the chain’s head somewhere whoever tampers with the log cannot reach.

And the test for whether you have a log or a piece of evidence is not reading the schema. It is this question:

If somebody on your team altered an access record from six months ago, what mechanism would detect it, and is that mechanism beyond their reach?

If the answer to the second half is no, you have a very well-built log.