Sub topic 4
Making logs tamper-evident and retaining them
This chapter assumes you have read the previous chapter on audit event design. You should know what an audit event contains. You should also be able to read basic Python and know what a SHA-256 hash is.
Tamper-evident, not tamper-proof
A log that an administrator can edit without anyone noticing has little value as evidence. Software cannot make that edit impossible for someone with enough access. It can make the edit detectable. That property is called tamper evidence.
For ML governance this matters because the log is what you show an auditor or regulator to prove who approved which model version and when. Under the EU AI Act, high-risk systems must support automatic event logging. If the logs can be silently rewritten, they prove little.
How a hash chain works
Each event stores the hash of the event before it. Each event's own hash covers its content, including that previous hash. Changing any earlier event changes its hash, which no longer matches the prev_hash stored in the next event. The break shows up when you verify the chain.
Save the following as auditlog.py. It canonicalizes each event body to JSON with sorted keys, so the same data always produces the same hash.
import hashlib
import json
from datetime import datetime, timezone
GENESIS = "0" * 64
def _digest(body: dict) -> str:
payload = json.dumps(body, sort_keys=True, separators=(",", ":")).encode("utf-8")
return hashlib.sha256(payload).hexdigest()
def append_event(log: list, actor: str, action: str, model: str, version: str, details: dict) -> dict:
body = {
"ts": datetime.now(timezone.utc).isoformat(),
"actor": actor,
"action": action,
"model": model,
"version": version,
"details": details,
"prev_hash": log[-1]["hash"] if log else GENESIS,
}
event = {**body, "hash": _digest(body)}
log.append(event)
return event
def verify(log: list) -> bool:
prev = GENESIS
for event in log:
body = {k: v for k, v in event.items() if k != "hash"}
if body["prev_hash"] != prev or _digest(body) != event["hash"]:
return False
prev = event["hash"]
return True
if __name__ == "__main__":
log = []
append_event(log, "alice", "register", "credit-scoring", "2.4.0", {"rows": 120000})
append_event(log, "bob", "approve", "credit-scoring", "2.4.0", {"role": "risk_reviewer"})
print(verify(log)) # True
log[0]["details"]["rows"] = 5 # silent edit
print(verify(log)) # FalseCanonical serialization is the detail people most often get wrong. If you hash str(dict) or JSON without sorted keys, a harmless change in key order produces a false alarm. If you re-serialize with different settings during verification, every event fails.
What the chain does not catch
The chain only proves that the events present are consistent with each other. Two attacks get past it:
- Tail truncation. Deleting the last events leaves a valid shorter chain.
- Full rewrite. Someone with write access recomputes every hash from the edited event onward. The result is a fully valid chain.
The fix for both is to keep a copy of the latest hash somewhere the log writer cannot modify. This is called anchoring. Options include:
- a separate account with write-once permissions
- a signed timestamp from a timestamping authority
- a periodic entry in a system owned by another team
The anchor records a length and a hash. Verification then confirms that the log still contains that exact prefix.
from auditlog import GENESIS, append_event, verify
def make_anchor(log: list) -> tuple:
"""Return (length, head_hash). Store this somewhere the log writer cannot edit."""
return len(log), (log[-1]["hash"] if log else GENESIS)
def verify_with_anchor(log: list, anchor: tuple) -> bool:
length, head = anchor
if len(log) < length or not verify(log):
return False
prefix_head = log[length - 1]["hash"] if length else GENESIS
return prefix_head == head
log = []
for i in range(3):
append_event(log, "ci-bot", "evaluate", "credit-scoring", "2.4.0", {"run": i})
anchor = make_anchor(log)
append_event(log, "ci-bot", "deploy", "credit-scoring", "2.4.0", {})
print(verify_with_anchor(log, anchor)) # True: new events after the anchor are fine
del log[2:] # truncate back to two events
print(verify(log)) # True: the chain alone is fooled
print(verify_with_anchor(log, anchor)) # False: the anchor exposes itStorage controls that support the chain
A hash chain works best alongside storage-level controls. Each control covers a different gap:
| Control | What it protects against | Typical implementation |
|---|---|---|
| Hash chain | Silent edits and deletions in the middle | Code as above |
| External anchor | Truncation and full rewrites | Separate account, signed timestamp |
| Write-once storage (WORM) | Deletion or overwrite before retention ends | Object storage with a retention lock |
| Append-only permissions | Accidental or casual edits | Writers get `append`, never `update` or `delete` |
| Access logging on the log store | Unrecorded reads and administrative changes | Cloud audit logs sent to a separate account |
Retention
Retention answers how long you must keep logs, and when you may or must delete them. Two kinds of pressure pull in opposite directions:
- Keep longer. The EU AI Act requires providers of high-risk systems to keep automatically generated logs under their control for a period appropriate to the intended purpose, and at least six months (Article 19). Deployers have a similar six-month minimum for logs under their control (Article 26). Technical documentation must be kept for ten years after the system is placed on the market (Article 18). Sector rules, such as those for financial institutions, can set longer periods. Litigation or investigations can add a legal hold.
- Keep shorter. Data protection law, such as the GDPR, asks you to limit personal data to what you need. Audit events often include user identifiers or input data.
Treat six months as a floor. Choose the actual period from your intended purpose and sector rules, and have your legal team confirm it. This tutorial is engineering guidance and not legal advice.
To satisfy both pressures:
- Log references and identifiers, not raw inputs. Store a dataset snapshot ID instead of the data itself.
- Pseudonymize people where you can. Keep the mapping in a separate store with its own retention rule.
- Split the log into segments, for example one per month. Start each new segment with an event that records the last hash of the previous segment, so the chain stays continuous across archive boundaries.
- Delete whole segments only when the retention period has passed and no legal hold applies.
from datetime import datetime, timedelta, timezone
MIN_RETENTION = timedelta(days=183) # about six months; set your own policy at or above this
def may_delete(segment_end: datetime, legal_hold: bool, retention: timedelta = MIN_RETENTION, now=None) -> bool:
if retention < MIN_RETENTION:
raise ValueError("retention policy is below the six-month floor")
now = now or datetime.now(timezone.utc)
return not legal_hold and now >= segment_end + retention
end = datetime(2026, 1, 31, tzinfo=timezone.utc)
print(may_delete(end, legal_hold=False, now=datetime(2026, 9, 1, tzinfo=timezone.utc))) # True
print(may_delete(end, legal_hold=True, now=datetime(2026, 9, 1, tzinfo=timezone.utc))) # FalseCommon errors
- Verifying only at write time. Run
verifyon a schedule and compare against the anchor. An unchecked chain detects nothing. - Letting the logging service hold the delete permission. Whoever can delete logs can erase their own actions.
- Hashing mutable fields. If a field such as
detailsis later enriched, the hash breaks. Record corrections as new events that reference the original. - Clock trust. The
tsfield comes from the writer's clock. An external timestamp in the anchor gives a second source. - Concurrent writers. Two processes appending at once can fork the chain. Use a single writer, a lock, or one chain per writer.
Exercise
A hash-chained audit log passes verify(). An auditor still asks how you know the last two weeks of events were not deleted. What do you add, and why does the chain alone not answer the question?
Show answer
Add an external anchor: the log length and head hash, saved periodically in a place the log writer cannot modify, such as a separate account or a signed timestamp. The chain only shows that the events present are consistent with each other, so removing the newest events still leaves a valid chain. Comparing the log against a stored anchor shows whether the expected prefix is still present.
Exercise
Your retention policy keeps audit logs for 90 days to reduce stored personal data. The system is high-risk under the EU AI Act. What is the problem, and how can you reduce the personal data without shortening the period?
Show answer
Ninety days is below the six-month minimum for logs under your control (Articles 19 and 26). Keep the period at six months or more, and cut personal data by logging identifiers and snapshot references instead of raw inputs, pseudonymizing people, and keeping any identity mapping in a separate store with its own retention rule.