Shield Platform Encryption & Compliance

0/2 in this phase0/41 across the roadmap

📖 Concept

Salesforce Shield is a set of enterprise security features for highly regulated industries. Understanding Shield, encryption, and compliance requirements (GDPR, HIPAA, PCI-DSS) is essential for architect-level roles.

Salesforce Shield components:

  1. Platform Encryption — Encrypts data at rest

    • Encrypts field values in the database
    • Supports: text, email, phone, URL, textarea, date, datetime, number, currency
    • Data is encrypted with AES-256
    • Key management: Salesforce-managed or customer-managed (BYOK)
    • Impact: Some features limited (formula fields, SOQL filtering on encrypted fields)
  2. Event Monitoring — Track user activity

    • Login events, API calls, report exports, page views
    • Transaction Security policies (real-time alerts)
    • Event log files (30-day retention, BigQuery/Splunk export)
  3. Field Audit Trail — Extended data retention

    • Track field changes for up to 10 years
    • Standard audit trail only tracks 20 fields × 18 months
    • Critical for regulatory compliance

GDPR (General Data Protection Regulation):

  • Right to access: Users can request their data
  • Right to erasure: Must delete personal data on request
  • Data portability: Export data in machine-readable format
  • Consent tracking: Record and manage user consent
  • Salesforce features: Individual object, Data Privacy fields, consent management

HIPAA (Health Insurance Portability and Accountability Act):

  • Encrypt PHI (Protected Health Information) at rest and in transit
  • Audit trail for all PHI access
  • Business Associate Agreement (BAA) with Salesforce
  • Restrict access using FLS, sharing rules, Shield encryption

Apex Security Best Practices:

  • Always use with sharing by default
  • Check FLS before DML: Security.stripInaccessible()
  • Check CRUD before operations: isAccessible(), isCreateable()
  • Never expose sensitive data in debug logs
  • Use Shield encryption for PII/PHI fields

💻 Code Example

