Verdalia now controls who gets in and what they can do. But access controls fail, and then what matters is what whoever gets past them finds. Seven of the sixteen threats in the register were information disclosure, and the store's most valuable asset is the data of its 38,000 customers. In this lesson you will learn to classify data and to know where it is, to protect it with encryption in transit and at rest, to manage keys, to reduce what is stored, and to decide how long it is kept. You will also meet, at an introductory level, the legal framework that requires all of this. Verdalia will take its data inventory and find personal data in three places where nobody expected it.
A warning that is especially important in this lesson: what follows is a technical introduction, not legal advice. The retention periods, the legal bases, and the specific obligations depend on each case. In a real system, they must be reviewed with a security professional and with legal and compliance advice (GDPR, PCI DSS).
Data Classification and Inventory
Classifying
Not all data deserves the same protection. Classifying it lets you spend the effort where it matters:
| Level | What it includes | Example in Verdalia | If it leaks |
|---|---|---|---|
| Public | What is already published | Product pages, prices, images | Nothing |
| Internal | What is not published, but causes no serious harm | Stock, supplier prices | Advantage for a competitor |
| Confidential | Secrets of the business and the system | Credentials, encryption keys, margins | Serious, direct harm |
| Personal | Any information about an identified or identifiable person | Name, email, phone, address, orders | Harm to customers, legal obligations, and possible penalties |
| Especially sensitive | Categories the law protects with extra safeguards, such as health, ideology, or sexual orientation; and payment data | Verdalia does not ask for them | Very serious harm |
Two observations. A piece of data is personal even if it does not carry the name: an IP address or a customer identifier is, if it allows reaching the person. And free-text fields are unpredictable: in a gift message, a customer may write “for Mom, get well soon after the operation.” Verdalia does not ask for health data, but it has it.
Taking Inventory
In Module 3 we drew Verdalia's data map, to decide which data store suited each piece of data. Now we go over it with another question: which personal data is in each place.
| Data store | Data | Level | Was it known? |
|---|---|---|---|
PostgreSQL: customers |
Name, email, phone, addresses, password hash | Personal | Yes |
PostgreSQL: orders and order_items |
What each customer bought, delivery address and notes, gift message | Personal, with free text | Yes |
PostgreSQL: products, categories, stock |
Catalog and stock | Public and internal | Yes |
| Redis | Sessions and carts; catalog cache | Personal; public | Yes |
| RabbitMQ | Messages with the customer's email and the amount | Personal, in transit | Yes |
notification-service data store |
Customer's email, order, and status of each notification | Personal | Yes |
| Object storage and CDN | Product images | Public | Yes |
| PagoRaíz | Card data. Verdalia only stores the transaction identifier | Especially sensitive, outside Verdalia | Yes |
| Nightly backups | Everything in PostgreSQL | Personal | Yes, unassessed |
| Activity logs of the 3 application servers | Email and delivery address of every confirmed order | Personal | No |
Queue emails.failed |
Messages that could not be sent, with no expiration | Personal | No |
verdalia-test-01 |
Full copy of production, used in the March load tests | Personal | No |
The last three findings have the same origin. Data gets copied: to a log for debugging, to a queue, to a test environment. Each copy inherits the classification of the original, but not its protection.
Encryption Fundamentals
Encrypting means transforming data so that only whoever has the key can read it. An architect does not need to know the math, but does need to tell four tools apart:
| Tool | How it works | What it is for | Examples |
|---|---|---|---|
| Symmetric encryption | The same key encrypts and decrypts | Encrypting data, at rest and in transit. It is fast | AES, ChaCha20 |
| Asymmetric encryption | A key pair: what the public key encrypts, only the private key decrypts | Agreeing on keys with a stranger; signing. It is slow | RSA, elliptic curves |
| Hash function | Turns any data into a fixed-size digest, with no way back | Checking integrity; storing passwords, with the slow functions from the previous lesson | SHA-256 |
| Digital signature | Signed with the private key and verified with the public key | Proving origin and integrity. Provides non-repudiation | Certificate signatures |
The HMAC from the previous lesson is the symmetric equivalent of the signature: it proves origin and integrity, but between two parties that share the key.
Real systems combine the two families. Asymmetric encryption solves the problem of agreeing on a key with someone you have never spoken to; symmetric encryption, which is much faster, encrypts the data with that key. And one rule without exceptions: algorithms are used through maintained libraries. They are never invented or reimplemented.
Encryption in Transit
TLS is the protocol that protects communications. It lies behind HTTPS, and it can also protect the connections to the database, to Redis, or between services.
| Guarantees | How |
|---|---|
| Confidentiality | Nobody along the way can read the data |
| Integrity | Nobody along the way can alter it unnoticed |
| Server authenticity | The client checks that it is talking to whom it thinks |
It guarantees nothing about the endpoints. If the server is compromised, TLS delivers the data, nicely encrypted, to whoever should not have it.
A certificate binds a domain name to a public key, and it is signed by a certificate authority that browsers trust. On connecting, the client checks three things: that the certificate matches the name it asked for, that it has not expired, and that a trusted authority signed it. The most frequent failures are operational:
- Expired certificates. They cause a complete outage and can be foreseen. Renewal must be automatic, and the expiration date, monitored.
- Verification disabled in the code, “because it gave an error in testing.” A client that does not verify the certificate encrypts the data for anyone.
- Old versions of the protocol. Today, TLS 1.2 and 1.3 are accepted.
In Verdalia, the traffic between the customer and the load balancer is encrypted, as are the calls to PagoRaíz. The internal traffic is not. We will decide that in the next lesson.
Encryption at Rest
| Level | What is encrypted | Protects against | Does not protect against |
|---|---|---|---|
| Disk or volume | The whole disk. It is transparent to applications | Theft or reuse of the disk | Anyone who gets into the running machine: the disk is decrypted |
| Database | The database files | Access to the files and to physical copies | Anyone who connects to the database with a valid user |
| Field | Specific fields, which the application encrypts before storing them | All of the above, plus anyone who reads the table, a dump, or a backup | Anyone who compromises the application, which has the key |
The levels add up: it is defense in depth. Field-level encryption is the strongest and the most expensive: an encrypted field cannot be searched or sorted in the database, and every read requires decrypting. That is why it is reserved for a few fields.
Backups are encrypted too. A backup contains the same as the database, and it is usually less protected and in more places.
Key Management
Encrypting moves the problem: you no longer have to protect the data, but the key. Correct encryption with a badly stored key protects nothing.
| Principle | Meaning |
|---|---|
| Separate the key from the data | They must not be in the same place. A copy of the database must not include the key that decrypts it |
| Limit who has access | The key is the most confidential piece of data in the system |
| Rotate | Keys are replaced periodically and on any suspicion. The system must be able to read with the old one while re-encrypting with the new one |
| Keep a copy of the key | Losing the key is losing the data. Confidentiality competes here with availability |
| Do not reuse | One key for each purpose and for each environment |
Envelope encryption solves rotation when there is a lot of data. Each piece of data is encrypted with a data key, and this key is stored, encrypted with a master key, next to the data. The master key lives in a key management service and never leaves it. Rotating the master key requires re-encrypting the data keys, which are small, and not the data.
flowchart LR
master["Master key, in the key service"] -->|"encrypts"| data_key["Data key"]
data_key -->|"encrypts"| value["Data"]
data_key -.->|"stored encrypted, next to the data"| store[("Data store")]
value -.-> store
Cloud platforms offer key management as a service, and we will come back to it in Module 6. Verdalia, with three encrypted fields, keeps its keys in the environment file from ADR-007.
Minimization, Pseudonymization, and Anonymization
The best-protected data is the data you do not have.
| Technique | What it consists of | Is it still personal data? |
|---|---|---|
| Minimization | Collect and store only what is necessary for the stated purpose | Yes, but there is less of it |
| Masking | Hide part of the data when displaying or logging it | Yes: the original still exists |
| Pseudonymization | Replace the identifier with another one. With additional information, kept separately, you can get back to the person | Yes |
| Anonymization | Transform the data so that nobody can be identified anymore, irreversibly | No |
Anonymization is harder than it looks. Removing the name is not enough: the postal code, the date, and the amount of an order can point to a single person. Aggregated data, such as sales by province and by month, is safer than nameless individual data.
Masking has two main uses:
- In the activity logs. A log needs to know that an email was sent, not to whom. Logs are copied and kept with less care than the database.
- In test environments. A test environment must not contain real customer data. It has less protection, more people with access, and, in Verdalia's case, it lives on machines rented by the day. The options are to generate synthetic data or to mask a copy before it leaves production.
Retention and Deletion
Keeping data “just in case” is not an option: personal data is kept as long as it is necessary for the purpose it was collected for, or as long as a law requires keeping it. Each type of data needs a retention period and a mechanism that enforces it. The periods in this table are the ones Verdalia set with its advisors, and they cannot be carried over to another case:
| Data | Period | Mechanism |
|---|---|---|
| Sessions | 30 minutes without activity | Expiration in Redis |
| Carts | 30 days | Expiration in Redis |
Messages in emails.failed |
7 days | Expiration in the queue |
| Activity logs | 90 days | Automatic rotation and deletion |
| Sent notifications | 1 year | Monthly scheduled job |
| Audit log | 2 years | Monthly scheduled job |
| Inactive accounts | 3 years; prior notice by email | Monthly scheduled job |
| Orders and invoices | The period required by commercial and tax regulations; afterwards they are anonymized | Yearly scheduled job |
Two difficulties. Truly deleting is hard in a system with replicas, caches, and backups: the data removed from the database is still in the backups until they expire, and that must be foreseen and documented. And a manual mechanism does not run: if deletion depends on someone remembering, it will not happen.
Legal Framework: GDPR and PCI DSS
GDPR
The General Data Protection Regulation applies to the processing of personal data of people who are in the European Union. In Spain it is complemented by the organic law on data protection. Its principles translate into architecture requirements:
| Principle | What it requires | Consequence for the design |
|---|---|---|
| Lawfulness, fairness, and transparency | A legal basis for each processing activity, and clear information | Knowing what is processed and what for: the inventory |
| Purpose limitation | Not using the data for purposes other than the stated ones | Separating the data by use |
| Minimization | Only the necessary data | Reviewing every field of every form |
| Accuracy | Correct, up-to-date data | Allowing rectification |
| Storage limitation | Not keeping it longer than necessary | Retention periods and automatic deletion |
| Integrity and confidentiality | Security appropriate to the risk | This whole module |
| Accountability | Being able to prove compliance | Documentation, auditing, and ADRs |
People have rights that the system must be able to honor, within set deadlines: access to their data, rectification, erasure, restriction of processing, portability, and objection. For the architecture, this means being able to locate all of a person's data, in every data store, and export or delete it. With the data spread across six places, it is not trivial.
There are three other obligations with a direct effect on the design: notifying security breaches to the supervisory authority, within 72 hours where applicable; signing a contract with every provider that processes data on the company's behalf; and applying data protection by design and by default.
PCI DSS
PCI DSS is the security standard of the payment card industry. It is not a law: it is a contractual obligation for anyone who stores, processes, or transmits card data. Its requirements are many and demanding, and they apply to every system that touches that data, which make up the scope.
Verdalia's strategy, since before this course began, is to reduce the scope. The customer types their card details on a PagoRaíz page, and the store only receives the result and a transaction identifier. Card data never passes through Verdalia's servers. It is the treatment we called transfer in the risk register, and it has two nuances: the scope is reduced, but it does not disappear, because the store is still responsible for the page that sends the customer to the gateway; and the store must never log or store a card number, not even by mistake in a free-text field.
Access Control, Auditing, and Caching
Who Accesses the Data
Least privilege applies to people too. Module 1 set the goal: only those who need it access production data.
| Who | Before | Now |
|---|---|---|
| The store | User store, owner of everything |
store_app, with the module roles |
| Business reports | User store |
reports, read-only, on de-identified data |
| Íker | Direct access, as the user store |
No routine access. He works with synthetic data and intervenes in production only in planned procedures, with a personal user and logging |
| Lucía and Marta | Direct access | Access with a personal user, logged |
| Customer support | Panel, with every permission | Panel, with their role. The phone number is shown on click, and the lookup is logged |
Auditing
An audit log records who accessed what, when, from where, and with what result. It is a detective control, and it is what makes it possible to answer, after an incident, the question the supervisory authority will ask: which data was accessed.
- Accesses to personal data, permission changes, exports, and denied accesses are logged.
- The log does not contain the data looked up, only its reference: “carmen looked up the phone number of customer 501.”
- Whoever is audited must not be able to modify it. In Verdalia,
store_apphasINSERTpermission on theaudit_logtable, but notUPDATEorDELETE. - A log nobody reviews detects nothing. Lucía reviews a weekly summary, until alerts exist.
What Is Cached and What Is Not
In Module 4 we left the caching policy for personal data pending:
| Data | Redis cache | CDN and browser |
|---|---|---|
| Product pages, listings, and categories | Yes, with the keys from Module 4 | The pages do not go through the CDN |
| Images and static files | Not needed | Yes |
| Pages with customer data: account, orders, cart | No | Cache-Control: no-store |
| Admin panel | No | Cache-Control: no-store |
| Sessions | They are in Redis, as a data store and not as a cache | No |
The rule is that the keys of the shared cache contain no personal data, and no personalized response is stored outside the server. The session holds the customer's identifier, not their name or address.
Encryption, Masking, and Pseudonymization in Python
The example uses the cryptography library, installed with pip install cryptography. Fernet is one of its recipes: authenticated symmetric encryption, with few decisions to make.
import hashlib
import hmac
import re
from cryptography.fernet import Fernet, InvalidToken, MultiFernet
# 1. Encrypting a field
key_2026 = Fernet.generate_key() # in production it comes from the environment
cipher = MultiFernet([Fernet(key_2026)])
encrypted = cipher.encrypt("600123456".encode())
print("1. In the database:", encrypted[:6].decode() + "...", f"({len(encrypted)} characters)")
print(" Decrypted by the store:", cipher.decrypt(encrypted).decode())
print(" Same value, different ciphertext:", cipher.encrypt("600123456".encode()) != encrypted)
tampered = encrypted[:-4] + b"AAAA"
try:
cipher.decrypt(tampered)
except InvalidToken:
print(" Tampered value: rejected")
# 2. Key rotation
key_2027 = Fernet.generate_key()
transition = MultiFernet([Fernet(key_2027), Fernet(key_2026)]) # the first encrypts; all decrypt
print("2. Old value, read during the transition:", transition.decrypt(encrypted).decode())
re_encrypted = transition.rotate(encrypted) # re-encrypted with the new key
final = MultiFernet([Fernet(key_2027)]) # the 2026 key is retired
print(" Re-encrypted value, read with the new key:", final.decrypt(re_encrypted).decode())
try:
final.decrypt(encrypted)
except InvalidToken:
print(" Value not re-encrypted, with the new key: unreadable")
# 3. Masking in the activity logs
def mask_email(email):
user, _, domain = email.partition("@")
return f"{user[0]}***@{domain}"
def mask_phone(phone):
return "*" * (len(phone) - 3) + phone[-3:]
def mask(message):
message = re.sub(r"[\w.+-]+@[\w.-]+\.\w+", lambda m: mask_email(m.group()), message)
return re.sub(r"\b\d{9}\b", lambda m: mask_phone(m.group()), message)
print("3.", mask("Order 1042 confirmed for [email protected], phone 600123456"))
# 4. Pseudonymization
def pseudonym(value, key):
digest = hmac.new(key, value.strip().lower().encode(), hashlib.sha256).hexdigest()
return f"cus_{digest[:12]}"
PSEUDONYM_KEY = b"sample-key-not-real"
for email in ("[email protected]", "[email protected] ", "[email protected]"):
print(f"4. {mask_email(email.strip())} -> {pseudonym(email, PSEUDONYM_KEY)}")
print(" With another key:", pseudonym("[email protected]", b"another-key"))Output:
1. In the database: gAAAAA... (100 characters) Decrypted by the store: 600123456 Same value, different ciphertext: True Tampered value: rejected 2. Old value, read during the transition: 600123456 Re-encrypted value, read with the new key: 600123456 Value not re-encrypted, with the new key: unreadable 3. Order 1042 confirmed for a***@mail.example, phone ******456 4. a***@mail.example -> cus_64984d6fd0d3 4. A***@mail.example -> cus_64984d6fd0d3 4. l***@mail.example -> cus_eb9555eee5d4 With another key: cus_a0e3e7891a82
Explanation:
Fernet.generate_key()creates a random key. In the store, the keys come from the environment variableVERDALIA_FIELD_KEYS, which contains a list: the first one encrypts, and all of them decrypt.- The result of encrypting the same value twice is different, because each encryption includes a random value. That way, whoever reads the table cannot tell that two customers share a phone number. The consequence is that you cannot search by an encrypted field.
- The encryption is authenticated: if someone modifies the encrypted value,
decryptraisesInvalidTokeninstead of returning a wrong result. It protects confidentiality and integrity. MultiFernetis zero-downtime rotation, the same idea we applied to the credentials in ADR-007: for a while, two keys are valid.rotatedecrypts with whichever key applies and encrypts with the first one. A job walks through the table and, when it finishes, the old key is retired.maskuses regular expressions to locate emails and phone numbers inside any message. It is a safety net: the right thing is for the code not to write the data to the log at all. Regular expressions do not find a postal address or a name.pseudonymapplies an HMAC. The same email always gives the same pseudonym, so reports can count orders per customer without knowing who they are. It is normalized first, withstripandlower, so that two ways of writing the same email match.- HMAC is used, and not a keyless hash, because emails can be guessed. With a plain hash, computing the hash of a known email is enough to locate that person in the reports. With another key, the pseudonym is different. The key is the “additional information” that must be kept separately.
Verdalia: The April 20 Deployment
On Tuesday, April 20, the changes from this lesson were deployed:
| Measure | Detail | Threat or origin |
|---|---|---|
| Field-level encryption | phone, delivery_notes, and gift_message, with Fernet. The keys are on the application servers, not on the database servers |
Reduces the impact of any leak of the table or of a backup |
| Activity logs | No emails or addresses; mask filter as a safety net; 90 days of retention. The earlier logs were deleted |
TH-07 |
| Business reports | View with pseudonyms and no contact data, for the user reports |
TH-13 |
| Customer export | Feature removed from the panel | TH-13 |
| Auditing | audit_log table, insert-only |
TH-12 |
| Caching | Cache-Control: no-store on the account, orders, cart, and panel pages |
Pending from Module 4 |
Queue emails.failed |
7-day expiration | Inventory finding |
| Test environment | Synthetic data, generated by a program: 38,000 fictitious customers and 15,000 products. In use since the April 6 load test | Inventory finding |
Three decisions deserve comment:
- Three fields are encrypted, not all of them. The name, email, and address are used for searching and for preparing shipments, and encrypting them would have meant redoing the panel. They remain protected by permissions, by the network, and, when it arrives, by disk encryption. It is a residual risk, written down.
- Disk encryption is postponed. Enabling it on the database machines requires reinstalling them, with downtime nobody wants during the campaign. It will be done in the move to the cloud. In the meantime, threat TH-16, physical theft, remains accepted.
- The production copy in the test environment no longer existed. The machine was rented by the day and returned in March. Verdalia cannot check how that disk was wiped. Marta wrote it down in the risk register and consulted the data protection advisors. There were no signs of access, but the lesson was learned: real data does not leave production.
Common Mistakes and Tips
- Encrypting and storing the key next to the data. It is a lock with the key left in it.
- Considering data protected because the disk is encrypted. Disk encryption does not protect against whoever gets in through the application.
- Forgetting the copies of the data. Logs, queues, caches, test environments, spreadsheets, and backups contain the same data with less protection.
- Confusing pseudonymizing with anonymizing. Pseudonymized data is still personal, with all its obligations.
- Keeping everything. Every piece of data kept without need is a risk with no upside.
- Disabling certificate verification. Encryption without authentication does not protect against whoever steps into the middle.
- Designing without thinking about people's rights. Locating and deleting a customer's data must be a planned operation, not an investigation.
- Practical tip. Search for your own email in every data store, log, and backup of the system. What you find is your real inventory.
Exercises
Exercise 1: Classify and Decide
For each piece of data, state its classification level and which main measure you would apply:
- The date of birth that a registration form asks for “to congratulate the customer.”
- The Nginx log, which stores the IP address and the page visited on every request.
- The price list of Verdalia's suppliers.
- Product reviews, published with the customer's first name.
Exercise 2: Right to Erasure
A customer asks Verdalia to delete all her data. She placed three orders, the last one four months ago. List the data stores that must be reviewed and what you would do in each one. Can everything be deleted?
Solutions
Solution to Exercise 1
- Personal. Minimization: if the only purpose is to congratulate, the day and month are enough, and the field must be optional. It is the most frequent mistake: asking for data because the form allows it.
- Personal, because the IP address allows reaching a person. Short retention and restricted access. Field-level encryption is not needed.
- Internal or confidential. Access control: it must not be in tables the whole application reads.
- Personal, though public by the customer's decision. Transparency: they must have consented to the publication, and they must be able to withdraw it.
Solution to Exercise 2
| Data store | Action |
|---|---|
customers |
Delete the account |
orders |
They cannot be deleted while the legal obligation to keep invoices lasts. They are kept with the minimum data and their use for other purposes is blocked |
| Redis | Delete the session and the cart |
notification-service |
Delete her notifications |
| Queues | Review emails.failed |
| Activity logs | Since April 20 they do not contain her data |
| Audit log | Kept: it contains references, not data |
| Backups | Not modified. They expire according to their policy, and if one is restored, the deletion must be applied again |
| Email provider | Request erasure, if it keeps data |
Not everything can be deleted immediately: the right to erasure coexists with the legal obligations to retain. What must be possible is to answer precisely what has been deleted, what is kept, why, and until when. The backups case teaches that you need a list of pending erasures, to be applied again after a restore. A real case must be resolved with legal advice.
Conclusion
In this lesson you have learned to classify data and to take inventory of it, including the copies nobody remembers. You have told apart symmetric and asymmetric encryption, hash functions, and signatures. You have seen what TLS guarantees and what it does not, and the three levels of encryption at rest, each with what it protects and what it leaves out. You have learned that encrypting moves the problem to the key, and that the best-protected data is the data you do not store: minimize, pseudonymize, mask, and delete on time. And you have met the principles of the GDPR, people's rights, and the reason Verdalia leaves card data in PagoRaíz's hands.
In Verdalia, the inventory found personal data in the activity logs, in a queue with no expiration, and in a test environment. Since April 20 there are three encrypted fields, logs without personal data, an audit log, retention periods, and synthetic data for testing.
Almost every measure in this lesson and the previous one rests on an assumption: that only those who should reach the database, Redis, and the environment files do so. Today the eight machines share a network on which they can all see one another, the panel is still exposed to the internet, and internal traffic travels unencrypted. That is the subject of the next lesson: “Network Security and Zero Trust Architecture.”
