Data Pipeline Security: Encryption, Masking, GDPR
Difficulty: Senior Level | Companies: Stripe, PayPal, Amazon, Google, Microsoft
Security failures in data engineering are rarely dramatic. Nobody cracks a cipher in a movie. Instead a bucket policy is left permissive, a service account accumulates read access to every table, a copied production extract sits in a developer's scratch space for eight months, and an erasure request is answered with a promise rather than a delete. The work of securing a pipeline is mostly the work of making those ordinary mistakes hard to make.
Prerequisites
- !Object storage identity and access management
- !Relational permissions and views
- !How Spark jobs read and write partitions
What You'll Learn
- 1Layer network, identity, encryption and masking controls deliberately
- 2Implement envelope encryption with a managed key service
- 3Apply row-level and column-level policies at query time
- 4Fulfil data subject access and erasure requests across a lake
Defense in depth, layer by layer
No single control protects a warehouse. Network isolation keeps traffic inside a private boundary, identity and access management decides which principals may reach a resource, encryption protects the bytes at rest and in transit, and masking or tokenization limits what a human sees once they are inside. Each layer fails differently, so the combination is what matters.
The practical ordering matters too. Encryption is applied by the storage engine with almost no developer effort, so it is cheap insurance and should be on everywhere by default. Access control requires deliberate modelling and review, so it is where teams should spend design time. Masking sits closest to the user and is the only layer that protects data from people who legitimately have read permission, which makes it the difference between a data platform that analysts trust and one they work around by exporting everything to spreadsheets.
| Layer | Protects against | Typical mechanism | Cost to adopt |
|---|---|---|---|
| Network | Off-account access | Private endpoints, security groups | Low, mostly configuration |
| Identity | Wrong principal reaching data | Roles, policies, short-lived credentials | Medium, needs review |
| Encryption at rest | Storage or backup theft | AES-256 with managed keys | Low, often default |
| Encryption in transit | Sniffing between services | TLS 1.2 or newer, mutual TLS internally | Low |
| Row level security | Cross-tenant or cross-region reads | Predicate pushed into every query | Medium, needs modelling |
| Column level masking | Over-broad human access | Dynamic masking, tokenization | Higher, needs classification |
Envelope encryption and who holds the keys
Never encrypt data directly with the master key. Instead generate a unique data encryption key, encrypt the payload with it, then encrypt that data key with a master key held in a managed key service. This pattern, called envelope encryption, means rotating the master key does not require rewriting petabytes, and a leaked data key alone is useless without the master key that wraps it.
import base64
import hashlib
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
class EnvelopeEncryptor:
def __init__(self, master_key: bytes):
self.master_key = master_key
def derive_data_key(self, salt: bytes) -> bytes:
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=480000,
)
return base64.urlsafe_b64encode(kdf.derive(self.master_key))
def encrypt_value(self, plaintext: str, data_key: bytes) -> dict:
cipher = Fernet(data_key)
return {
"ciphertext": cipher.encrypt(plaintext.encode()).decode(),
"key_fingerprint": hashlib.sha256(data_key).hexdigest()[:16],
"algorithm": "AES-256-GCM",
}
def decrypt_value(self, payload: dict, data_key: bytes) -> str:
cipher = Fernet(data_key)
return cipher.decrypt(payload["ciphertext"].encode()).decode()
def rotate_data_key(envelope: EnvelopeEncryptor, record: dict, kms) -> dict:
plain = envelope.decrypt_value(record["value"], record["data_key"])
new_key = Fernet.generate_key()
record["value"] = envelope.encrypt_value(plain, new_key)
record["data_key"] = kms.encrypt(new_key)
return record
Two operational rules follow from this design. First, the plaintext data key must live only in memory for the duration of the operation and never be written to a log or a checkpoint. Second, every wrapped key needs a fingerprint stored alongside the ciphertext, because after a rotation you must know which records still depend on the previous master key before you can retire it.
Encrypting a column inside a Spark job
Column-level encryption is where the theory meets your existing pipelines. Register encryption and decryption as user-defined functions, apply encryption only to the columns classified as sensitive, and write the encrypted form alongside a stable key fingerprint so decryption can pick the right key later. Leave non-sensitive columns in the clear: encrypting everything destroys query performance and prevents the pruning that makes columnar storage worth using.
import json
from cryptography.fernet import Fernet
from pyspark.sql.functions import udf
from pyspark.sql.types import StringType
@udf(returnType=StringType())
def encrypt_pii(value, data_key):
if value is None:
return None
payload = Fernet(data_key.encode()).encrypt(value.encode()).decode()
return json.dumps({"ciphertext": payload, "algorithm": "AES-256-GCM"})
@udf(returnType=StringType())
def decrypt_pii(payload_json, data_key):
if payload_json is None:
return None
ciphertext = json.loads(payload_json)["ciphertext"]
return Fernet(data_key.encode()).decrypt(ciphertext.encode()).decode()
key = kms_generate_data_key(MASTER_KEY_ID)
secured = df.withColumn("email_encrypted", encrypt_pii(F.col("email"), F.lit(key)))
secured.write.format("parquet").save("s3://secure-data/users/")
Treat the master key as configuration injected at runtime from a secret manager, never as a literal in the job definition. Anyone with read access to the repository or the job configuration should still be unable to read a protected column.
Row and column level access control
Encryption protects stored bytes; access control protects query results. Row-level security injects a predicate into every query so a regional manager only sees their region, while column-level security filters or nulls out columns whose classification exceeds the caller's clearance. Both must be enforced by the engine rather than by application code, because any path that bypasses your application is a path that bypasses the policy.
class AccessPolicyEngine:
def __init__(self):
self.row_filters = {}
self.classifications = {}
self.role_grants = {}
def add_row_filter(self, table: str, role: str, predicate: str) -> None:
self.row_filters.setdefault(table, []).append((role, predicate))
def classify(self, table: str, column: str, label: str) -> None:
self.classifications[f"{table}.{column}"] = label
def grant(self, role: str, labels: set) -> None:
self.role_grants[role] = labels
def secure_query(self, table: str, role: str, projection: list) -> str:
allowed = self.role_grants.get(role, set())
columns = []
for column in projection:
label = self.classifications.get(f"{table}.{column}", "public")
columns.append(column if label in allowed else f"NULL AS {column}")
predicates = [
p for r, p in self.row_filters.get(table, []) if r == role
]
where = f" WHERE {' AND '.join(predicates)}" if predicates else ""
return f"SELECT {', '.join(columns)} FROM {table}{where}"
Deny by default. A role that appears in no grant list should see nothing, and new columns should inherit the most restrictive classification until someone deliberately lowers it. Silent inclusion of an unclassified column is how personal data reaches an analytics environment by accident.
Honouring erasure requests across a lake
Regulations such as GDPR and CCPA give individuals the right to see what you hold about them and to have it deleted. In a warehouse that is one statement. In a lake with partitioned copies, search indexes, downstream marts and ML feature stores, it is a distributed operation that needs a catalog capable of finding every dataset containing a given identifier.
class ErasureHandler:
def __init__(self, catalog, spark):
self.catalog = catalog
self.spark = spark
def handle(self, subject_id: str) -> dict:
report = {"deleted": [], "anonymized": [], "failed": []}
for dataset in self.catalog.find_containing(subject_id):
try:
if dataset.hard_delete_allowed:
self.spark.sql(
f"DELETE FROM {dataset.name} WHERE subject_id = '{subject_id}'"
)
report["deleted"].append(dataset.name)
else:
self.spark.sql(
f"UPDATE {dataset.name} SET subject_id = 'REDACTED', "
f"email = NULL, name = 'REMOVED' "
f"WHERE subject_id = '{subject_id}'"
)
report["anonymized"].append(dataset.name)
except Exception as exc:
report["failed"].append({"dataset": dataset.name, "error": str(exc)})
return report
def export_subject(self, subject_id: str) -> dict:
payload = {}
for dataset in self.catalog.find_containing(subject_id):
payload[dataset.name] = self.spark.sql(
f"SELECT * FROM {dataset.name} WHERE subject_id = '{subject_id}'"
).collect()
return payload
Prefer hard deletion where referential integrity allows it, and anonymization only where a foreign key relationship would be broken by removing the row. Record the outcome for every dataset, because the evidence of what you deleted is itself something a regulator will ask to see.
What auditors actually ask for
Auditors rarely ask whether you use AES-256. They ask who can read the data, how you know, what happens when a key is compromised, how long a deleted record survives in backups, and which report proves that last month's access reviews were completed. Answer those five questions with artifacts rather than assurances: a policy export, an access review log, a key rotation record, a backup retention schedule, and a signed review.
The cheapest way to stay ready is to keep the evidence generation automated. Every policy change should emit an audit event, every key operation should be logged by the key service, and every erasure request should produce a completion report. When the artifacts are produced by the same systems that enforce the controls, they cannot drift from reality.
The same principle applies to development environments. A masked copy of production is still sensitive if the masking is reversible or if a foreign key lets someone join back to an identifiable row. Generate non-production datasets through a documented masking job, refresh them on a schedule, and store them in an account whose network boundary already excludes the public internet.
đLeast privilege is a moving target
Revoke permissions when a project ends, not when someone leaves the company. Quarterly access reviews should compare actual query history against granted permissions and remove anything unused for ninety days.
Common Mistakes
Encrypting data with the master key directly
Fix: Encrypt with a per-record data key and wrap that key with the master key
Storing the master key in job configuration or source control
Fix: Inject keys at runtime from a managed key service with audited access
Relying on application code to filter rows
Fix: Enforce row and column policies inside the query engine so no path bypasses them
Answering an erasure request from one table only
Fix: Drive deletion from the catalog so every containing dataset is processed and reported
Best Practices
- Turn on encryption at rest and in transit everywhere before anything else
- Classify columns at ingestion time and let new columns default to the strictest label
- Keep plaintext data keys in memory only and never in logs or checkpoints
- Automate access reviews against actual query history rather than static group membership
- Produce an erasure completion report that lists every dataset touched
Interview Questions
Q1: What is envelope encryption and why is it preferred?
Data is encrypted with a unique data key, and that data key is encrypted with a master key held in a managed service. It lets you rotate the master key cheaply and limits the blast radius if a single data key leaks.
Q2: How would you implement row-level security in a shared warehouse?
Define a predicate per role on the table and have the engine append it to every query, defaulting to no rows for unknown roles, with policies stored as versioned objects and applied centrally.
Q3: Encryption at rest versus in transit, which do you start with?
Both, since both are configuration-level, but in transit first because it also protects credentials and intermediate results in addition to the stored payload.
Q4: How do you delete a user across a data lake with downstream marts?
Use the catalog to enumerate every containing dataset, hard delete where integrity allows, anonymize where it does not, then invalidate or rebuild downstream aggregates and emit a completion report.
Q5: How do you handle key rotation without downtime?
Store a key fingerprint with each ciphertext, support decrypting with any non-retired key, rewrite records in the background in small batches, then retire the old key once the fingerprint count reaches zero.
Key Takeaways
- Security is layered; encryption is cheap, access modelling is where design time belongs
- Envelope encryption keeps rotation affordable and limits key exposure
- Encrypt only classified columns so query performance survives
- Policies must live in the query engine, never only in application code
- Erasure is a distributed operation driven by the catalog, not a single delete
- Auditors want artifacts, so generate evidence from the enforcing systems automatically