DataCorp holds the name and email address of 200,000 people, the details of what they buy and what they write when they complain. Today that data is queried with shared credentials: nobody knows who looks at what, and anybody with the password sees everything. On top of that, the analytical platform is going to bring together in one place what used to be scattered, which makes it a more valuable target and a greater risk if it is poorly protected.

This lesson deals with two related but different topics. Security protects the data against unwanted access, alteration and loss. Privacy protects the people the data refers to: it determines what can legitimately be done with their data, even by somebody who has authorized access. We will look at the security controls (access, encryption, masking, auditing and backups), the GDPR obligations and how they apply to DataCorp in order to meet requirements RQ-08 and RQ-10.

Disclaimer. This lesson is for educational purposes and does not constitute legal advice. Data protection regulations depend on the specific case and change over time. Any real decision about legal bases, retention periods or handling of rights must be reviewed by the organization's data protection officer (DPO) or compliance department, and the technical controls, by a security professional.

The triad: confidentiality, integrity and availability

Information security pursues three goals, known as the CIA triad:

Goal Meaning Typical threat Main controls
Confidentiality Only those who are authorized access the data A leak of the customers table; an employee snooping on orders Access control, encryption, masking
Integrity The data is not improperly altered Somebody modifies amounts; a process corrupts files Minimal write permissions, immutable raw zone, auditing
Availability The data is accessible when it is needed Accidental deletion, ransomware, service outage Backups, redundancy, recovery plan

The three compete with each other: more confidentiality usually means less convenient access. The balance is not struck in the same way for all data, and that is why we start from its classification.

From classification to controls

Policy POL-01 (lesson 03-01) classified the data into four levels. Classification on its own protects nothing; its usefulness is to determine which controls apply:

Level Who has access Masking Auditing Example
public Any authenticated employee No Basic Product catalog
internal Platform roles No Basic consumption.daily_net_sales
confidential Specific roles, on a need-to-know basis Personal data masked by default Every access is logged consumption.dim_customer
restricted Specific people, for a limited time, with the owner's approval Column excluded by default Logged and reviewed every month tickets.description

Encryption at rest and in transit is applied to all levels: it is cheap and there is no reason to make exceptions.

Authentication and authorization

These are two different steps:

  • Authentication: checking that somebody is who they say they are. It is strengthened with multi-factor authentication (something you know, such as a password, plus something you have, such as your phone) and with single sign-on (SSO), which centralizes the company's identities: when an employee leaves, they lose all their access at once.
  • Authorization: deciding what an already authenticated identity can do.

The principle that governs authorization is least privilege: each person or process receives only the permissions that are essential for its task, and only for as long as necessary. There are two models for organizing it:

RBAC (role-based access control) ABAC (attribute-based access control)
Idea Permissions are assigned to roles, and roles to people A rule evaluates attributes of the user, of the data and of the context
Example "The analyst role can read the consumption schema" "A confidential piece of data can be read if the user belongs to the data's domain and connects from the corporate network"
Advantages Simple to understand and to audit Very flexible; avoids multiplying roles
Drawbacks With many special cases, roles proliferate Harder to reason about and to debug
Fits Small and medium-sized organizations Large organizations with many domains

DataCorp, with about 40 users, will use RBAC with five roles:

Role Who Access
role_data_engineering Marta and Íñigo Read and administration in the three zones
role_analyst Laura, Dani and the rest of the analysts Read on the consumption schema, with personal data masked
role_personal_data Specific people, for a limited time Read on consumption.dim_customer unmasked; approved by Nuria, owner of the Customers domain
role_load_service Service account svc_load, used by the load processes Write in the three zones
role_bi_service Service account svc_bi, used by the dashboard tool Read on the aggregate tables of consumption

The following SQL implements it. The syntax is PostgreSQL's; each analytical engine has its variants, but the concepts (role, GRANT, REVOKE) are common to all of them.

-- 1. Group roles: they represent profiles. NOLOGIN = nobody logs in with them
CREATE ROLE role_analyst NOLOGIN;
CREATE ROLE role_personal_data NOLOGIN;