codeTap to expand ⛶
1// Security & Compliance Patterns
2
3public with sharing class ComplianceService {
4
5 // 1. CRUD/FLS enforcement
6 public static List<Account> getAccountsSecure() {
7 // Check object-level access
8 if (!Schema.SObjectType.Account.isAccessible()) {
9 throw new SecurityException('No access to Account object');
10 }
11
12 List<Account> accounts = [
13 SELECT Id, Name, Phone, Industry, AnnualRevenue
14 FROM Account LIMIT 100
15 ];
16
17 // Strip fields the user can't access (FLS)
18 SObjectAccessDecision decision = Security.stripInaccessible(
19 AccessType.READABLE, accounts
20 );
21
22 return (List<Account>) decision.getRecords();
23 }
24
25 // 2. Secure DML with FLS
26 public static void updateAccountSecure(Account acc) {
27 // Check update permission
28 if (!Schema.SObjectType.Account.isUpdateable()) {
29 throw new SecurityException('No update access to Account');
30 }
31
32 // Strip fields the user can't update
33 SObjectAccessDecision decision = Security.stripInaccessible(
34 AccessType.UPDATABLE, new List<Account>{acc}
35 );
36
37 update decision.getRecords();
38 }
39
40 // 3. GDPR — Right to Erasure
41 public static void handleErasureRequest(String email) {
42 // Find all records related to this person
43 List<Contact> contacts = [
44 SELECT Id, AccountId FROM Contact WHERE Email = :email
45 ];
46 List<Lead> leads = [
47 SELECT Id FROM Lead WHERE Email = :email
48 ];
49
50 // Anonymize or delete based on business requirements
51 for (Contact c : contacts) {
52 c.FirstName = 'REDACTED';
53 c.LastName = 'REDACTED';
54 c.Email = null;
55 c.Phone = null;
56 c.MailingStreet = null;
57 }
58 update contacts;
59
60 if (!leads.isEmpty()) {
61 delete leads;
62 }
63
64 // Log the erasure for compliance
65 insert new Privacy_Request_Log__c(
66 Request_Type__c = 'Erasure',
67 Subject_Email__c = email,
68 Processed_Date__c = Datetime.now(),
69 Records_Affected__c = contacts.size() + leads.size()
70 );
71 }
72
73 // 4. Data export for portability (GDPR Right to Access)
74 public static String exportPersonalData(String email) {
75 Contact contact = [
76 SELECT FirstName, LastName, Email, Phone,
77 MailingAddress, Account.Name
78 FROM Contact WHERE Email = :email LIMIT 1
79 ];
80
81 Map<String, Object> exportData = new Map<String, Object>{
82 'name' => contact.FirstName + ' ' + contact.LastName,
83 'email' => contact.Email,
84 'phone' => contact.Phone,
85 'company' => contact.Account?.Name,
86 'exportDate' => Datetime.now().format()
87 };
88
89 return JSON.serializePretty(exportData);
90 }
91
92 // 5. Audit trail logging
93 public static void logSensitiveAccess(Id recordId, String action) {
94 insert new Audit_Log__c(
95 Record_Id__c = recordId,
96 Action__c = action,
97 User__c = UserInfo.getUserId(),
98 Timestamp__c = Datetime.now(),
99 IP_Address__c = Auth.SessionManagement.getCurrentSession()?.get('SourceIp')
100 );
101 }
102
103 // 6. Encryption-aware code
104 public static void handleEncryptedFields() {
105 // When Shield Platform Encryption is enabled:
106 // - Cannot filter on encrypted fields in SOQL WHERE
107 // - Cannot use encrypted fields in ORDER BY
108 // - Formula fields referencing encrypted fields are limited
109
110 // Pattern: Query by non-encrypted field, then filter in Apex
111 List<Contact> allContacts = [
112 SELECT Id, FirstName, LastName, SSN__c // SSN__c is encrypted
113 FROM Contact
114 WHERE AccountId = :accountId
115 ];
116
117 // Filter encrypted field in Apex (not SOQL)
118 Contact match = null;
119 for (Contact c : allContacts) {
120 if (c.SSN__c == targetSSN) {
121 match = c;
122 break;
123 }
124 }
125 }
126}

🏋️ Practice Exercise

Security & Compliance Practice:

  1. Implement CRUD and FLS checks using Security.stripInaccessible() for all object operations
  2. Build a GDPR erasure service that anonymizes personal data across 5 objects
  3. Create a data export feature that generates a JSON file of all personal data for a contact
  4. Design a consent management system using custom objects (Consent__c)
  5. Implement audit logging for all accesses to sensitive fields (SSN, DOB, medical records)
  6. Enable Shield Platform Encryption on 3 fields and verify SOQL filtering limitations
  7. Write test classes that verify FLS enforcement using System.runAs with restricted profiles
  8. Create an Event Monitoring dashboard using Shield Event Log data
  9. Design a data retention policy: which data to keep, archive, or delete based on age
  10. Build a compliance report that shows all users who accessed sensitive records in the last 30 days

⚠️ Common Mistakes

  • Not enforcing FLS in Apex — Apex runs in system context by default. Without explicit CRUD/FLS checks, all fields are accessible regardless of user permissions

  • Trying to filter SOQL on encrypted fields — Shield encryption prevents WHERE clause filtering. Query by non-encrypted fields and filter in Apex

  • Logging PII in debug logs — debug logs may be accessible to admins. Never log SSN, credit cards, passwords, or health data

  • Hard-deleting GDPR-protected data without audit trail — always log what was deleted, when, and why for compliance audits

  • Assuming 'with sharing' enforces FLS — 'with sharing' only enforces record-level security (OWD/sharing rules). FLS requires explicit checks with Security.stripInaccessible()

💼 Interview Questions

🎤 Mock Interview

Mock interview is powered by AI for Shield Platform Encryption & Compliance. Login to unlock this feature.