Published
A tamper-evident audit log in Laravel: HMAC chain and daily anchors
In the internal CRM I build at ONEXO.pl, protection periods and commissions depend on when something was recorded, so the log of who changed what has to hold up as evidence. A normal activity log can’t do that, because anyone with database access can edit a row and leave no trace. I built this one in layers, and a later audit of the repository found two gaps in my first version.
- Laravel
- audit log
- HMAC
- PostgreSQL
- GDPR
- application security
Four layers, each for a different kind of access
The base is spatie/laravel-activitylog 5.1, which records who changed which fields, with values before and after. The application runs on Laravel 13 and PostgreSQL. I replaced the package’s model and its writing action to add these four layers.
- Model guard: updating or deleting an audit entry throws a LogicException. That stops application code, including administrators, who bypass policies in this panel.
- Database triggers: UPDATE, DELETE and TRUNCATE on the log fail in PostgreSQL, which stops raw queries. The one exception is deleting from the separate authentication log, which has a retention period.
- HMAC chain: each entry stores the hash of the previous entry in the same log and its own HMAC-SHA256, made with a key kept outside the database. Someone who drops the triggers can change a row, but the check will notice, and without the key they can’t recalculate the chain.
- Daily anchors: after a successful check, the last hash of each log is saved and emailed to an address outside the CRM. This covers what a chain can’t show by itself: a removed tail or a recalculated chain.
Writing an entry
This is the core of the writing action, shortened. The repository is private, so the snippets here are simplified.
The HMAC-SHA256 covers the log name, description, subject, event, author, changes, request context, previous hash and timestamp. Before hashing I sort the JSON keys, so the result doesn’t depend on key order or on how a database returns JSON (MySQL sorts the keys, for example).
The previous entry is read without a lock, so two parallel writes can point at the same predecessor and the chain forks. I accepted that. The check asks whether the predecessor exists, not whether the chain is one straight line, and it still catches edited and removed entries.
$entry->created_at = now()->startOfSecond();
$entry->previous_hash = AuditActivity::query()
->where('log_name', $entry->log_name)
->latest('id')
->value('hash');
$payload = $entry->canonicalPayload();
$entry->hash = hash_hmac('sha256', $payload, $key);
$entry->save();The nightly check
audit:verify --anchor runs from the Laravel scheduler at 03:00. It walks the entries by id, recalculates each hash and checks that the predecessor appeared earlier in the same log. Only the first entry may have no predecessor, otherwise the beginning of the log was removed. Then it checks that every stored anchor still points to an existing entry, and only after all of that passes does it write new anchors.
If the check fails, it writes a critical entry to the application log and sends administrators a notification in the panel.
The triggers come from one migration. A shared function raises an exception for everything except the retention delete from the authentication log.
CREATE TRIGGER activity_log_append_only
BEFORE UPDATE OR DELETE ON activity_log
FOR EACH ROW
EXECUTE FUNCTION activity_log_append_only();
CREATE TRIGGER activity_log_no_truncate
BEFORE TRUNCATE ON activity_log
FOR EACH STATEMENT
EXECUTE FUNCTION activity_log_append_only();What my first version missed
The first version, from 6 October 2026, used plain SHA-256. Anyone who could write to the database could recalculate the whole chain, because the hash needed no secret. On the same day I added the HMAC key, the triggers and the anchors. Entries already written couldn’t be signed again, so an hmac_cutover anchor records the last one made with SHA-256, and the check verifies older entries with SHA-256 and newer ones with HMAC.
The bigger gap lasted until 2 November. Anchors were written and emailed every night, but audit:verify never read them, so removing the newest entries still passed the check. A failed check also went only to the application log, which nobody reads unless they already suspect a problem. An audit of the repository found both, and I fixed them in the same pull request.
That same audit widened the data masked in the log to company names, tax IDs, websites and customer contact people, and kept recipients of the Mailing API out of it.
Personal data in a log that can’t change
An append-only log conflicts with anonymising a person’s record: the record can be cleared, but the old values would stay in the log. So each model lists its personal fields, and the log stores only a fingerprint: hmac: plus the first 16 hex characters of an HMAC of the value. The entry still proves that the field changed, and you can check a value you already know. Anonymising the record doesn’t touch the log, so the chain stays valid.
This is pseudonymisation, not anonymity. With the key, someone can test guessed values against a fingerprint. IP addresses and user agents are stored in the entries as they are, and failed logins keep the email address that was tried.
The authentication log is deleted after its retention period, so the check verifies each entry there but not the links between them.
What this doesn’t protect against
The log detects changes. It doesn’t prevent them and it can’t restore what was lost.
- Someone with both database access and the HMAC key can rewrite the chain and the anchor table. Only the emailed anchors would show that, and nothing compares them automatically.
- Entries written since the last anchor can be removed from the end of the log without detection, so the exposure is up to about a day.
- An anchor covers one entry. If the chain forked, removing the end of a side branch leaves no missing predecessor. I got this from reading the code and haven’t tested it.
- The code has no key rotation. A different key makes verification fail, so changing the key would need its own procedure.
- The check keeps hashes in memory, about 100 bytes per entry, so with millions of entries it would have to run in batches.
How I tested it
The tests drop the triggers on purpose and then edit an entry, delete one, remove the beginning of the log, remove an anchored entry from the end and swap the key, and each time audit:verify has to fail. On 4 November 2026 all 16 tests in this suite passed, with 58 assertions. They run on in-memory SQLite, so they exercise the SQLite versions of the triggers, not the PostgreSQL ones shown above.
Parts of this code were written with Claude Code. I merge every change myself. This note describes the design and its tests; I’m not giving figures from production here.
See also: Work history, Freelance Laravel backend development.
To talk about a similar setup or problem, use the contact page.