-- 2. Permissions of the analyst role: the whole consumption schema...
GRANT USAGE ON SCHEMA consumption TO role_analyst;
GRANT SELECT ON ALL TABLES IN SCHEMA consumption TO role_analyst;
-- ...except the unmasked customer dimension
REVOKE SELECT ON consumption.dim_customer FROM role_analyst;

-- 3. The personal data role can read it
GRANT USAGE ON SCHEMA consumption TO role_personal_data;
GRANT SELECT ON consumption.dim_customer TO role_personal_data;

-- 4. Individual users: one identity per person, which inherits from its role
CREATE ROLE laura LOGIN;
GRANT role_analyst TO laura;

-- 5. End of the inherited shared credential
DROP ROLE reports;
  • Permissions are granted to roles, never directly to people. When Laura changes jobs, it is enough to take the role away from her.
  • GRANT USAGE ON SCHEMA allows "entering" the schema; GRANT SELECT allows reading its tables. Both are needed.
  • REVOKE withdraws a permission. The result is that an analyst sees all of consumption except dim_customer.
  • CREATE ROLE laura LOGIN creates an individual identity (in practice, linked to the corporate SSO instead of having its own password). This satisfies the part of RQ-10 that requires individual credentials.
  • The generic user reports, whose password half the company knew, is removed. Automated processes use their own service accounts, with their credentials stored in a secrets manager, never in the code.

Column-level and row-level security

Table-level permissions are sometimes too coarse.

Column-level security limits which columns of a table a role can read. When the tickets reach the consumption zone (table consumption.fact_tickets, planned in the bus matrix of lesson 02-05), analysts will need them for use case UC-05, but not the free text classified as restricted:

-- The permission on the whole table is withdrawn...
REVOKE SELECT ON consumption.fact_tickets FROM role_analyst;
-- ...and granted only on the allowed columns: all except 'description'
GRANT SELECT (ticket_id, customer_sk, order_id, date_sk, status, subject)
    ON consumption.fact_tickets TO role_analyst;

Row-level security (RLS) limits which rows each user sees within the same table. When consumption.fact_daily_inventory exists, each warehouse manager will have to see only their own:

ALTER TABLE consumption.fact_daily_inventory ENABLE ROW LEVEL SECURITY;

CREATE POLICY own_warehouse_only ON consumption.fact_daily_inventory
    FOR SELECT
    TO role_warehouse_manager
    USING (warehouse_sk IN (SELECT warehouse_sk
                            FROM security.user_warehouse
                            WHERE user_name = current_user));

The USING clause is a filter that the database automatically adds to every query from that role: current_user is the connected user, and the security.user_warehouse table says which warehouses are theirs. The user writes SELECT * FROM ... and receives only their rows, with no way of bypassing the filter.

Encryption and key management

To encrypt is to transform the data with a key so that it is unreadable without it. It is applied at two moments:

Encryption at rest Encryption in transit
Protects Stored data: objects, disks, backups Data while it travels over the network
Against Theft of media, improper access to storage Interception of communications
How Storage encryption (usually AES-256), enabled on the three buckets TLS protocol on all connections, including internal ones
Limit It does not protect against an authorized user: for them, the data is decrypted transparently It does not protect the data once it reaches its destination

Encryption shifts the problem to the keys: whoever has the key has the data. Managing them follows some basic rules:

  • Keys are kept in the cloud provider's key management service (KMS), separate from the data they protect.
  • They are rotated periodically (for example, every year) and their use is logged.
  • Access to the keys is restricted as tightly as access to the most sensitive data.
  • Passwords, API keys and other secrets go in a secrets manager, never in the code or in the repository.

Encryption is no substitute for access control: encrypting the customers table does not prevent an authorized analyst from reading the email addresses. That is what the techniques in the next section are for.

Masking, pseudonymization, anonymization and tokenization

These are four techniques for reducing the exposure of personal data. They are often confused and their legal consequences are very different:

Technique What it does Reversible? Is it still personal data? Typical use
Masking Hides part of the value when displaying it (l***@example.com) The original data is still stored Yes Letting analysts work without seeing identities
Pseudonymization Replaces the identifier with another one (a code or a hash); the link is kept separately or depends on a key Yes, with the additional information Yes: the GDPR treats it as personal data Analyzing behavior per customer without knowing their identity
Tokenization Replaces the value with a token that has no mathematical relationship to it; the mapping lives in a protected vault Yes, by querying the vault Yes Payment data
Anonymization Irreversibly removes the possibility of identifying the person No No, if it is truly irreversible Statistics, open data

