Skip to main content

08 - Legal Data Privacy & GDPR Compliance Systems

An append-only consent log, data subject request deadlines and time-limited retention: the GDPR turned into code that was actually run.

What do you think about this article?

At a Glance

An append-only consent log, data subject request deadlines and time-limited retention: the GDPR turned into code that was actually run.

Data Privacy and GDPR Compliance Systems

The GDPR does not only ask you to respect the rules on personal data: it asks you to be able to demonstrate it. This is the principle of accountability, written in Article 5, paragraph 2, and it has a very practical consequence for those who develop. When a user says "I never consented" or "delete my data", the answer is not an opinion: it is a row in a log, an expiry date computed by the system, a deletion report. A compliance system is, first of all, a system that produces evidence.

This article builds four components with code that I ran: an append-only consent log, the handling of a data subject request with a deadline computed according to Article 12, a time-limited data retention engine and the expiry logic of a cookie banner. The record of processing activities and the privacy by design practices follow. The tone is that of a developer who reads the rules, not of a lawyer: where a choice is legal, I say so and point you to the source. The personal data side connects with another theme of the series, that of signatures and the authenticity of documents.

From the principles of Article 5 to architecture decisions

The principles of Article 5, paragraph 1, are six, and each one translates into a technical choice that you can verify in a code review. The table lists them with the technical choice that follows from them; the seventh element, accountability, is paragraph 2 and closes the circle.

Principle What it means for the code Where you see it in this article
Data minimisation Collect only the fields needed for the declared purpose The consent log stores a pseudonym of the IP, not the IP
Purpose limitation Each consent is tied to a purpose, not to "cookies" The finalita column of the log
Accuracy Data that can be corrected on request (art. 16) The flow of data subject requests
Storage limitation Data deleted or anonymised when the purpose ends The retention engine
Integrity and confidentiality Encryption, access control, tracking Pseudonymisation and the access log
Accountability Being able to demonstrate everything else The append-only log and the dry-run reports

A consent log that withstands a challenge

Article 7, paragraph 1, says that the controller "shall be able to demonstrate" that the data subject has consented, and paragraph 3 that consent is withdrawn as easily as it is given. From this come two design choices. The log is append-only: a withdrawal does not delete the previous consent, it writes a new one with concesso = 0, so that the history can be reconstructed. And the current state is derived from the last record per purpose, ordered by a sequence number and not by time, because server clocks can go backwards.

A frequent oversight is saving sha256(ip) thinking it is anonymous. IPv4 addresses are about four billion: whoever has the hash can try them all. The listing uses instead an HMAC with a secret key (hmac, in the standard library), which remains a pseudonym, therefore still personal data, but is not reversible by someone who does not have the key. The key in the listing is a placeholder: in a real system it lives outside the repository. The code uses sqlite3 from the standard library and runs as it is.

consenso.py - append-only consent log
import hashlib
import hmac
import sqlite3
import uuid
from datetime import datetime, timezone

CHIAVE_PSEUDONIMI = b"replace-with-a-secret-kept-outside-the-repository"


def pseudonimo(valore: str) -> str:
    """HMAC with a secret key: you cannot get back to an IP without the key."""
    return hmac.new(CHIAVE_PSEUDONIMI, valore.encode(), hashlib.sha256).hexdigest()[:16]


class RegistroConsensi:
    """Append-only log: a consent is never modified, a new one is written."""

    def __init__(self, conn: sqlite3.Connection, versione_informativa: str):
        self.conn = conn
        self.versione = versione_informativa
        conn.execute("""
            CREATE TABLE IF NOT EXISTS consensi (
                seq INTEGER PRIMARY KEY AUTOINCREMENT,
                record_id TEXT NOT NULL,
                utente TEXT NOT NULL,
                finalita TEXT NOT NULL,
                concesso INTEGER NOT NULL,
                versione TEXT NOT NULL,
                istante TEXT NOT NULL,
                ip_pseudonimo TEXT NOT NULL,
                punto_di_raccolta TEXT NOT NULL
            )""")

    def registra(self, utente, finalita, concesso, ip, punto_di_raccolta):
        self.conn.execute(
            "INSERT INTO consensi (record_id, utente, finalita, concesso, versione, istante,"
            " ip_pseudonimo, punto_di_raccolta) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
            (str(uuid.uuid4()), utente, finalita, int(concesso), self.versione,
             datetime.now(timezone.utc).isoformat(), pseudonimo(ip), punto_di_raccolta))

    def stato_corrente(self, utente: str) -> dict:
        """The last record for each purpose wins. Order by seq, not by time."""
        righe = self.conn.execute("""
            SELECT finalita, concesso FROM consensi c
            WHERE utente = ? AND seq = (
                SELECT MAX(seq) FROM consensi WHERE utente = c.utente AND finalita = c.finalita)
            ORDER BY finalita""", (utente,)).fetchall()
        return {finalita: bool(concesso) for finalita, concesso in righe}


