How-To Guide

How to Implement Audit Trails for Compliance

Build an audit trail: record who did what and when, make it append-only and tamper-evident, and retain and query it for compliance.

On this page

  1. Introduction
  2. Record the who, what, and when for every action
  3. Make the store append-only
  4. Make it tamper-evident with a hash chain
  5. Retain for the period and query for the request
  6. Test the record, the append-only property, and the chain
  7. Common pitfalls
  8. Conclusion

Introduction

An audit trail is the record of who did what, when, and to which target, for the security-relevant actions in a system. It is not a debugging log: it must be accurate, retained for a compliance period, and tamper-evident, because it may be used to investigate an incident or to prove compliance. A trail that the application can edit is not evidence, and a trail with gaps does not answer the auditor’s question.

This tutorial covers recording the who, what, and when, making the store append-only, making it tamper-evident with a hash chain, and retaining and querying it. The examples use a structured record and a hash chain, and the properties apply to any system with an audit requirement.

Record the who, what, and when for every action

Each audit record names the actor, the action, the target, the outcome, and the time, plus the request id and the source. The actor is the authenticated identity, not a client-supplied name; the action is what was attempted; the target is the object affected; the outcome is success or failure. Together they answer the auditor’s question about an action.

Record the security-relevant actions: authentication, authorization changes, data access that is sensitive, configuration changes, and any privileged operation. Record the failures too, because a failed attempt to access or to change is as interesting to an auditor as a success. A record that omits the failures cannot show a denied access.

function audit(action, actor, target, outcome, extra = {}) {
  return {
    time: new Date().toISOString(),
    actorId: actor.id,                     // the authenticated identity
    action,                                // e.g. 'document.delete'
    targetType: target.type,
    targetId: target.id,
    outcome,                               // 'success' | 'denied' | 'error'
    requestId: extra.requestId,
    sourceIp: extra.sourceIp,
  };
}

Make the store append-only

The application must not be able to edit or delete an audit record, or the trail is only as trustworthy as the application’s restraint. Store the records in a way that the application role can insert and read but not update or delete: a table with no update or delete grant for the application role, a separate store the application can only append to, or a write to an external audit system.

Retention is part of the store: the records are kept for the compliance period, and the removal of expired records is a separate, controlled process, not something the application does. Separate the append permission from the cleanup permission, so the application cannot erase a record, and the cleanup is auditable itself. The trail’s integrity depends on the append-only property.

-- the application role can insert and read, but not update or delete
GRANT INSERT, SELECT ON audit_log TO app_role;
REVOKE UPDATE, DELETE ON audit_log FROM app_role;

CREATE INDEX idx_audit_actor_time ON audit_log (actor_id, time DESC);
CREATE INDEX idx_audit_target ON audit_log (target_type, target_id, time DESC);

Make it tamper-evident with a hash chain

An append-only store prevents the application from editing a record, but an administrator or a storage-level change could still alter the data. A hash chain makes any change detectable: each record’s hash is computed over its content and the previous record’s hash, so altering one record breaks the chain from that point, and removing one leaves a gap. The chain is verified by recomputing the hashes and comparing the last.

Store the previous hash with each record, and compute the record’s hash over its content plus that previous hash. To verify, recompute each record’s hash and check it matches, and that each record’s previous hash equals the prior record’s hash. A mismatch names the tampered record. Anchor the last hash periodically to an external store, so a wholesale rewrite of the chain is also detectable.

import { createHash } from 'node:crypto';

function chainedHash(content, previousHash) {
  return createHash('sha256')
    .update(previousHash + '|' + JSON.stringify(content))
    .digest('hex');
}

function append(record, lastHash) {
  const hash = chainedHash(record, lastHash);          // chain to the previous
  return { ...record, prevHash: lastHash, hash };        // store both
}
// verify: recompute each hash, and assert prevHash equals the prior record's hash

Retain for the period and query for the request

Keep the records for the compliance period, which is set by the regulation or the policy, often months or years. Archival storage that is also append-only keeps the long tail affordable while preserving integrity, and the cleanup of expired records is scheduled and audited. The retention is part of the design, not an afterthought, because the auditor checks the period.

Index the records for the queries a compliance request makes: by actor and time, by target, by action. A request such as show every access to this document or every action by this user in this period is a query on those keys. Design the indexes around the questions the auditor asks, so the request is answered quickly and completely.

-- a compliance query: every actor who touched this document, in order
SELECT time, actor_id, action, outcome
FROM audit_log
WHERE target_type = 'document' AND target_id = $1
ORDER BY time;

Test the record, the append-only property, and the chain

Test that a security-relevant action writes a record with the actor, the action, the target, and the outcome, including a denied action. Test that the application role cannot update or delete a record, by attempting it and asserting the database rejects it. Test the chain, by altering a record in a copy and asserting the verification fails and names it, so the tamper-evidence is real.

# the application role must not be able to modify or delete an audit record
psql -d app -c "UPDATE audit_log SET action='x' WHERE id=1;"   # expect permission denied
psql -d app -c "DELETE FROM audit_log WHERE id=1;"              # expect permission denied
# verify the chain
node scripts/verify-audit-chain.mjs                               # expect intact

Common pitfalls

Using the operational log as the audit trail, letting the application role update or delete a record, recording only successes so a denied access is invisible, no tamper-evidence so an edit is undetectable, and no retention policy so the records expire before the compliance period are the recurring mistakes. A dedicated structured record, an append-only store, denied actions recorded, a hash chain, and a retention policy address them.

Conclusion

An audit trail is evidence, so it must be accurate, append-only, tamper-evident, and retained. Record the actor, the action, the target, the outcome, and the time, store the records so the application can only append, chain them with a hash so an edit is detectable, and retain and index them for the compliance queries. Self-check by asserting the application cannot modify a record and that altering one breaks the chain. Then the trail answers the auditor’s question and shows it is intact.

Sources: NIST: Audit logging guidance (SP 800-92), OWASP: Logging cheat sheet, AWS: CloudTrail and audit logging.

FAQ

How is an audit trail different from a log?
An audit trail is a record of security-relevant actions that must be accurate and tamper-evident, retained for a compliance period. An operational log is a debugging aid that may be sampled and rotated. The audit trail is designed for integrity and retention, not for debugging.
Why tamper-evidence?
A trail that an administrator can edit is not evidence. Chaining each record's hash with the previous one makes a removed or altered record detectable, so the trail can be shown to be intact. It is a property the auditor checks.

Related Examples