--- title: "Copy Production Data to Dev Without Leaking Real Users' Data" author: "Anshu Pathak" published: "2026-12-02T04:46:18.394Z" updated: "2026-12-02T04:46:18.394Z" url: "https://zyvop.com/copy-production-data-to-dev-without-leaking-real-users-data-ydank" canonical: "https://zyvop.com/copy-production-data-to-dev-without-leaking-real-users-data-ydank" tags: ["Python","security","data privacy","DevOps","database"] --- # Copy Production Data to Dev Without Leaking Real Users' Data Build a repeatable, schema-aware anonymization pipeline that preserves relationships while replacing sensitive production data. ![Cover image]() Real data makes the best test data. It has the weird edge cases, the realistic volumes and the relationships you'd never think to invent. It's also a liability: real emails, phone numbers and addresses end up on laptops, in CI logs, in screenshots and in bug reports. The fix isn't to stop using production-shaped data. It's to put a repeatable anonymization step between production and everyone else. This post builds one that: - keeps **ids, relationships, numbers and dates**, so the data still behaves like production, - replaces **identifying values** with fake ones that are **consistent**: the same person gets the same fake identity in every table, and on every refresh, - **refuses to run** when a new, unreviewed column shows up in the schema, - **checks its own output** for leaks before anything is exported. ```mermaid flowchart LR A["Production DB"] -->|"nightly backup"| B["Scratch copy on the server"] B --> C["anonymize.py with a secret key"] C --> D{"Leak check passes?"} D -->|"No"| E["Abort, nothing is exported"] D -->|"Yes"| F["Export the anonymized dump"] F --> G["Developer laptops and CI"] ``` ## The idea: keyed, deterministic fakes Each real value is run through **HMAC-SHA256 with a secret key**, and the result decides the fake value. That gives you three properties: - **Deterministic:** the same email always becomes the same fake email, so joins, duplicates and "same customer" logic keep working, and your dev accounts don't change on every refresh. - **Consistent across tables:** the email in `users` and the copy in `orders.customer_email` map to the same fake, even if one has different capitalization or stray spaces. - **Not reversible without the key.** The key matters: if you used a plain `sha256(email)`, anyone with a list of candidate emails could hash them and match. With a secret key, they can't. Keep it on the server and never give it to developers. ## The rules 1. **Never anonymize in production or on a laptop.** Restore a backup into a scratch database on the server, anonymize that, and export from there. 2. **Classify every column.** Each one is either explicitly safe to keep or gets a replacement rule. Anything unclassified stops the run, so a new `birthdate` column can't slip through unnoticed. 3. **Blank free text and delete secret tables.** Notes, support messages and tokens can't be safely pseudonymized. Remove them. 4. **Reset passwords** to a known dev-only hash. 5. **Verify before you export.** ## The script This version works on a SQLite copy and has no dependencies. ```python #!/usr/bin/env python3 """Usage: ANON_KEY=... DEV_PASSWORD_HASH=... python3 anonymize.py copy.db --yes-this-is-a-copy Deterministically pseudonymizes a COPY of production data. Never run it on production. """ import hashlib import hmac import os import sqlite3 import sys KEY = os.environ["ANON_KEY"].encode() # secret: stays on the server DEV_PASSWORD_HASH = os.environ["DEV_PASSWORD_HASH"] # hash of a known dev password FIRST = ["Asha", "Ravi", "Meera", "Kabir", "Isha", "Arjun", "Nina", "Omar", "Lena", "Diego"] LAST = ["Sharma", "Patel", "Iyer", "Khan", "Rossi", "Silva", "Novak", "Kim", "Brown", "Garcia"] def digest(kind, value): return hmac.new(KEY, f"{kind}:{value}".encode(), hashlib.sha256).digest() def fake_name(v): d = digest("name", v.strip()) return f"{FIRST[d[0] % len(FIRST)]} {LAST[d[1] % len(LAST)]}" def fake_email(v): return f"user_{digest('email', v.strip().lower())[:8].hex()}@example.test" def fake_phone(v): n = int.from_bytes(digest("phone", v.strip())[:8], "big") % 10**10 return f"+1555{n:010d}" def fake_address(v): return f"{1 + digest('address', v.strip())[0] % 200} Sample Street, Testville" def blank(v): return "[removed]" def dev_password(v): return DEV_PASSWORD_HASH KEEP = None # column is safe to copy as-is RULES = { "users": { "id": KEEP, "created_at": KEEP, "name": fake_name, "email": fake_email, "phone": fake_phone, "password_hash": dev_password, "notes": blank, }, "orders": { "id": KEEP, "user_id": KEEP, "total": KEEP, "created_at": KEEP, "customer_email": fake_email, "shipping_address": fake_address, }, } EMPTY = ["sessions", "api_tokens"] # tables whose rows are deleted LEAK_CHECKED = (fake_email, fake_phone, fake_address) # names are too common to check def main(path): con = sqlite3.connect(path) tables = [r[0] for r in con.execute( "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")] columns = {t: [r[1] for r in con.execute(f'PRAGMA table_info("{t}")')] for t in tables} # 1. Refuse to run if any table or column has not been classified problems = [] for t in tables: if t in EMPTY: continue if t not in RULES: problems.append(f"table {t} has no rules") continue problems += [f"column {t}.{c} is not classified" for c in columns[t] if c not in RULES[t]] if problems: sys.exit("Refusing to run:\n " + "\n ".join(problems)) # 2. Remember the distinctive original values, for the leak check originals = set() for t, rules in RULES.items(): for col, fn in rules.items(): if fn in LEAK_CHECKED: for (v,) in con.execute(f'SELECT "{col}" FROM "{t}" WHERE "{col}" IS NOT NULL'): originals.add(str(v).strip().lower()) # 3. Rewrite the sensitive columns (NULL stays NULL) for t, rules in RULES.items(): cols = [c for c, fn in rules.items() if fn] fns = [rules[c] for c in cols] select = ", ".join(f'"{c}"' for c in cols) sets = ", ".join(f'"{c}" = ?' for c in cols) rows = con.execute(f'SELECT rowid, {select} FROM "{t}"').fetchall() data = [[fn(str(v)) if v is not None else None for fn, v in zip(fns, vals)] + [rowid] for rowid, *vals in rows] con.executemany(f'UPDATE "{t}" SET {sets} WHERE rowid = ?', data) for t in EMPTY: if t in tables: con.execute(f'DELETE FROM "{t}"') # 4. Leak check: no original email, phone or address may survive anywhere leaks = [] for t in tables: for c in columns[t]: for (v,) in con.execute(f'SELECT "{c}" FROM "{t}"'): if isinstance(v, str) and v.strip().lower() in originals: leaks.append(f"{t}.{c}") break if leaks: con.rollback() sys.exit("Leak check failed, nothing was changed:\n " + "\n ".join(leaks)) con.commit() con.execute("VACUUM") # rewrite the file so old values don't linger in free pages print(f"anonymized {path}") if __name__ == "__main__": if len(sys.argv) != 3 or sys.argv[2] != "--yes-this-is-a-copy": sys.exit("usage: anonymize.py --yes-this-is-a-copy") main(sys.argv[1]) ``` Run it on the server, against the scratch copy: ```bash export ANON_KEY="$(cat /etc/anon-key)" # created once with: openssl rand -hex 32 export DEV_PASSWORD_HASH='...' # hash of a known dev password, from your framework python3 anonymize.py scratch.db --yes-this-is-a-copy ``` ### What it does - **Step 1 is the safety net.** It reads the real schema and stops if any table or column has no rule. When someone adds a column next month, the next refresh fails loudly instead of leaking it quietly. - **Step 3 changes only the columns with a rule.** Primary and foreign keys, totals and dates are left alone, so relationships survive. `NULL` stays `NULL`, so the shape of the data doesn't change. - **Email matching ignores case and whitespace**, so `" Alice@Corp.com "` and `alice@corp.com` become the same fake. - **Step 4 is the leak check.** It scans every column of every table for any original email, phone number or address, and rolls everything back if it finds one. - `VACUUM` **rewrites the database file.** Deleted rows can otherwise linger in the file's free pages. In my test, a deleted session token was still readable in the file until `VACUUM` ran. (This depends on SQLite's `secure_delete` setting, which overwrites deleted data. My build had it on, so I switched it off to see the problem. Your build may differ, so keep the `VACUUM`.) ## What it produces From a demo database, with made-up data and a test key (your fake values will differ with your key): | Column | Before | After | | --- | --- | --- | | `users.name` | Alice Realperson | Isha Khan | | `users.email` | [alice@corp.com]() | [user\_6cc0de473e61cced@example.test]() | | `orders.customer_email` | `Alice@Corp.com` | [user\_6cc0de473e61cced@example.test]() | | `users.phone` | a real number, or `NULL` | `+1555` plus 10 digits, or `NULL` | | `users.password_hash` | the real hash | the dev hash | | `users.notes` | free text | `[removed]` | | `sessions` | live tokens | table emptied | In my test run on 1,002 users and 1,502 orders, the row counts, the sum of order totals and the number of orders that still match their user's email were identical before and after. Running the script again from a fresh copy with the same key produced identical contents, and a different key produced different fakes. ## Check the output yourself The built-in leak check only compares whole values. It won't notice an email buried inside a free-text column that you chose to keep. So also search the final export for a handful of real values you know are in production, such as your own email and a colleague's: ```bash grep -ci "your.real.email@yourcompany.com" anonymized-dump.sql # should print 0 ``` ## Using it with Postgres or MySQL The workflow is the same: 1. Restore last night's backup into a **scratch database** on the server. 2. Run the same logic against it, using each table's primary key instead of SQLite's `rowid`. (Postgres can also compute HMACs in plain SQL with the `pgcrypto` extension's `hmac()` function, which is useful for very large tables. I haven't shown or tested that here.) 3. Dump the scratch database and hand out _that_. 4. Drop the scratch database. ## Gotchas - **Pseudonymized is not the same as anonymous.** Dates, rare combinations of fields and small groups can still point to a person, and anyone holding the key can confirm guesses. Treat the output as sensitive, limit who gets it, and check what privacy law (GDPR, India's DPDP Act and similar) requires for your data. - **Free text and JSON blobs are where leaks hide.** "Call Priya on her new number" can't be pseudonymized. Blank these columns. The same goes for audit logs, uploaded files and search indexes: this script doesn't cover them, so handle them separately. - **Short fake values can collide.** Names don't need to be unique, and emails use 64 bits of the hash, so collisions there are not a practical concern. A 10-digit phone number can collide on very large tables, which matters if the column has a unique constraint. - **Why not Faker?** Libraries like Faker generate richer data, but their output can differ between versions, which would change your fakes from one refresh to the next. Fixed lists plus a keyed hash stay stable. You can swap in richer lists if you need more realism. - **Block real sending in dev anyway.** The fake emails end in `.test`, a reserved domain that never resolves to a real mailbox, but point dev at a mail catcher so nothing is ever delivered by accident. - **Every account shares one password in dev.** That's convenient for testing, so never expose a dev environment to the public internet. - **Rotating the key changes every fake value.** Do it if the key leaks, not for fun. ## Wrap-up The goal is a refresh that developers can run without thinking about privacy, because the script has already thought about it: unknown columns stop the run, secrets are deleted, identities are fake but consistent, and a leak aborts the export. Start with the schema classification, since that's the part that keeps working after your schema changes.