Sub topic 9
Keeping an audit trail of consent
This chapter assumes you can read basic SQL and Python, know how HTTP GET and POST requests differ, and have already modelled the subscriber lifecycle (pending, confirmed, unsubscribed). It covers what evidence to keep when someone signs up or changes their mind, how to store it so it can't quietly change, and which mistakes make the evidence useless.
Why a status column is not evidence
The status column on subscribers tells you what is true now. It says nothing about how the subscriber got there. If a regulator, a mailbox provider, or an angry recipient asks "how did you get my address?", a column reading confirmed is only a claim.
An audit trail answers the questions that follow:
- When did the person sign up, and when did they confirm?
- Which form, page, or import produced the sign-up?
- What wording did they see at the time?
- Which network address and browser made the request?
- What happened afterwards, such as unsubscribes and preference changes?
Under GDPR, the controller has to be able to demonstrate that consent was given. A trail that records events as they happen is the practical way to do that. Note that the trail supports consent you actually obtained. It cannot repair consent you never collected.
The consent events table
The schema from the earlier chapters has two tables. subscribers holds the current state. consent_events holds history.
CREATE TABLE subscribers (
id BIGSERIAL PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
status TEXT NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'confirmed', 'unsubscribed')),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
confirmed_at TIMESTAMPTZ
);
CREATE TABLE consent_events (
id BIGSERIAL PRIMARY KEY,
subscriber_id BIGINT NOT NULL REFERENCES subscribers(id),
event_type TEXT NOT NULL
CHECK (event_type IN ('signup', 'confirm', 'unsubscribe', 'preferences_updated')),
source TEXT NOT NULL,
consent_text TEXT,
ip_address INET,
user_agent TEXT,
occurred_at TIMESTAMPTZ NOT NULL DEFAULT now()
);Each column has a job:
| Column | What it proves |
|---|---|
| `event_type` | Which step in the lifecycle happened |
| `source` | Where the action came from, such as `footer_form`, `checkout`, `one_click_header`, or `import_2026_03` |
| `consent_text` | The exact wording shown to the person at that moment |
| `ip_address` | The network address that made the request |
| `user_agent` | The browser or client that made it |
| `occurred_at` | When the server recorded the event |
occurred_at defaults to now() on the database server, so a client cannot supply its own timestamp. Use TIMESTAMPTZ so the value is unambiguous across time zones.
What each event should capture
A double opt-in flow produces at least two events per subscriber, and the two carry different evidence.
The signup event records that someone typed this address into a form. The IP address and user agent belong to whoever submitted the form, who may not own the mailbox. The consent_text is the checkbox label or the sentence beside the button.
The confirm event records that someone with access to the mailbox clicked the link and pressed the Confirm button. Its IP address and user agent will usually differ from the sign-up event, and that is expected. The difference is part of the proof: the mailbox owner acted separately.
An unsubscribe event records the withdrawal and its source. Distinguishing one_click_header from preference_centre and from email_link helps you diagnose problems later. A preferences_updated event records changes to topics or frequency.
Do not store the full state of the subscriber in every row. Store what happened and the evidence for it. If you need the preference values at a given time, put a small JSON snapshot in an extra column, or reconstruct them by replaying events.
Write the event and the state change together
The most common integrity bug is updating subscribers without writing an event, or the other way round. Put both in one database transaction so either both happen or neither does.
from datetime import datetime, timezone
def record_confirmation(db, token: str, ip: str, user_agent: str):
"""Handle POST: confirm the subscriber and log the event atomically."""
email = verify_token(token, "confirm")
if email is None:
return render("link_invalid_or_expired.html")
now = datetime.now(timezone.utc)
with db.transaction():
row = db.query_one(
"UPDATE subscribers SET status = 'confirmed', confirmed_at = %s "
"WHERE email = %s AND status = 'pending' RETURNING id",
(now, email),
)
if row is not None:
db.execute(
"INSERT INTO consent_events "
"(subscriber_id, event_type, source, ip_address, user_agent, occurred_at) "
"VALUES (%s, 'confirm', 'confirmation_link', %s, %s, %s)",
(row["id"], ip, user_agent, now),
)
return render("subscription_confirmed.html")The WHERE status = 'pending' condition makes the operation idempotent. A second POST, for example from a double click, matches no row, so RETURNING yields nothing and no duplicate confirm event is written. The learner should notice that the function reuses verify_token and render from the token chapters. The db helper object here is a placeholder with transaction, query_one, and execute methods, so adapt those calls to your database library.
Log only on the POST. A GET that merely displays the Confirm button must not write a confirm event, because a security scanner may fetch it. Recording scanner traffic as consent would corrupt the evidence.
Keep the trail append-only
An audit trail loses its value if rows can be edited. Treat consent_events as append-only:
- Never run
UPDATEorDELETEagainst it from application code. - Give the application's database role only
INSERTandSELECTon the table. - Correct mistakes by adding a new event, not by editing an old one.
REVOKE UPDATE, DELETE ON consent_events FROM app_role;
GRANT SELECT, INSERT ON consent_events TO app_role;For stronger guarantees you can add a trigger that raises an error on any update or delete, or ship the events to write-once storage. Those options cost more to run, so choose them based on how likely you are to need them in a dispute.
Store the wording, not just a version label
Sign-up forms change. If you store only form_v3, you depend on keeping every old template forever. Storing the literal consent_text in the row avoids that. When the wording is long, hash it and keep the full text in a separate consent_texts table keyed by the hash, so identical wording is stored once.
import hashlib
def consent_text_id(text: str) -> str:
"""Stable identifier for a piece of consent wording."""
return hashlib.sha256(text.strip().encode("utf-8")).hexdigest()The same reasoning applies to imported lists. If you migrate subscribers from another system, create signup events with a source such as import_2026_03 and keep whatever evidence the previous system had. If the previous system has no evidence, the import event honestly records that gap. A vague event is better than an invented one.
Privacy cost of the trail
IP addresses and user agents are personal data. Collecting them is justified by the need to demonstrate consent, but that justification does not last forever. Decide in advance:
- How long you keep events after a subscriber unsubscribes. A fixed period tied to how long complaints or claims could arise is common. Ask your legal adviser for the number.
- Whether to truncate or hash IP addresses after a set time, keeping the proof of the event without the full address.
- How an erasure request is handled. You may need to keep a minimal record, such as a hashed address with the suppression entry, so you do not email the person again.
That last point connects to the suppression list. Erasing a subscriber completely while forgetting that they opted out can lead to re-adding them from a later import.
Reading the trail
A trail is only useful if you can answer questions from it. A single query shows one subscriber's history:
SELECT event_type, source, consent_text, ip_address, user_agent, occurred_at
FROM consent_events
WHERE subscriber_id = (SELECT id FROM subscribers WHERE email = '[email protected]')
ORDER BY occurred_at, id;You can also use it for quality checks. This query finds confirmed subscribers who have no confirm event, which indicates a code path that changed state without logging it:
SELECT s.id, s.email
FROM subscribers s
LEFT JOIN consent_events e
ON e.subscriber_id = s.id AND e.event_type = 'confirm'
WHERE s.status = 'confirmed' AND e.id IS NULL;Run it on a schedule. Any rows it returns are a bug to investigate. Imported subscribers will appear here unless you gave them a matching event type, so decide how your imports are represented.
Common errors
| Mistake | Consequence | Fix |
|---|---|---|
| Logging the event on GET | Scanner traffic counted as consent | Log only on POST |
| Updating status in one transaction and logging in another | State and history disagree after a failure | One transaction for both |
| Storing only a form version | Wording cannot be reproduced | Store the text or its hash |
| Letting the app edit events | History can be questioned | Revoke `UPDATE` and `DELETE` |
| Trusting a client-supplied timestamp | Time can be forged | Use the server clock |
| Reading `X-Forwarded-For` without checking | Recorded IP is spoofable | Take it only from your trusted proxy |
Exercise
A subscriber says they never signed up. Your database shows status = 'confirmed'. List the events you would look for in consent_events and explain what each one would tell you about whether the claim holds up.
Show answer
Look for a signup event, which shows the form or import source, the consent_text shown, and the IP address and user agent that submitted the address. Then look for a confirm event, which shows that someone controlling the mailbox pressed Confirm through the emailed link, along with a separate IP address and user agent. A signup followed by a confirm with differing network details and a plausible gap in time is good evidence that the mailbox owner acted. A signup with no confirm, or a confirm logged within milliseconds of the email being sent, suggests scanner activity or a logging bug. No events at all means you cannot demonstrate consent, so stop emailing the address and add it to the suppression list.
Exercise
Why does the confirm handler write the event only when the UPDATE ... WHERE status = 'pending' matched a row?
Show answer
The condition makes confirmation idempotent. If the person double-clicks or the request is retried, the second call matches no pending row, so no second confirm event is written. The trail then holds exactly one confirmation for the one real state change.