if __name__ == "__main__":
    conn = sqlite3.connect(":memory:")
    reg = RegistroConsensi(conn, versione_informativa="2026-11")
    reg.registra("u-42", "analytics", True, "203.0.113.7", "banner")
    reg.registra("u-42", "marketing", True, "203.0.113.7", "banner")
    reg.registra("u-42", "marketing", False, "203.0.113.7", "preferences_panel")  # withdrawal
    print("current state:", reg.stato_corrente("u-42"))
    print("records written:", conn.execute("SELECT COUNT(*) FROM consensi").fetchone()[0])
    print("same IP, same pseudonym:", pseudonimo("203.0.113.7") == pseudonimo("203.0.113.7"))
    print("pseudonym:", len(pseudonimo("203.0.113.7")), "characters, it is not the IP")

# Output:
# current state: {'analytics': True, 'marketing': False}
# records written: 3
# same IP, same pseudonym: True
# pseudonym: 16 characters, it is not the IP

The output shows the behavior that matters. Three records were written, but the current state reports two purposes: analytics remains granted and marketing results withdrawn, because the last record for that purpose is the withdrawal, which came from a different collection point (the preferences panel, not the banner). The same IP always produces the same pseudonym, so you can correlate events without storing the address. In real use you will also want the privacy notice versioned, as in the versione field: it serves to know what the user accepted, not just that they clicked.

Data subject requests: the deadline is a calendar one, not thirty days

Articles 15 to 22 give the data subject the rights of access, rectification, erasure, restriction, portability and objection. Article 12, paragraph 3, sets the response time: "without undue delay and in any event within one month of receipt of the request", extendable by two further months where necessary, taking into account the complexity and the number of the requests, with the obligation to inform the data subject of the extension within one month of receipt. It is not "30 days" and it is not "60": it is one month plus, at most, two.

The listing below computes the deadline in calendar months. The regulation does not specify how to count a month that ends on a nonexistent day: the code chooses the last day of the month of arrival (31 January plus one month is 28 February), a convention worth agreeing with whoever looks after data protection in the organisation. The most delicate part is erasure. Not everything is deleted: Article 17, paragraph 3, excludes data necessary for compliance with a legal obligation and data necessary for the establishment, exercise or defence of legal claims. For this reason the policy per table is explicit data, with the reason next to it, and the function has a dry-run mode that shows what it would do without doing it.

dsr.py - the Article 12 deadline and erasure by policy
import calendar
import sqlite3
from dataclasses import dataclass
from datetime import date

# For each table: what to do on an erasure request, and why.
POLITICA_CANCELLAZIONE = {
    "profili":   ("delete", "no retention obligation"),
    "analytics": ("delete", "purpose exhausted"),
    "ordini":    ("keep",   "legal retention obligation (art. 17, par. 3, point b): which fields and for how long is set by the sector rule"),
    "consensi":  ("keep",   "to be decided with the DPO: proof of consent and defence in legal proceedings (art. 17, par. 3, point e)"),
}


def aggiungi_mesi(d: date, mesi: int) -> date:
    """A calendar month, not 30 days: 31 January + 1 month is 28 (or 29) February."""
    indice = d.month - 1 + mesi
    anno, mese = d.year + indice // 12, indice % 12 + 1
    return date(anno, mese, min(d.day, calendar.monthrange(anno, mese)[1]))


@dataclass
class Richiesta:
    tipo: str            # "access", "erasure", ...
    utente: str
    ricevuta: date
    prorogata: bool = False

    @property
    def scadenza(self) -> date:
        # art. 12, par. 3: one month, extendable by two more if the request is complex
        return aggiungi_mesi(self.ricevuta, 3 if self.prorogata else 1)


def cancella_dati(conn: sqlite3.Connection, utente: str, applica: bool = False) -> list[dict]:
    report = []
    for tabella, (azione, motivo) in POLITICA_CANCELLAZIONE.items():
        n = conn.execute(f"SELECT COUNT(*) FROM {tabella} WHERE utente = ?", (utente,)).fetchone()[0]
        voce = {"table": tabella, "records": n, "action": azione, "reason": motivo}
        if applica and n:
            if azione == "delete":
                conn.execute(f"DELETE FROM {tabella} WHERE utente = ?", (utente,))
        report.append(voce)
    return report