Genuine anonymization is harder than it looks: removing the name is not enough if the combination of other attributes (postal code, signup date, infrequent purchases) makes it possible to single out a person.

Masked view for analysts

Requirement RQ-10 asks that analysts see neither the name nor the email. The simplest way is a view that shows the dimension with those columns masked:

CREATE VIEW consumption.v_dim_customer AS
SELECT
    customer_sk,
    customer_id,
    LEFT(name, 1) || '***'                                 AS name,
    LEFT(email, 1) || '***@' || SPLIT_PART(email, '@', 2)  AS email,
    city, signup_date, valid_from, valid_to, is_current
FROM consumption.dim_customer;

GRANT SELECT ON consumption.v_dim_customer TO role_analyst;
  • LEFT(name, 1) takes the first letter and || concatenates text: "Lucía Ferrer" is shown as L***.
  • SPLIT_PART(email, '@', 2) returns what comes after the at sign: [email protected] is shown as l***@example.com. Keeping the domain allows useful analyses (for example, business customers versus individuals).
  • The view keeps the same column names as the table, so a query written against one works against the other.
  • The analyst has permission on the view and not on the table (the REVOKE from the previous section). The view runs with its owner's permissions, so it can read the table even though the analyst cannot.

The view keeps customer_id and city: Laura can count distinct customers or analyze sales by city (UC-01). But be careful: what she sees is still pseudonymized data, not anonymous, and it remains subject to the GDPR.

Salted hash of the email

Sometimes data needs to be matched by email across systems (campaigns and customers) without exposing the address. It is replaced with a hash: a function that turns a text into a fixed-length string from which the original cannot be recovered.

import hashlib
import hmac
import os


def pseudonymize_email(email: str, key: bytes) -> str:
    """Returns a stable pseudonym of the email: same email, same result."""
    normalized = email.strip().lower()     # no spaces and in lowercase
    return hmac.new(key, normalized.encode("utf-8"),
                    hashlib.sha256).hexdigest()


# The secret key (the "salt") is read from the environment, where the secrets
# manager places it. It is never written in the code.
key = os.environ["CLAVE_SEUDONIMIZACION"].encode("utf-8")

print(pseudonymize_email(" [email protected]", key))
print(pseudonymize_email("[email protected]", key))   # same result
  • Normalizing first guarantees that two ways of writing the same email produce the same pseudonym.
  • Why a secret salt? A plain hash (sha256(email)) is easily broken: you only need to compute the hash of a list of known addresses and compare. By mixing the email with a key that the attacker does not have, that comparison is no longer possible. hmac is the standard, secure way of combining key and message.
  • The result is 64 hexadecimal characters, always the same for the same email and the same key, so it works as a join key.
  • Whoever holds the key can recompute the pseudonym of any email: this is pseudonymization, not anonymization. If the key is destroyed, the link is lost.

Auditing and access logging

Access control without a log gives you no way of knowing whether it works. Auditing records who did what, on which data, when, from where and with what result. On DataCorp's platform three logs are enabled: access to the object buckets, the queries run on the analytical engine and permission changes.

For the log to be useful it must meet four conditions:

  • Tamper-proof: it is stored in a separate location where not even the platform administrators can modify it.
  • Retained: DataCorp will keep it for 12 months.
  • Reviewed: a log that nobody looks at deters nobody. Every month, access to restricted data and to the role_personal_data role is reviewed.
  • Proportionate: the log itself contains personal data about employees and must be protected.

A quarterly permission review is added: each owner confirms who should keep access to their domain. It is the way to keep least privilege from eroding over time.

Backups and recovery

Availability comes down to two figures from requirement RQ-08, defined in lesson 01-04: an RPO of 24 hours (at most one day of data is lost) and an RTO of 8 hours (at most one working day is needed to restore service).

The zone-based architecture simplifies the problem: the cleansed and consumption zones can be rebuilt from the raw zone, so the raw zone is what has to be protected at all costs.

