Audit Logs Need an Integrity Boundary
Use hash chains to expose changes, then place trusted checkpoints and append permissions outside the boundary an attacker can rewrite.
A table called audit_log is useful for investigation, but its name does not make it trustworthy. If the same compromised application account can update business records and rewrite the corresponding audit rows, an attacker can change the event and its supposed evidence together.
Integrity comes from a boundary: which component can append events, which component can alter history, and where an investigator obtains an independent expectation of what history should exist. Hashes can support that boundary, but they cannot create it by themselves.
Define the evidence you need
An audit event should identify an actor, action, target, outcome, and the relevant time or operation identity. The actor may be a service acting on behalf of a user, so preserve that relationship when it matters. Use structured fields with a documented schema rather than relying only on a prose message that changes between releases.
Separate an attempted action from a committed result. A log written before a transaction commits may describe work that later rolls back; a log written afterward may be lost if the process crashes in between. For evidence tied to a database change, record the event or an obligation to emit it in the same transaction when possible.
Choose what the log must prove. Detecting accidental corruption, detecting unauthorized rewriting, attributing events to a signer, and proving completeness are different requirements. A mechanism designed for one does not automatically satisfy the others.
Link records and test the limits
The following Python example hashes each serialized event together with the preceding digest. JSON encoding uses a fixed local convention and rejects nonfinite numbers. This is a small hash-chain model, not a cross-language canonical JSON standard, a signed log, or a transparency service.
from dataclasses import dataclass, replace
import hashlib
import json
GENESIS = "0" * 64
@dataclass(frozen=True)
class Record:
sequence: int
previous: str
payload: str
digest: str
def digest(previous, payload):
return hashlib.sha256((previous + "\n" + payload).encode("utf-8")).hexdigest()
def append(log, event):
sequence = len(log) + 1
previous = log[-1].digest if log else GENESIS
payload = json.dumps({"sequence": sequence, "event": event},
sort_keys=True, separators=(",", ":"), allow_nan=False)
log.append(Record(sequence, previous, payload, digest(previous, payload)))
def verify(log, trusted_head=None):
previous = GENESIS
for sequence, record in enumerate(log, 1):
if record.sequence != sequence or record.previous != previous:
return False
if digest(previous, record.payload) != record.digest:
return False
previous = record.digest
return trusted_head is None or previous == trusted_head
log = []
append(log, {"actor": "operator-7", "action": "grant", "resource": "report-4"})
append(log, {"actor": "operator-7", "action": "revoke", "resource": "report-4"})
anchor = log[-1].digest # In production, save independently of this log.
assert verify(log, anchor)
changed = [replace(log[0], payload=log[0].payload.replace("grant", "erase")), log[1]]
assert not verify(changed, anchor)
assert verify(log[:1]) # a valid prefix is not evidence of completeness
assert not verify(log[:1], anchor)
rewritten = []
append(rewritten, {"actor": "operator-7", "action": "read", "resource": "report-4"})
assert verify(rewritten)
assert not verify(rewritten, anchor)
Changing a payload without updating the hashes breaks verification. Removing the last record leaves a valid prefix, so verification without an independently trusted head still succeeds. Rewriting the entire chain also produces a self-consistent chain. The final checks show why a digest saved outside the rewritten data matters.
The in-memory variable named anchor only makes the comparison visible in a test. It is not an independent trust boundary. If an attacker can replace both the log and that variable's persisted equivalent, the comparison provides no protection against that attacker.
Move the checkpoint outside the rewrite boundary
Periodically publish the current sequence number and head digest to a separately controlled system. Depending on the threat model, that might be an append-restricted service, storage with independently administered retention controls, or a signed checkpoint distributed to external verifiers. The checkpoint's authentication and retention must survive the compromise you are trying to detect.
A checkpoint establishes an expected prefix at a point in time. It does not prove that every later event was recorded. The interval between checkpoints bounds part of the detection window, and a missing checkpoint is itself an operational signal. Preserve both the sequence and digest so an investigator knows which prefix the checkpoint covers.
Digital signatures can authenticate checkpoints to holders of a public key, but protecting and rotating the signing key becomes another responsibility. A compromised signer can sign false checkpoints. Consider separation of duties, restricted signing access, and independent monitoring rather than treating the presence of a signature as the end of the design.
Make appending an ordered durable operation
The example appends to one list in one process. A production writer must allocate the next sequence, read the current head, append the event, and advance the head atomically. Two concurrent writers that both build on the same head can otherwise create a fork. Database transactions or a serialized append service can enforce the intended order.
Define how retries work. A stable operation identifier can prevent the same committed event from being appended repeatedly after an acknowledgment is lost. Preserve duplicate or rejected append attempts in suitable operational telemetry when they matter, but do not confuse that telemetry with the authoritative audit stream.
Restrict the application account to the operations it needs. An append-only interface backed by an unrestricted database account is a convention, not an enforced boundary against account compromise. Backups, exports, and administrative tools also need integrity and access controls because investigators may rely on them after the live service is unavailable.
Keep evidence useful without collecting everything
Auditability does not require logging credentials, raw authorization headers, or complete private documents. Prefer stable identifiers and the minimum fields needed to establish the action. Apply access controls, retention, and redaction rules deliberately. Once a secret enters several retained copies, removing it becomes much harder than preventing its collection.
Validate and escape fields when rendering events so untrusted input cannot forge extra log lines or execute in a viewer. Monitor append failures, unexpected sequence gaps, delayed checkpoints, and verification failures. Decide which business operations may continue when the audit sink is unavailable and which must fail; that is a product and operational requirement.
Test mutation, truncation, reordering, competing appenders, key rotation, and recovery from a trusted checkpoint. A useful audit system can explain both what the retained evidence supports and what remains outside its guarantees. That clarity is more valuable than calling an editable table immutable.