def banco_di_prova() -> sqlite3.Connection:
    conn = sqlite3.connect(":memory:")
    conn.executescript("""
        CREATE TABLE profili   (utente TEXT, email TEXT, nome TEXT);
        CREATE TABLE analytics (utente TEXT, pagina TEXT);
        CREATE TABLE ordini    (utente TEXT, email TEXT, nome TEXT, importo REAL);
        CREATE TABLE consensi  (utente TEXT, finalita TEXT);
        INSERT INTO profili   VALUES ('u-42', 'a@example.com', 'Anna');
        INSERT INTO analytics VALUES ('u-42', '/pricing'), ('u-42', '/blog');
        INSERT INTO ordini    VALUES ('u-42', 'a@example.com', 'Anna', 120.0);
        INSERT INTO consensi  VALUES ('u-42', 'analytics');
    """)
    return conn


if __name__ == "__main__":
    print("31 Jan + 1 month :", aggiungi_mesi(date(2026, 1, 31), 1))
    print("simple deadline  :", Richiesta("access", "u-42", date(2026, 11, 12)).scadenza)
    print("extended deadline:", Richiesta("access", "u-42", date(2026, 11, 12), prorogata=True).scadenza)

    conn = banco_di_prova()
    for voce in cancella_dati(conn, "u-42", applica=False):
        print("dry run", voce["table"], voce["records"], voce["action"])
    print("profiles after the dry run:", conn.execute("SELECT COUNT(*) FROM profili").fetchone()[0])
    cancella_dati(conn, "u-42", applica=True)
    print("profiles after:", conn.execute("SELECT COUNT(*) FROM profili").fetchone()[0],
          "| orders:", conn.execute("SELECT COUNT(*) FROM ordini").fetchone()[0],
          "| consents:", conn.execute("SELECT COUNT(*) FROM consensi").fetchone()[0])

# Output:
# 31 Jan + 1 month : 2026-02-28
# simple deadline  : 2026-12-12
# extended deadline: 2027-02-12
# dry run profili 1 delete
# dry run analytics 2 delete
# dry run ordini 1 keep
# dry run consensi 1 keep
# profiles after the dry run: 1
# profiles after: 0 | orders: 1 | consents: 1

The first three output lines are the deadline: one month from 12 November 2026 falls on 12 December, with the extension on 12 February 2027, and 31 January plus one month is 28 February. The "dry run" lines show the dry-run report: the profiles and the analytics events are to be deleted, the orders and the consents to be kept, and after the dry run the profile is still there. After applying, the profile is gone, while the orders and the consent remain. Pay attention to the table names: they end up in an SQL string because they come from a constant in the code; they must never come from user input. As for the orders, keeping them does not mean leaving them available to everyone: they must be isolated and no longer used for other purposes, and which fields to keep and for how long is set by the sector rule, not by the programmer.

Limited retention: making data expire without anyone having to remember

Article 5, paragraph 1, point e, forbids keeping data in a form that allows the identification of data subjects for longer than necessary for the purposes. A term written in a policy is not enough: you need a process that applies it. The engine below receives a list of policies (table, days, action, reason) and a "now" time passed in from outside, instead of reading it from the clock: it is the trick that makes the behavior verifiable with fixed dates.

retention.py - retention policies with a dry-run mode
import sqlite3
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone


@dataclass(frozen=True)
class PoliticaDiConservazione:
    tabella: str
    giorni: int
    azione: str          # "delete" or "anonymize"
    motivo: str          # why exactly this term: it must be written down, and it must be defensible


def applica(conn: sqlite3.Connection, politiche, adesso: datetime, a_secco: bool = True) -> list[dict]:
    report = []
    for p in politiche:
        limite = (adesso - timedelta(days=p.giorni)).isoformat()
        scaduti = conn.execute(
            f"SELECT COUNT(*) FROM {p.tabella} WHERE creato_il < ?", (limite,)).fetchone()[0]
        if not a_secco and scaduti:
            if p.azione == "delete":
                conn.execute(f"DELETE FROM {p.tabella} WHERE creato_il < ?", (limite,))
            else:
                conn.execute(f"UPDATE {p.tabella} SET email = NULL WHERE creato_il < ?", (limite,))
        report.append({"table": p.tabella, "limit": limite[:10], "expired": scaduti,
                       "action": p.azione, "executed": not a_secco and scaduti > 0})
    return report


