DEV Community

Sandscale
Sandscale

Posted on Originally published at sandscale.dev

Hash-chained audit logs, explained in under 40 lines of code

An audit log has one job that ordinary application logs do not: it has to be believable after something went wrong. When an agent ran a command it should not have, or a secret was used at 3 a.m., the log is what you show your team, your customer or your assessor. If anyone with database access could have quietly edited it, it is a story, not evidence.

Hash chaining is the standard, simple technique for making a log tamper-evident. This post explains how it works, what it proves and what it does not, and walks through a small verifier.

The idea in one paragraph

Each entry stores the hash of the entry before it. To compute an entry's own hash, you hash its contents together with that previous hash. Change any byte of any entry, and its hash changes, so the next entry's "previous hash" no longer matches. Delete an entry, and the entry after it points at a hash that is not there. To hide an edit, an attacker has to recompute every hash from the edited entry to the end of the log, and if anyone holds a copy of a later hash, the rewrite shows.

That is the whole mechanism. Git commits work the same way, as do the Merkle trees behind Certificate Transparency. The academic treatment is Crosby and Wallach's Efficient Data Structures for Tamper-Evident Logging (USENIX Security 2009), which is worth reading if you want the stronger tree-based variants.

A minimal chain

Here is a minimal implementation in Node, using only the standard library. It is an illustration of the technique, not the format any particular product uses.

import { createHash } from 'node:crypto';

const GENESIS = '0'.repeat(64);

// Canonical JSON: sorted keys, so the same entry always hashes the same way.
function canonical(value) {
  if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
  if (value && typeof value === 'object') {
    const keys = Object.keys(value).sort();
    return `{${keys.map((k) => `${JSON.stringify(k)}:${canonical(value[k])}`).join(',')}}`;
  }
  return JSON.stringify(value);
}

function hashEntry(prevHash, body) {
  return createHash('sha256').update(prevHash).update('\n').update(canonical(body)).digest('hex');
}

export function append(log, body) {
  const prevHash = log.length ? log[log.length - 1].hash : GENESIS;
  const entry = { seq: log.length, prevHash, body, hash: hashEntry(prevHash, body) };
  log.push(entry);
  return entry;
}

export function verify(log) {
  let prevHash = GENESIS;
  for (let i = 0; i < log.length; i++) {
    const e = log[i];
    if (e.seq !== i) return { ok: false, at: i, why: 'sequence gap or reorder' };
    if (e.prevHash !== prevHash) return { ok: false, at: i, why: 'previous hash does not match' };
    if (hashEntry(e.prevHash, e.body) !== e.hash) return { ok: false, at: i, why: 'entry contents changed' };
    prevHash = e.hash;
  }
  return { ok: true, head: prevHash };
}
Enter fullscreen mode Exit fullscreen mode

Three details in there carry most of the weight.

Canonical serialization. If two systems serialize the same entry with keys in a different order, they get different hashes and the chain "breaks" for no reason. Sorting keys, or using a defined canonical form, makes verification reproducible by someone other than the writer.

A sequence number. The hash chain already catches deletion in the middle, but an explicit seq makes the failure message obvious and catches reordering cheaply.

The head. verify returns the hash of the last entry. That single value summarizes the entire log up to that point. It is the thing you publish, store elsewhere or hand to someone, and it is what makes truncation and wholesale rewrites detectable.

What it proves, and what it does not

A hash chain is tamper-evident, not tamper-proof. Be precise about this when you describe your log to anyone.

It does show: an entry was edited after the fact; an entry was removed from the middle; entries were reordered.

It does not show, on its own:

  • Truncation at the end. Delete the last ten entries and the remaining chain still verifies. You catch this only if you compare against a head you saved earlier.
  • A full rewrite. Someone who controls the log storage can rebuild every hash from scratch. Again, only an independently held head reveals it.
  • Lies at write time. If the system writing the log records a false event, the chain faithfully protects the false event. The chain protects history, not truth.
  • Missing events. If an action never generated an entry, there is nothing to verify.

The first two are why serious designs anchor the head somewhere the log's operator cannot rewrite: a periodic export to storage you control, a signed checkpoint, or a published value. The last two are why it matters which component writes the log. Entries written by the platform that performed the action are worth more than entries the agent writes about itself.

Anchoring the head in practice

You do not need a blockchain. Some practical options, from least to most effort:

  1. Periodic exports. Export the log on a schedule into storage with object lock or write-once retention under your own account. Each export contains the head at that time. A later rewrite of the source does not match your copy.
  2. Signed checkpoints. Every N entries or every hour, sign the current head with a key the log writer does not hold, and store the signature with the export.
  3. Cross-posting the head. Some teams put the daily head into a ticket, a commit in a separate repository or an email to an archive. Crude, and surprisingly effective, because it puts a copy outside the operator's control.

When you hand a log to an assessor, include the head you anchored and the verifier, so they can check it themselves rather than trusting your word.

Why this matters more for agents

Agents act fast, in volume, and often without a person watching each step. When an incident review asks "did the agent read that secret, and what did it run next?", the honest answer depends on a record nobody had a chance to tidy up. A chained log makes that record checkable. Pair it with the right fields, which we covered in what an audit log for AI coding agents should record.

How Sandscale does it

Sandscale writes every action in an organization to an audit log where each entry is chained to the one before it, so a change or a gap shows. It records sign-ins, sandboxes and workspaces started and stopped, commands run, files moved, secrets used, approvals asked for and given, policy changes and kill switch use, with who did it, when and where.

Every plan can read its audit log in the console, and GET /api/v1/organizations/{id}/audit-logs reads it from the API. Team and Enterprise can export it for a period, as evidence for your own assessments. Sandscale does not claim a certification; certification stays with you and your assessor. Exporting on a schedule into storage you control is exactly the anchoring step described above.

Originally published on the Sandscale blog.

Top comments (0)