Sub topic 12
Keeping sensitive data out of non-production orgs
This chapter assumes you can run sf commands, read Apex, and understand how sandbox types differ from scratch orgs. You should also know the export and import commands from earlier chapters. Here you will learn where real customer data can leak into development environments and how to prevent it.
Why non-production orgs are a risk
Production data often includes personal information, such as names, email addresses, phone numbers, and national IDs. It can also include financial or health details. Non-production orgs are usually less protected than production:
- More people have access, including developers, contractors, and testers.
- Debug logs, exported files, and screenshots are easy to share.
- Automation in the org, such as workflows or email alerts, can contact real customers by accident.
- Data files committed to a repository stay in its history.
Privacy rules such as GDPR and many company policies apply to copies of data too. A sandbox full of real customers is a copy.
Where real data enters
Real data reaches a non-production org in three ways.
| Path | What gets copied | Typical risk |
|---|---|---|
| Full sandbox | All production records, plus attachments and history | Every sensitive field arrives unchanged |
| Partial Copy sandbox | A sample of records chosen by a sandbox template | Sensitive fields arrive unless excluded |
| Developer and Developer Pro sandboxes | Metadata only, no records | Low, until someone loads data |
| Scratch org | Nothing | Low, until you import data |
| `sf data export tree` from production | Whatever the query selects | Real values land in JSON files on disk and in git |
Scratch orgs and Developer sandboxes start without records. The leak happens when you load data into them. The most common mistake is exporting from production with sf data export tree, then committing the JSON files.
Principle: prefer data that was never sensitive
The safest dataset contains no real values at all. Choose from these options, safest first:
- Synthetic data that you or a generator invent, such as an Apex seed script.
- Data exported from a sandbox that has already been masked.
- Data exported from production with only non-sensitive fields selected.
- Unmasked production data. Avoid this one.
The diagram shows how to decide.
Select only the fields you need
An export query decides which values leave the source org. List fields explicitly and leave out the sensitive ones. Do not use FIELDS(ALL).
sf data export tree \
--query "SELECT Id, Name, Industry, (SELECT Id, FirstName, LastName FROM Contacts) FROM Account WHERE Industry = 'Technology' LIMIT 10" \
--plan \
--output-dir data \
--target-org my-source-orgThis query leaves out Email, Phone, and mailing addresses. Contacts still have real names, so run this against a masked sandbox, not production. If your tests need a valid email, add it back after import. Use a fake address such as [email protected], which is a reserved domain that never receives mail.
Masking data in a sandbox
When a Full or Partial Copy sandbox is the source or the working environment, mask it after creation. There are two common ways.
Salesforce Data Mask. This is a separately licensed product that masks fields in a sandbox using rules you configure, such as replacing values with random characters or deleting them. It suits large orgs and compliance needs. Check your edition and licensing before you plan around it.
A post-copy Apex class. SandboxPostCopy runs automatically after each create or refresh, as covered in the previous chapter. You can use it to overwrite sensitive fields. It costs nothing extra, but you write and maintain the code yourself. It also does not hide data from anyone who has access between the copy finishing and the script finishing.
This example masks contact emails and phone numbers with a batch job. A batch is necessary because a sandbox can hold more records than a single transaction can update.
global class MaskContactsBatch implements Database.Batchable<SObject> {
global Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator(
'SELECT Id, Email, Phone, MobilePhone FROM Contact ' +
'WHERE Email != null OR Phone != null OR MobilePhone != null'
);
}
global void execute(Database.BatchableContext bc, List<Contact> scope) {
for (Contact c : scope) {
if (c.Email != null) {
c.Email = 'masked+' + c.Id + '@example.invalid';
}
c.Phone = null;
c.MobilePhone = null;
}
update scope;
}
global void finish(Database.BatchableContext bc) {
System.debug('Contact masking finished');
}
}global class MaskAfterRefresh implements SandboxPostCopy {
global void runApexClass(SandboxContext context) {
System.debug('Masking sandbox ' + context.sandboxName());
Database.executeBatch(new MaskContactsBatch(), 200);
}
}The email includes the record Id so each value stays unique. Some orgs have duplicate rules or unique constraints on email, and a single shared value would fail them.
Choose the MaskAfterRefresh class when you create or refresh the sandbox. Test it first, because a class that throws an error can leave the sandbox unmasked.
Stop mail from leaving the sandbox
Masking data is not enough if automation can still send messages. Check these settings in every sandbox:
- Email deliverability. In Setup, under Deliverability, a new sandbox is normally set to system email only. Leave it there unless you are testing email on purpose. Confirm the setting after each refresh.
- User email addresses. Salesforce changes the usernames and emails of copied users so they are not delivered. Contact, lead, and custom email fields are not changed. This is why the batch above exists.
- Integrations. Named credentials and endpoints can still point at production services. Reset them in the same post-copy step.
- Scheduled jobs. Review scheduled Apex and flows that send outbound messages.
Keep data files out of version control
Seed files are code, but exported records are data. Treat them differently.
- Commit only data you made up or that has been masked.
- Add raw export folders to
.gitignore. - Do not keep production exports in a shared folder, a ticket, or a chat message.
# Raw exports from real orgs
data/raw/
*.local.jsonThen add an automated check that scans the data directory before any commit or CI run. This script fails when it finds an email address outside the reserved fake domains.
#!/usr/bin/env bash
set -euo pipefail
if grep -RIEoh '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}' data \
| grep -viE '@example\.(com|org|invalid)$'; then
echo "Found non-example email addresses in data/" >&2
exit 1
fi
echo "No real email addresses found in data/"Email is only one pattern. The same approach works for phone numbers or ID formats your business uses. A scan lowers the risk but does not remove it, because names and free-text fields cannot be reliably detected.
Common mistakes
- Exporting from production "just once". The files outlive the task. Export from a masked sandbox instead.
- Assuming a refreshed sandbox is safe. A Full sandbox copies everything, so masking must run on every refresh.
- Masking only the visible fields. Notes, attachments, email messages, case comments, and field history can hold personal data.
- Forgetting debug logs. Logs can contain field values. Delete logs and restrict who can view them.
- Trusting masking you never tested. After a refresh, query for values that should be gone and confirm the result is empty.
Exercise
A teammate exports 50 Contacts from production with sf data export tree, commits the JSON files to a feature branch, and then deletes the files in the next commit. Is the data now safe? Name two steps you would take.
Show answer
No. Git keeps the files in the earlier commit's history, so anyone with the repository can still read them. First, treat it as a data exposure: report it under your company's process and remove the commit from history, which may need a history rewrite that you coordinate with the repository owner. Second, prevent a repeat by exporting only from a masked sandbox, selecting non-sensitive fields, adding raw export folders to .gitignore, and running a PII scan script in CI.
Exercise
Why does the MaskContactsBatch example put the contact's Id in the masked email instead of using one fixed address for every record?
Show answer
A fixed address would give every Contact the same email. Duplicate rules or uniqueness constraints in the org could reject the update. Including the Id keeps each masked value unique, and the .invalid domain guarantees it can never reach a real mailbox.