if __name__ == "__main__":
    adesso = datetime(2026, 11, 12, tzinfo=timezone.utc)
    conn = sqlite3.connect(":memory:")
    conn.execute("CREATE TABLE log_accessi (email TEXT, creato_il TEXT)")
    for giorni_fa in (3, 40, 400):
        conn.execute("INSERT INTO log_accessi VALUES (?, ?)",
                     ("x@example.com", (adesso - timedelta(days=giorni_fa)).isoformat()))
    politiche = [PoliticaDiConservazione("log_accessi", 30, "delete", "fault diagnosis: 30 days are enough")]
    print("dry run :", applica(conn, politiche, adesso, a_secco=True)[0])
    print("left    :", conn.execute("SELECT COUNT(*) FROM log_accessi").fetchone()[0])
    print("executed:", applica(conn, politiche, adesso, a_secco=False)[0]["executed"])
    print("left    :", conn.execute("SELECT COUNT(*) FROM log_accessi").fetchone()[0])

# Output:
# dry run : {'table': 'log_accessi', 'limit': '2026-10-13', 'expired': 2, 'action': 'delete', 'executed': False}
# left    : 3
# executed: True
# left    : 1

On the three test records (from 3, 40 and 400 days ago) the 30-day policy finds two expired, and the dry run leaves the three records where they were; only the second run deletes two. The motivo field carries the most weight: a retention term without a written reason is the first thing an authority or a customer asks you to explain. The 30 days in the listing are an example value, not a recommendation: every term must be derived from the purpose and, where one exists, from a rule. Schedule the run with a scheduler, and keep the report of every run: it is the proof that the process runs.

The cookie banner: where the rule is already a computation

For cookies and other tracking tools in Italy the guidelines of the Italian data protection authority (the Garante) of 10 June 2021 apply (the page is in Italian). Two sentences of that text translate directly into code. The first: consent is validly given only if it is the result of an active and informed action by the user, verifiable and demonstrable; the consent log above serves this. The second: after the user has chosen not to give consent, the site must not show the banner again for a period of not less than 6 months, except for the exceptions described in the same guidelines, for example if the conditions of the processing change or if the site cannot detect the previous choice.

The function that follows is the smallest possible example of this rule. It is not an Angular component: it is a pure function, run with Node 24, which is then inserted into the banner service of your frontend. Keeping it separate from the framework makes it testable with fixed dates. I did not run the complete Angular component: the listing that appears here is only the expiry logic. In the real service the state must be read from where you saved it; choosing between localStorage and a cookie is your decision, but remember that the former too falls among the tracking tools the guidelines talk about.

consenso_scadenza.ts - when to show the banner again
type Scelta = { analytics: boolean; marketing: boolean; salvatoIl: string };

const SEI_MESI_IN_GIORNI = 183; // prudent threshold: "at least 6 months" in the Garante's guidelines

/** True if the banner must be shown again. */
export function bannerDaMostrare(salvata: Scelta | null, adesso: Date): boolean {
  if (salvata === null) return true; // no recorded choice: the banner is needed
  const trascorsi = (adesso.getTime() - new Date(salvata.salvatoIl).getTime()) / 86_400_000;
  const haRifiutatoTutto = !salvata.analytics && !salvata.marketing;
  // After a refusal the banner is not shown again before 6 months; after a consent the
  // expiry is decided by the controller (and must be written in the privacy notice).
  return haRifiutatoTutto ? trascorsi >= SEI_MESI_IN_GIORNI : false;
}

const adesso = new Date("2026-11-12T10:00:00Z");
const rifiuto: Scelta = { analytics: false, marketing: false, salvatoIl: "2026-09-12T10:00:00Z" };
console.log("no choice            :", bannerDaMostrare(null, adesso));
console.log("refusal 2 months ago :", bannerDaMostrare(rifiuto, adesso));
console.log("refusal 8 months ago :", bannerDaMostrare({ ...rifiuto, salvatoIl: "2026-03-01T10:00:00Z" }, adesso));

// Output:
// no choice            : true
// refusal 2 months ago : false
// refusal 8 months ago : true