Element Protection Reason
Raw zone Object versioning and delete lock; previous versions are kept for 30 days It is irreplaceable (the clickstream exists nowhere else)
Cleansed and consumption zones Versioning for 7 days; rebuilding from the raw zone Derivable; versioning covers recent human error
Code, datasheets, rules and infrastructure as code Repository with a remote copy Makes it possible to recreate the platform
Encryption keys Managed KMS, with deferred deletion Without the key, an encrypted backup is worthless

Three remarks:

  • The most likely threats are not disasters, but accidental deletion and ransomware. Versioning and the delete lock cover them: what has been deleted can be recovered.
  • A backup that has never been restored is an assumption. Every six months a drill will be held: rebuilding one month of the consumption zone from the raw zone and timing it. If it takes more than 8 hours, the RTO is not met and direct backups of the consumption zone will have to be added.
  • ADR-003 placed everything in a single region. The loss of the entire region remains an accepted risk for the first year, to be reviewed with the costs in Module 7. If a second location is added, it must also be in the European Union.

Privacy and the GDPR

The General Data Protection Regulation (GDPR) applies to all processing of data about natural persons in the European Union. Personal data is any information about an identified or identifiable person: the name and the email, but also a customer_id, an IP address or a browsing history associated with an identifier.

Its principles (Article 5) translate into architecture decisions:

Principle What it requires Consequence for the platform
Lawfulness, fairness and transparency Having a legal basis and informing the data subject Each processing activity documents its legal basis
Purpose limitation Not using the data for purposes incompatible with the one it was collected for A new use case on personal data is reviewed before it is built
Data minimization Processing only the data that is necessary Not copying to the platform columns that no use case needs; masking by default
Accuracy Keeping the data correct and up to date Quality rules (lesson 03-03)
Storage limitation Not keeping the data longer than necessary Policy POL-03 and lifecycle rules
Integrity and confidentiality Protecting the data All the controls in this lesson
Accountability Being able to demonstrate compliance Datasheets, ADRs, audit logs

Legal bases. Every processing activity needs to rely on one of the six in Article 6:

Legal basis Possible example at DataCorp
Performance of a contract Managing and delivering an order
Legal obligation Keeping sales documentation for the tax and commercial retention periods
Consent Sending commercial communications; tracking browsing for analytical purposes
Legitimate interests Internal sales analysis; fraud prevention (requires balancing them against the data subject's rights)
Vital interests / Public interest Not applicable to an e-commerce business under normal conditions

The legal basis shapes the architecture: if the clickstream relies on consent, the platform must be able to stop processing the events of anybody who withdraws it. Which basis corresponds to each processing activity is determined by the DPO, not by the data team.

Data subject rights. As a general rule, the organization has one month to respond:

Right What the person can ask for What the platform needs
Access A copy of their data Locating all of a customer's data (lineage and catalog)
Rectification Correcting inaccurate data The correction at the source to propagate
Erasure ("right to be forgotten") Having their data deleted A deletion procedure across all zones
Restriction and objection Restricting or stopping a processing activity Being able to exclude a customer from a process
Portability Receiving their data in a reusable format Structured export

Other obligations that affect the platform:

  • Record of processing activities (Article 30): an inventory of which personal data is processed, for what purpose, on what legal basis, who has access and how long it is kept. The datasheets from lesson 03-01 (personal_data, retention_months, owner) provide a good part of that information.
  • Data protection impact assessment (DPIA, Article 35): a prior analysis that is mandatory when a processing activity entails a high risk, such as large-scale profiling. The analysis of the clickstream per customer (UC-04) or the ticket texts (UC-05) must be submitted to the DPO's judgment before being built.
  • Data protection by design and by default (Article 25): protection is built into the design, not added at the end. It is the fifth principle from lesson 01-04, and it explains why masking is the default option and unmasked access the exception.
  • Breach notification (Article 33): a security breach that poses a risk to individuals must be notified to the supervisory authority within 72 hours at most. Without auditing, it is impossible to know what has been affected.
  • Data residency and international transfers: ADR-003 set an EU region. You also have to keep an eye on the external tools (reporting, catalog, support) that may process the data outside the European Economic Area: an international transfer requires specific safeguards.

The right to erasure on a platform with an immutable raw zone

Two decisions collide here. ADR-002 establishes that the raw zone is an immutable copy; the GDPR may require deleting a person's data that is in it. The solution starts by pinning down the term: the raw zone is immutable with respect to ordinary processes. Erasure under a legal obligation is an exception, with its own restricted, audited procedure.

There are three technical strategies, which DataCorp combines depending on the type of data:

Strategy How it works Where DataCorp applies it
Short retention of the raw copies containing personal data If the copy expires soon, the data erased at the source disappears by itself postgres/customers: it is a daily full load, so keeping 14 days in the raw zone is enough (the history lives in the cleansed zone)
Audited selective rewrite A special process locates the affected files and rewrites them without the person's data support/tickets (3 years of retention, free text)
Separating the identity (pseudonymizing on ingestion) The high-volume data stores only an identifier; once the identity is deleted, it can no longer be attributed clickstream: the events contain only customer_id

The complete procedure, step by step:

  1. Logging and validation. The request is recorded in privacy.erasure_requests with its deadline. The requester's identity is verified, and the DPO determines the scope: there is data that must be kept under a legal obligation (orders, for their 6 years), although detached from the identity as far as possible.
  2. Erasure in the source systems. The store and the support tool anonymize the name and the email. This is each system's responsibility.
  3. Cleansed and consumption zones. On the next load, all the versions of the customer in dim_customer are left with the name Erased customer and a null email, and the affected Parquet files are rewritten. The sales are kept, associated with a customer who is no longer identifiable.
  4. Raw zone. The strategy for each source is applied according to the table above. The previous versions of the rewritten objects also have to be removed: the versioning that protects against accidental deletion preserves precisely what is meant to be deleted.
  5. Verification and closure. The email is searched for in all the datasets that the lineage identifies as destinations of the data, the data subject is answered and the evidence is kept (without the erased data).

This procedure is a starting design that the DPO must validate, in particular whether the treatment given to the clickstream is sufficient. And it leaves an architecture lesson: the fewer places contain the personal data, the easier it is to delete. Minimization simplifies operation too.

ADR-006: access and masking model

ADR-006: Role-based access with individual identities and masking
         of personal data by default
Status: accepted            Date: 2026-11-24

CONTEXT
The credentials for accessing the data are shared and there is no record of
who queries what. RQ-10 requires complying with the GDPR, masking name and
email for analysts and using individual credentials. About 40 users.

DECISION
1. Individual identities linked to the corporate SSO, with multi-factor.
   Shared credentials are removed. Processes use service accounts
   (svc_load, svc_bi) with secrets in a secrets manager.
2. RBAC authorization with five roles: role_data_engineering, role_analyst,
   role_personal_data, role_load_service and role_bi_service. Permissions
   are granted only to roles.
3. Analysts access customers through the view
   consumption.v_dim_customer (name and email masked). Unmasked access
   (role_personal_data) is granted to named individuals, is temporary and
   is approved by the owner of the Customers domain.
4. Columns at the restricted level (description of the tickets) are excluded
   by default through column permissions.
5. Encryption at rest and in transit in all zones; keys in KMS.
6. Access audit log kept for 12 months; monthly review of access to
   restricted data and quarterly review of permissions.
7. Erasure: raw copies of full loads with personal data
   kept for 14 days; audited selective rewrite for the rest.

ALTERNATIVES CONSIDERED
A. ABAC. Rejected for now: unnecessary complexity for 40 users.
B. The engine's dynamic masking instead of views. Deferred until the
   analytical engine is chosen (Module 6); views work on any of them.
C. Not loading name or email into the platform. Rejected: they are needed
   to resolve duplicate customers; masking compensates for it.

CONSEQUENCES
Positive: traceability of every access; minimal exposure of personal
data; compliance with RQ-10.
Negative: the views have to be maintained when the tables change;
exceptional access requires a formal request; the 14-day retention limits
the reprocessing of customers from the raw zone (it qualifies ADR-002).
Pending: validation by the DPO; record of processing activities.

Common Mistakes and Tips

  • Believing that encrypting equals protecting. Encryption stops nothing for somebody with authorized access. Access control and masking are needed as well.
  • Confusing pseudonymizing with anonymizing. A hash of the email is still personal data. Declaring something "anonymous" when it is not is one of the mistakes with the worst consequences.
  • Granting permissions to people instead of roles. Two years later nobody knows why somebody has access to what.
  • Permissions that only grow. Without periodic reviews, every job change accumulates access.
  • Forgetting the copies. Personal data is also in the backups, in the old versions, in the exports to spreadsheets and in the test environments. Never use real unmasked data in testing.
  • Secrets in the code. A password pushed to the repository stays in its history forever; it has to be changed, not just deleted.
  • Leaving privacy until the end. Redesigning a platform to be able to delete a customer is far more expensive than planning for it.
  • Making legal decisions from the technical team. The legal basis, the retention periods and the scope of an erasure are decided by the DPO or the compliance department.
  • Tip: for every column with personal data, ask "which use case needs it?". If there is no answer, do not load it.

Exercises

Exercise 1: Choosing the technique

State which technique (masking, pseudonymization, tokenization or anonymization) corresponds to each situation:

  1. Marketing wants to know how many customers of an external campaign were already DataCorp customers, matching by email, without exchanging the addresses in the clear.
  2. A study with the number of orders by province and month is going to be published.
  3. Support staff must confirm the identity of a caller while seeing only part of their email.
  4. A system must store a reference to the customer's card for refunds, without storing the number.

Exercise 2: Permissions for a new profile

Dani, a digital marketing analyst, needs to analyze campaign profitability (UC-02): sales, products, dates and the customer's city. He also asks for "the list of emails of the customers in Valencia" to send them a promotion. Write the SQL that gives him access and state how you would respond to the second request.

Exercise 3: RPO and RTO

One Thursday at 11:00 a faulty process overwrites the November partition of consumption.fact_sales with wrong data. It is detected at 12:30. With the protections from the lesson, how is it recovered? Is the RPO met? And the RTO?

Solutions

Exercise 1

  1. Pseudonymization with a keyed hash agreed between both parties: each one computes the pseudonym of its emails and the pseudonyms are matched. It is still processing of personal data and requires a legal basis.
  2. Anonymization through aggregation. Careful: a cell with one or two orders in a small province may identify somebody; it is best to set a minimum per cell.
  3. Masking.
  4. Tokenization.

Exercise 2

CREATE ROLE dani LOGIN;
GRANT role_analyst TO dani;

Nothing else is needed: role_analyst already reads fact_sales, dim_product, dim_date and the v_dim_customer view, which includes the city. Creating a specific role for Dani would be the mistake of granting permissions to people.

To the second request, the answer is not this way. Sending promotions requires a legal basis (normally consent) and the analytical platform is not the system from which communications are sent. The right approach is for the platform to deliver the segment (identifiers of the customers in Valencia) to the marketing tool and for that tool, which manages consents, to do the sending. Dani does not need to see the emails at any point.

Exercise 3

There are two routes: restoring the previous versions of the partition's files (the consumption zone's versioning keeps them for 7 days), or rebuilding the partition from the cleansed and raw zones, which have not been affected. The first is a matter of minutes.

  • RPO: met. The data is recovered to the state of the last correct load, the one from the early hours of that day. Nothing is lost.
  • RTO: met if the restore finishes before 20:30 (8 hours after detection). With versioning, comfortably.

Reflection: detection took 90 minutes because somebody saw strange figures. A check such as the DQ-08 reconciliation from lesson 03-03, run before publishing, would have prevented the wrong data from reaching the consumption zone.

Conclusion

Security protects the data and privacy protects people. The former is organized around confidentiality, integrity and availability, and takes shape in controls proportionate to the classification: individual authentication, role-based authorization with least privilege, column and row permissions, encryption with well-managed keys, masking and pseudonymization, auditing and tested backups. The latter is shaped by the GDPR: legal basis, minimization, limited retention, data subject rights and the ability to demonstrate compliance. DataCorp replaces its shared credentials with individual identities and five roles, offers analysts the consumption.v_dim_customer view with name and email masked, and has a procedure for honoring the right to erasure even in its raw zone. All of it is captured in ADR-006, pending validation by the DPO.

With governance, the catalog, quality and security defined, the cross-cutting layers of the architecture are no longer empty. What remains to be solved is how the data gets to the platform: five sources with different technologies, formats, identifiers and paces that have to be brought together consistently. That is the problem of data integration, which we tackle in the next lesson.

© Copyright 2026. All rights reserved