The output shows the three cases: with no recorded choice the banner must be shown, after a refusal two months ago it must not, after a refusal eight months ago it must. The value of 183 days is my approximation of "at least 6 months", chosen to stay on the prudent side; if the organisation prefers a different number, that number must be written in the privacy notice. The granted-consent branch returns false with no expiry: in the guidelines I read I did not find a term for consent and I do not invent one.

The record of processing activities

Article 30 requires keeping a record of processing activities. Paragraph 5 exempts enterprises and organisations with fewer than 250 employees, but not if the processing is likely to result in a risk to the rights and freedoms of data subjects, if it is not occasional or if it includes special categories of data (Article 9) or data on criminal convictions and offences (Article 10). Since an organisation that processes data continuously often falls under one of these exceptions, the prudent practice is to keep it anyway. For each processing the record shows:

  • the name and contact details of the controller and, if present, of the data protection officer;
  • the purposes of the processing;
  • the categories of data subjects and the categories of personal data;
  • the categories of recipients, including those in third countries;
  • any transfers to a third country, with the appropriate safeguards;
  • where possible, the envisaged time limits for erasure and a description of the security measures.

The list is that of paragraph 1, and the order does not change the meaning. As a developer, the lesson is that the record should not be kept in a separate document that goes stale: the purposes are already in the consent log, the terms are already in the retention policies, and the recipients are in the contracts with suppliers. When these three things are data, the record is generated from them and does not diverge from the system. The record must be made available to the supervisory authority on request (Article 30, paragraph 4).

Privacy by design: three practices you can see in the code

Article 25 asks for data protection by design and by default. Some of the practices that follow from it are checks you can do in a code review.

  • Pseudonymisation: use an internal identifier in place of the email in the working databases, and keep the mapping table in a separate service with restricted access.
  • Separation by purpose: data collected for analytics must not be readable by the marketing modules, and vice versa.
  • Restrictive defaults: every optional purpose starts off, and turning it on requires an action by the user.

The common criterion is least privilege for data: each component receives only what it needs for its purpose. Pseudonymisation does not remove the nature of personal data (Article 4, point 5, defines it as a measure, not as anonymity), but it reduces the harm if a database leaks. The defaults are the easiest to verify: just look at the initial state of the banner.

Where consent systems go wrong

Four mistakes recur, and all have a precise reference. Consent "bundled" into the terms of service: Article 7, paragraph 4, says that in assessing whether it is freely given, utmost account is taken of whether the performance of a contract is conditional on consent that is not necessary for its performance. Withdrawal made harder than consent: Article 7, paragraph 3, wants it as easy as giving it, and a "Reject" button that is hidden or weaker than "Accept" is a case of deceptive design addressed by the Guidelines 03/2022 of the European Data Protection Board, referring in particular to social media platforms but useful as a catalogue of things not to do. Third, analytics tools activated before the choice. Fourth, a log that does not allow demonstrating when and how consent was given. I give no ranking of which is the most frequent penalty: I have no primary source to say so.

What you can do now

You can build a consent log that can be defended, compute the deadline of a data subject request as Article 12 intends it, apply retention policies with a dry-run proof, translate a rule of the Garante into a verifiable function and derive the record of processing activities from the data the system already holds. What the code does not decide, and what stays with whoever answers for data protection in your organisation, are the legal bases, the retention terms and the reading of the exceptions. This article is not legal advice. For the next part of the series, an assistant that works on such sensitive data, read the Legal Copilot; for data that crosses several systems, the integration patterns.

Sources

The three Python listings and the TypeScript listing were run with Python 3.14 and Node 24: the outputs shown are the real ones. The Angular banner component was not run, and the legal bases and the retention terms are choices of the organisation, not of the code.

Frequently asked questions

How soon must I respond to a data subject request?

Without undue delay and in any event within one month of receipt. The term can be extended by two months where necessary, because of complexity or the number of requests, informing the data subject within the first month (art. 12, par. 3).

Is a hash of an IP address anonymous data?

No. IPv4 addresses are about four billion, so a simple hash is reversed by trying them. An HMAC with a secret key is a pseudonym, not reversible without the key, but it remains personal data.

After the user refuses cookies, when can I show the banner again?

The Garante's guidelines of 10 June 2021 indicate a period of not less than 6 months, with some exceptions, for example if the conditions of the processing change. The text of the guidelines is the source, not this answer.

Do I have to keep a record of processing activities if I have fewer than 250 employees?

The exemption in Article 30, paragraph 5, does not apply if the processing presents a risk to the rights of data subjects, is not occasional or concerns special categories of data or data on criminal convictions. In many cases the record is therefore needed anyway.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects