Security - Guide
Who this page is for: developers who read or save records that not every user should see, and who need to honour the running user's permissions, sharing and encryption.
It also serves architects designing how an org protects sensitive data and enforces access, business analysts checking what the security capabilities and encryption options do and do not cover for compliance, and security reviewers auditing where sharing is enforced, and where (and why) it is deliberately bypassed.
New to it? Try Fast Start - Security first. Deciding whether to use KernDX? See Why KernDX.
Copy this first
List<Account> accounts = kern.QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Name', 'Industry'})
.withUserMode()
.toList();What this does: returns the accounts with Name and Industry filled in. withUserMode() runs this read in user mode whatever the user mode flag says, so it checks the current user's object and field permissions, and record sharing.
Read next: Get rows back without the hidden fields, Who turned a check off, Record sharing, Encrypting a short-lived value.
Quick Navigation
| I need to... | Go to... |
|---|---|
| Get the rows back without the fields the user cannot read | Quick Start |
| Know what is checked when I do nothing special | Safe by Default |
| Run one query or save in system mode | How to opt out |
| Turn user mode off for the whole org during an incident | Org-Wide Access Mode Kill-Switches |
| See who turned a check off, and why | How do I see who turned a check off? |
| Ignore record sharing for a batch or a system job | When to Bypass Sharing |
Know what bypassSharing() still checks in user mode | USER_MODE vs Sharing Proxy |
| Set the access mode or sharing on one save | Per-Transaction DML Control |
Choose with, without or inherited sharing for a class, a reusable one too | Classes with Explicit Sharing Declarations, Use Inherited Sharing for Reusable Code |
| Enforce object, field and record checks together | Combining All Three Security Layers |
| Encrypt a short-lived value, such as a token between wizard steps | Data Encryption & Decryption |
| Redact sensitive data before it is saved | Data Masking |
| Check who can see the framework's own records | Who can see the framework's own records? |
| Check who a scheduled job runs as, and who may run a failed API call again or delete one | Who runs a scheduled job |
| Give a user or group access to records with share records | Share Object Management |
| Test what a lower-permission user can see | Testing Sharing Behavior |
| Protect a portal page that takes a record Id | Parameter-Based Record Access in Portals |
| Keep a portal flow's input variables safe | Flow Input-Variable Hygiene |
| Give an auditor evidence | Security Governance Evidence |
| Know what KernDX does not monitor | What KernDX Does Not Monitor |
| Look up a method or a pattern | Quick Reference |
| Understand how the security layers fit together | How does it work? |
| Understand how the framework picks the sharing at run time | How the Proxy Pattern Works |
| See why KernDX is worth using | Why KernDX: the security example |
Quick Start
Most reads need the first row:
| When the user cannot read a field you select, you want | Use |
|---|---|
| An error | withUserMode(), as under Copy this first: the first sample below |
| The rows back without that field | withSystemMode(), withSharing() and stripInaccessible(): the second sample below. System mode skips the object permission check, so use it only where the user may read the object |
In your own classes you chain these methods on a selector's query, because every read goes through a selector; here they are on the builder so each one stands on its own. The simplest form:
// Enforce CRUD, FLS, and sharing in a single query
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Name', 'Industry'})
.withUserMode()
.toList();In user mode, a query that selects a field the user cannot read is refused with an error. If you would rather get the rows back with that field removed, run the query in system mode (SYSTEM_MODE, which turns off the object and field permission checks), keep record sharing with withSharing(), and remove the hidden fields with stripInaccessible():
// Enforce sharing and strip inaccessible fields
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Name', 'Industry'})
.withSystemMode()
.withSharing()
.stripInaccessible()
.toList();In system mode the query itself skips the object permission check, so use this form only where the user may read the object.
Namespaces in code samples:
kern.on a class andkern__on an object, field, or metadata type mark the managed package's namespace. On the managed package, framework references need those prefixes even where a sample omits them; repackaged under your own namespace, replacekern/kern__with your prefix; on an unmanaged deploy, drop them. See How to read the code samples.
What problem does this solve?
Every Salesforce app has to answer the same questions on every read and write: can this user see this object and field, can they see this particular record, and is any sensitive value about to be written down in plain text. Getting one of those wrong is how data leaks reach a security review.
KernDX answers them for you. By default, queries and saves run with the current user's read/write permissions and record sharing enforced (Salesforce calls this USER_MODE), sensitive values can be masked before they ever hit the database, and short-lived secrets can be encrypted in memory.
Mental model
Think of KernDX security as a checkpoint that every query and save passes through on its way to the database.
- By default it asks "is this user allowed to do this?" and turns away anything they have no permission for: a field they cannot read, a record they cannot see, an object they cannot change.
- You can wave a specific operation through on purpose (a system batch that must touch every record). Each time you do, the checkpoint writes down what was waved through and why.
- Encryption and masking are separate tools at the same checkpoint. Encryption scrambles a value you need back later. Masking redacts a value that should never be stored readable in the first place.
Use this when
- You write Apex that reads or writes records and want the current user's permissions and record sharing enforced without hand-coding the checks.
- You need to choose at run time whether a query or save respects sharing rules, so the same logic can run for a UI user and for a system batch.
- You want to redact secrets or personal data on records before they are saved, configured in metadata rather than code.
- You need to encrypt a short-lived value (a token passed between wizard steps, for example) without managing keys yourself.
- You have to show an auditor where access is enforced, and where it is deliberately bypassed.
Don't use this when
- You need long-term encrypted storage or compliance-grade key management.
UTIL_SessionEncryptionkeys expire within 8 hours and are lost if the cache clears; use Shield Platform Encryption or external key management instead. - You want org-wide security monitoring, config-drift detection, backup, or login-anomaly alerts. KernDX gives you mechanisms inside your own code, not an org-security monitor; see What KernDX Does Not Monitor.
Safe by Default
The safe behaviour is on automatically. You step outside it only when you choose to. Every query and save your code can reach runs with the current user's permissions and sharing enforced (AccessLevel.USER_MODE) unless you say otherwise. In practice:
new SEL_Account().findById(id)runs in USER_MODE (field security, object permissions, and sharing all enforced).QRY_Builder.selectFrom(Account.SObjectType)...toList()runs in USER_MODE.DML_Builder.newTransaction().doInsert(record).execute()runs in USER_MODE.
So a developer who writes a normal query gets the protected behaviour without thinking about it. Two configuration records (FeatureFlag__mdt) drive this default:
FeatureFlag.UserModeQueries_EnabledcontrolsQRY_Builder/SEL_Base.query.FeatureFlag.UserModeDml_EnabledcontrolsDML_Builderand the access mode every framework save uses by default.
Both ship turned on (IsEnabledByDefault__c = true).
Opting individual calls out of the default:
// Query that must run SYSTEM_MODE (framework-internal CMDT read, etc.)
QRY_Builder.selectFrom(TriggerAction__mdt.SObjectType)
.withSystemMode()
.fields(...)
.toList();
// DML that must run SYSTEM_MODE
DML_Builder.newTransaction()
.withSystemMode()
.doInsert(logEntry)
.execute();Opting a whole selector out (when you write your own SEL_* class):
global inherited sharing class SEL_MyInternalCmdt extends SEL_Base
{
global SEL_MyInternalCmdt() { super(MyInternalCmdt__mdt.SObjectType); }
global override Boolean systemModeRequired()
{
return true;
}
}The systemModeRequired() hook on SEL_Base is global virtual, so you can override it in your own selectors.
- When it returns
true, everyfindById,findByField, andquery-getter call through that selector runs inAccessLevel.SYSTEM_MODE(object and field permission checks skipped), whatever the flag is set to. - Record sharing is not affected by that hook and keeps following the sharing keyword of the class the query runs in. Use
.bypassSharing()where sharing must be set aside too.
Emergency off-switch (metadata only, no deployment needed):
Go to Setup, then Custom Metadata Types, then FeatureFlag, edit UserModeQueries_Enabled, set IsEnabledByDefault__c = false, and save. The next transaction picks it up, and every query your code can reach reverts to SYSTEM_MODE. The same applies to UserModeDml_Enabled. This is a lever for incidents, not a routine setting.
Bypass audit trail (triggers, queries, saves and validations). When a safety check is turned off through one of the framework's bypass calls, KernDX records what was bypassed and why, so a later review can see it.
Each bypass call writes a LogEntryEvent__e record with category BypassEvent, capturing the user, the action, the surface, the target, and an optional reason you set with TRG_Base.setBypassReason(String). That reason applies to every bypass in the transaction.
| Call | Writes an audit entry? |
|---|---|
Triggers: TRG_Base.bypass* | Yes |
Queries: QRY_Builder.withSystemMode / bypassSharing / withoutSecurity | Yes |
Saves: DML_Builder.withSystemMode / bypassSharing | Yes |
Validations: UTIL_ValidationRule.bypassObject / bypassGroup / bypassRule | Yes |
withUserMode(), withSharing() and stripInaccessible() | No: they turn no check off |
Three lower-level save methods your code can call directly: DML_Transaction.setAccessLevel(AccessLevel.SYSTEM_MODE), DML_Transaction.commitWork(false), and PROC_ExecuteDML built with AccessLevel.SYSTEM_MODE | Yes. A DML_Transaction commit writes one entry per object it saves (system-mode:Account, sharing:Account), once per commitWork call and only when it saves records. PROC_ExecuteDML writes one entry when you build it, before it has its records, so the target is system-mode with the operation and no object |
A selector that overrides SEL_Base.systemModeRequired() | No: it is a design choice written in the selector's own source, where code review sees it, not a call that turns a check off |
| The framework's own reads and saves in system mode that no call of yours asked for, such as logging and resolving API issues, setting up the Health Check's scheduled jobs and reading the recipients of the Send Email (Flow-Delegated) and Log Activity action | No: they are the framework's own work, not a check your code turned off |
Two switches turn the whole audit off:
- The
BypassAudit_Enabledfeature flag (FeatureFlag__mdt) is the master off-switch for the audit. It ships on, and you can disable it through aFeatureFlagStrategy__mdtoverride. - Logging itself. While Is Enabled (
IsEnabled__conLogSetting__c) is unchecked, no bypass entry is saved.
The log level does not turn the audit off: bypass entries are saved at every log level, ERROR included. A class filter or the suppression list on the log setting can hide part of it (details below).
How do I see who turned a check off?
To browse the bypass audit, open the Log Console. Its Problem summary view groups the bypass audit for you, as warnings whose short message reads like BYPASS sharing:Account (query) (the action, the target and the surface).
To list every recorded bypass with one query, filter on each log entry's grouping key, Fingerprint__c. The framework gives each distinct bypass a key that starts with detail:bypass:.
- Two bypasses count as the same when the same user, from the same class and method, makes the same bypass (same action, surface and target).
- The row for each distinct bypass holds the first time it happened and the reason given then. The row stays until log retention deletes it.
The package does not give you a log selector to call, so the reads below go through a short selector of your own, in its own class file. It leaves systemModeRequired() alone, so it reads in user mode while the UserModeQueries_Enabled flag is on, as it ships:
public with sharing class SEL_LogEntries extends SEL_Base
{
public SEL_LogEntries()
{
super(LogEntry__c.SObjectType);
}
public override List<SObjectField> getFields()
{
return new List<SObjectField>{
LogEntry__c.UserId__c,
LogEntry__c.ShortMessage__c,
LogEntry__c.ClassMethod__c,
LogEntry__c.CreatedDate,
LogEntry__c.ContextData__c,
LogEntry__c.OccurrenceCount__c,
LogEntry__c.LastModifiedDate
};
}
}Every recorded bypass, newest first:
List<LogEntry__c> bypasses = new SEL_LogEntries().query
.condition(LogEntry__c.Fingerprint__c).startsWith('detail:bypass:')
.orderBy(LogEntry__c.CreatedDate).descending()
.toList();| Field | What it tells you |
|---|---|
UserId__c | The user who turned the check off. Read this field, not CreatedById: log entries are saved by a background process, so CreatedById is always the Automated Process user. |
ShortMessage__c | The action, the target and the surface, for example BYPASS sharing:Account (query). |
ClassMethod__c | The class and method that made the bypass call. When the framework cannot tell which class made the call, it shows the framework's own audit class instead (see below the table). |
CreatedDate | The first time this bypass happened. |
ContextData__c | The details, including the reason you set with TRG_Base.setBypassReason(String). SOQL cannot filter on this long text field, so read it from the rows the query returns. |
ClassMethod__c shows the framework's own audit class when no Apex class of yours is on the call stack at the moment of the bypass. That is the case for:
- a bypass started from a Flow with the Trigger Bypass, Bypass Validation or Clear Validation Bypass action;
- the part of a bulk field update (
PROC_UpdateFields) with itsaccessLevelset toAccessLevel.SYSTEM_MODEthat runs as a background job. A read it makes before the job starts, and a call of yours to itsexecutemethod, record your class; - an API service that calls
setAccessLevel(AccessLevel.SYSTEM_MODE)in its own code and leaves the save to the framework. The entry is written when the save runs and names the class that started the save, so when the framework starts it (a send in the background, for example),ClassMethod__cshows a framework class instead of yours.
How the audit class reads depends on how the framework is installed:
| How the framework is installed | What ClassMethod__c shows |
|---|---|
| The managed package | kern.UTIL_BypassAudit.emit |
| A copy renamed to your own namespace | Your namespace in place of kern, for example acme.UTIL_BypassAudit.emit. Code of yours in that same namespace also shows it, because the framework cannot tell your classes from its own there. |
| A copy with no namespace | UTIL_BypassAudit.emit. This is rare: in the cases above the column shows the framework class and method that made the call, for example FLOW_BypassTrigger.execute. |
A repeat of the same bypass adds no new row of this kind. To see the days on which it happened again, and how often, read the daily summary rows. Their key starts with rollup:bypass:. The query keeps only the last 30 days, so it does not read every summary row ever saved:
List<LogEntry__c> bypassDays = new SEL_LogEntries().query
.condition(LogEntry__c.Fingerprint__c).startsWith('rollup:bypass:')
.andCondition(LogEntry__c.CreatedDate).equals(new QRY_Condition.DateLiteral().lastNDays(30))
.orderBy(LogEntry__c.CreatedDate).descending()
.toList();There is one summary row for each bypass on each day (days are counted in UTC, Coordinated Universal Time):
OccurrenceCount__cis how many times the bypass happened that day,CreatedDatethe first time andLastModifiedDatethe last.- The row keeps the first reason given that day. A different reason given later the same day is not kept.
Three things to know:
- Bypass entries are saved at every log level. The log level (
LogLevelThreshold__conLogSetting__c) applies only to your application logs, so a bypass entry is saved when the log level is ERROR too (the entry itself keeps the level WARN). It ships set to DEBUG.- The class filter (
ClassFilter__c) and the suppression list (SuppressClassMethod__c) onLogSetting__cdo apply. If one of them leaves out a class, the bypass entries made from that class are not saved either. - A caller that carries a namespace is matched by its namespace, not by its class name:
kern.UTIL_BypassAudit.emitis matched askern, and a class of yours in the namespaceacmeasacme. So a class filter that must keep those entries names the namespace. - Each bypass entry publishes one platform event, at every log level. The Logging Guide explains what that costs.
- The class filter (
- The queries run with your own permissions. They read log entries as the person who runs them, so that person needs read access to log entries. Log entries are private, so that person also needs to see every entry: the permission set
LogConsoleReadOnly(label "Kern Log Console Read Only") grants both. - Inside an event trigger, the user is the Automated Process user. Platform-event and change-event triggers run as the Automated Process user. The framework reads the user once for each transaction, so a bypass made inside one of these triggers shows the Automated Process user in
UserId__c.
How to opt out
You step outside the secure default for a single call, right where you make it. Every protection here is opt-in per layer:
- On the same line you choose the sharing behaviour, the access mode (
AccessLevel), and whether object and field permissions are enforced. Nothing is hidden in framework internals. - The overwhelming majority of the framework's own classes default to
inherited sharing, so the caller's sharing context flows through unchanged.
| You need | Use | See |
|---|---|---|
AccessLevel.USER_MODE for one transaction | DML_Builder.withUserMode() / QRY_Builder.withUserMode(). Explicitly overrides the flag-driven default. | Per-Transaction DML Control, Per-Query Sharing Control |
AccessLevel.SYSTEM_MODE (privileged framework code) | .withSystemMode() on either builder. Skips object and field permission checks for that one operation. | AccessLevel Selection |
| Bypass sharing rules for an isolated calculation | .bypassSharing() routes through the without sharing proxy; in user mode the user's object and field permissions still apply. Raw SOQL or DML you write in a without sharing class of your own is not intercepted; a builder call from that class still enforces sharing in user mode. | Without Sharing Classes |
| Inherit sharing from the caller | The default for framework classes. The caller's sharing context flows through unchanged. | Inherited Sharing Classes |
| Org-wide off-switch for the USER_MODE rollout | The UserModeDml_Enabled feature flag. Flip it in metadata; it takes effect on the next transaction. | Org-Wide Access Mode Kill-Switches |
Direct Database.insert(records, allOrNothing, AccessLevel) | Not a framework path: nothing intercepts raw platform DML, so the flag-driven default does not reach it. Save through DML_Builder, except for the four saves the builder cannot express (merge, lead conversion, DMLOptions, recycle bin). | DML - Guide: How to opt out |
Sharing control is decided where you call it, not buried in framework internals. Every default has a documented override on the same fluent builder (the chain of short method calls you build the query or save with).
What is the Security framework?
The security capabilities KernDX provides are data encryption, record-level sharing, and the patterns that enforce field, object, and record permissions. Together they help you follow Salesforce security best practice, protect sensitive data, and control who can reach which records.
What this framework is responsible for: it checks that the current user is allowed to perform an operation, and throws an exception when they are not. It enforces access control (object create/read/update/delete permissions, field-level security, and record sharing) and protects sensitive data through encryption. It does not contain business logic or decide what data your app reads.
The framework gives you three main security capabilities:
- Data encryption (
UTIL_SessionEncryption): encrypt and decrypt sensitive values in memory, with the key managed for you. - Record sharing (
UTIL_Sharing,DML_Builder): decide at run time whether Salesforce sharing rules apply, instead of fixing it in code. - Query security (
QRY_Builder): combinable options that enforce object create/read/update/delete permissions (CRUD) and field-level security (FLS) on a query, through.withUserMode()and.stripInaccessible().
Key Concepts
| Term | Description |
|---|---|
| Sharing Rules | Salesforce record-level security determining which users can access which records |
| CRUD | Object-level permissions (Create, Read, Update, Delete) |
| FLS | Field-Level Security - permissions on individual fields |
| AccessLevel | Salesforce's programmatic mode for Database operations (SYSTEM_MODE vs USER_MODE) |
| Sharing Proxy | Inner class pattern that executes operations with specific sharing context |
Framework Philosophy
Four ideas shape how KernDX handles security. Each one exists to prevent a common way that access controls quietly go wrong.
- Choose sharing on purpose, not by accident. Whether a piece of code respects sharing rules should be a deliberate decision you can see, not something it inherited without anyone noticing.
- Let the context decide at run time. The same logic may run from a UI button, a nightly batch, and a trigger, and each may need different sharing. You set the behaviour when the code runs, not when it compiles.
- Route data access through one place. Queries and saves flow through framework classes, so a security policy can be applied in one spot rather than re-checked everywhere.
- Layer the protections. Record sharing, field-level security, and object permissions are separate concerns. You can turn each on independently, so a gap in one does not silently open the others.
How does it work?
Architecture Diagram
+---------------------------------------------------------------------------+
| SECURITY FRAMEWORK ARCHITECTURE |
+---------------------------------------------------------------------------+
| |
| DATA PROTECTION CRUD/FLS ENFORCEMENT |
| =============== ==================== |
| |
| +-----------------------------+ +-----------------------------+ |
| | UTIL_SessionEncryption | | QRY_Builder | |
| +-----------------------------+ +-----------------------------+ |
| | - AES-256 encryption | | .withUserMode() | |
| | - Automatic key management | | (CRUD + FLS + Sharing) | |
| | - encrypt() / decrypt() | | .stripInaccessible() | |
| +-----------------------------+ | (post-query FLS) | |
| +-----------------------------+ |
| |
+---------------------------------------------------------------------------+
| |
| RECORD-LEVEL SHARING |
| ==================== |
| |
| +-------------------------------+ +-------------------------------+ |
| | DML Sharing (DML_Builder) | | Query Sharing (QRY_Builder) | |
| +-------------------------------+ +-------------------------------+ |
| | .withUserMode() | | .withUserMode() | |
| | (CRUD + FLS + Sharing) | | (CRUD + FLS + Sharing) | |
| | .withSystemMode() | | .withSystemMode() | |
| | .bypassSharing() | | .withSharing() | |
| | -> without sharing proxy | | .bypassSharing() | |
| | Default: flag-driven | | .stripInaccessible() | |
| | (UserModeDml_Enabled) | | Default: flag-driven | |
| | | | (UserModeQueries_Enabled) | |
| +-------------------------------+ +-------------------------------+ |
| |
+---------------------------------------------------------------------------+The security framework works in layers. You turn each one on independently and combine them as a feature needs:
- Object and field permissions (CRUD/FLS).
QRY_Builder.withUserMode()enforces object permissions and field-level security right inside the query: a query that selects a field the user cannot read is refused.QRY_Builder.stripInaccessible()quietly drops fields the user cannot read from the results of a query that runs in system mode or withbypassSharing(). - Record sharing.
DML_BuilderandQRY_Builderdecide at run time whether a query or save respects sharing rules (with sharing), ignores them (without sharing), or follows whatever the caller chose (inherited sharing). They do this through a small "proxy" class, explained below. - Query security options. On a query,
QRY_BuilderofferswithUserMode()(enforce object permissions, field security, and sharing at the database),stripInaccessible()(remove unreadable fields after a query in system mode),bypassSharing()(ignore record sharing while the user's object and field permissions still apply), andwithSharing()(enforce sharing on a query that runs in system mode). - Data protection.
UTIL_SessionEncryptionencrypts sensitive values with AES-256 and manages the key for you.
The starting point matters most: every query and save your own code can reach runs with the current user's permissions and sharing enforced by default (AccessLevel.USER_MODE). So a developer who does nothing special still gets the safe behaviour.
- The one exception is records an API service registers in
onSuccess(): they are saved in system mode (see onSuccess()). - The layers do not depend on one another: you can enforce field security without enforcing sharing, or control sharing without checking object permissions.
- A few framework-internal selectors do need to skip those checks, for example readers of custom metadata, framework-owned objects, and system schema. They opt out by overriding the
systemModeRequired()hook onSEL_Base. - To roll the secure default back across the whole org in an incident, there is a master off-switch you can flip in metadata without a deployment: the
FeatureFlag.UserModeQueries_Enabled/UserModeDml_Enabledrecords, described in Safe by Default above.
Data Encryption & Decryption (UTIL_SessionEncryption)
What it does
UTIL_SessionEncryption protects a sensitive value for a short while, for example a token you pass between two steps of a wizard, without you managing encryption keys:
- It encrypts and decrypts values using AES256 with HMAC-SHA256 (the Encrypt-then-MAC pattern, which also detects tampering).
- It manages the key for you.
- It is for short-lived data only. The trade-off, and it is a sharp one, is in the warning below.
CRITICAL ARCHITECTURAL WARNING
This utility keeps its encryption keys in temporary storage (Platform Cache), not in the database.
The key is not saved to the database. If the cache expires, is flushed, or the session ends, the key is lost forever, and any data you encrypted with it becomes permanently unrecoverable.
Do not use this class for:
- Persisting encrypted data to SObjects or Custom Settings
- Data that must survive beyond an 8-hour session
- Long-term data storage
- Long-term data encryption (use Shield Platform Encryption)
- Credit card data (use PCI-compliant tokenization service)
- Data requiring compliance-mandated encryption key management
- Data that must survive org refreshes or cache flushes
Use this class only for:
- Short-lived data passing (e.g., ViewState, temporary token exchange)
- Session-scoped data where data loss is acceptable upon session expiry
- Temporary credentials that expire within hours
Key Features:
- AES256 encryption with HMAC-SHA256 for integrity validation
- Automatic key generation and management via Platform Cache
- Platform cache integration with 8-hour maximum key expiry
- User-scoped keys (unique per user session)
- Base64-encoded output for safe storage in text fields
- Automatic key rotation on cache expiry
Critical Warning: Data Loss Risk
KernDX UTIL_SessionEncryption:
// DANGER: Data encrypted today may be unrecoverable tomorrow!
// Day 1: Encrypt and store
String encrypted = UTIL_SessionEncryption.encrypt('secret');
account.EncryptedToken__c = encrypted;
update account;
// Day 2: Cache expires or org is refreshed
// THIS WILL FAIL - Key is gone forever:
String decrypted = UTIL_SessionEncryption.decrypt(account.EncryptedToken__c);
// Exception: IllegalArgumentException: No encryption key foundRecommendation: For any data that must be decrypted beyond an 8-hour window, use Shield Platform Encryption or external key management.
Encryption Methods
Encrypt Plain Text
/**
* @description Encrypts a plain text string using AES256 encryption
*
* @param plainTextValue The plain text to encrypt
*
* @return Base64-encoded encrypted string
*/
global static String encrypt(String plainTextValue)Example:
// Encrypt sensitive data for secure session-scoped passing
String apiToken = 'sk_live_1234567890abcdef';
String encryptedToken = UTIL_SessionEncryption.encrypt(apiToken);
// Pass encrypted token through page state, cache, or between controllers
// Key remains in platform cache for up to 8 hours
// encryptedToken is a Base64-encoded string like "xK7j9mP3nQ8wR5sT6uV1yZ2..."Decrypt Encrypted Text
/**
* @description Decrypts an encrypted string back to plain text
*
* @param encryptedTextValue The Base64-encoded encrypted string
*
* @return Decrypted plain text string
*/
global static String decrypt(String encryptedTextValue)Example:
// Decrypt within the same session (key must still be in cache)
String plainTextToken = UTIL_SessionEncryption.decrypt(encryptedToken);
// Use decrypted token for API callout
HttpRequest request = new HttpRequest();
request.setHeader('Authorization', 'Bearer ' + plainTextToken);How Automatic Key Management Works
First Encryption Request:
- Generates a random 256-bit AES key using
Crypto.generateAesKey(256) - Stores key in user-scoped platform cache with 8-hour TTL (28,800 seconds)
- Generates HMAC key by deriving from AES key using SHA-256
- Encrypts the plain text using AES256 with random IV (Initialization Vector)
- Appends HMAC for integrity validation (Encrypt-then-MAC pattern)
- Returns Base64-encoded encrypted string:
IV:Cipher:HMAC
- Generates a random 256-bit AES key using
Subsequent Requests:
- Retrieves user-scoped key from platform cache
- If key not found or cache unavailable, throws exception
- Uses cached key for encryption/decryption
- Validates HMAC before decryption to detect tampering
UTIL_SessionEncryption.decrypt()throws an exception if the value was changed
Key Rotation:
- Keys automatically expire after 8 hours (maximum session cache TTL)
- Once a key expires, all data encrypted with it is permanently lost
- Key is user-scoped (unique per user) for security isolation
Cache Strategy:
// Uses Platform Cache with AUTO mode (Session -> Org fallback)
// Keys are unique per user for security isolation
// Cache availability is verified before operations
// Throws Cache.CacheException if cache is unavailable or misconfiguredUse Cases
Secure Multi-Step Wizard State
A user enters a credential in step 1 of a wizard that you need again in step 3, and you do not want it sitting in page state as plain text. Encrypt it on the way in and decrypt it on the way out, all within the same session:
public inherited sharing class WizardController
{
/**
* @description Encrypts credentials entered in step 1 for use in step 3.
* Encrypted value is passed through page state, not persisted.
*/
@AuraEnabled
public static String encryptCredentials(String externalPassword)
{
return UTIL_SessionEncryption.encrypt(externalPassword);
}
/**
* @description Decrypts credentials in step 3 to authenticate with external system.
* Must be called within the same session (key expires after 8 hours).
*/
@AuraEnabled
public static String completeIntegration(String encryptedPassword, String endpoint)
{
String password = UTIL_SessionEncryption.decrypt(encryptedPassword);
HttpRequest request = new HttpRequest();
request.setEndpoint(endpoint);
request.setHeader('Authorization', 'Basic ' + EncodingUtil.base64Encode(
Blob.valueOf('user:' + password)
));
HttpResponse response = new Http().send(request);
return response.getBody();
}
}Temporary OAuth Token Caching
You get an OAuth token back from an external login and want to reuse it for the rest of the session without writing it to the database. Encrypt it before caching, decrypt it just before each callout:
public inherited sharing class OAuthSessionManager
{
/**
* @description Caches encrypted access token for reuse during the session.
* Token is encrypted in memory/cache, never persisted to database.
*/
public static String cacheAccessToken(String accessToken)
{
String encrypted = UTIL_SessionEncryption.encrypt(accessToken);
Cache.Session.put('oauth_token', encrypted, 3600); // 1 hour
return encrypted;
}
/**
* @description Retrieves and decrypts access token for API callout.
*/
public static String getAccessToken()
{
String encrypted = (String)Cache.Session.get('oauth_token');
if(String.isBlank(encrypted))
{
throw new AuthException('Session expired. Please re-authenticate.');
}
return UTIL_SessionEncryption.decrypt(encrypted);
}
private class AuthException extends Exception {}
}Secure Parameter Passing via Platform Events
You need to send a sensitive value through a Platform Event but the event payload would otherwise carry it in the clear. Encrypt it before publishing, and have the subscribing code decrypt it, as long as both run under the same user's cache:
public inherited sharing class SecureEventPublisher
{
/**
* @description Publishes encrypted payload via Platform Event.
* Consuming subscriber must decrypt within the same cache window.
*/
public static void publishSecureEvent(String sensitivePayload)
{
String encrypted = UTIL_SessionEncryption.encrypt(sensitivePayload);
Secure_Event__e event = new Secure_Event__e(
Encrypted_Payload__c = encrypted
);
EventBus.publish(event);
}
/**
* @description Decrypts payload received from Platform Event.
* Only works if the encryption key is still in the subscriber's cache.
*/
public static String decryptEventPayload(String encryptedPayload)
{
return UTIL_SessionEncryption.decrypt(encryptedPayload);
}
}Note: Platform Event encryption only works when the publisher and subscriber share the same user-scoped cache (e.g., same user context). For cross-user event encryption, use
Crypto.encrypt()with a shared key stored in a Named Credential or Protected Custom Setting.
Important Considerations
Key Expiry and Data Persistence:
- Encrypted data can only be decrypted while the original key is in cache (max 8 hours)
- If cache expires, is cleared, or org is refreshed, keys are lost forever
- For long-term storage, use Salesforce Shield Platform Encryption instead
- This utility is best for temporary encryption (session tokens, temporary credentials, ViewState)
Cache Availability:
- Requires Platform Cache to be allocated and configured in the org
- Uses AUTO mode (Session -> Org fallback)
isAvailable()method checks cache availability before operations- Throws
Cache.CacheExceptionif cache is unavailable
Performance:
- The first encryption operation generates a new 256-bit AES key.
- After that, operations are fast because the key comes from platform cache.
- User-scoped keys stop one user's key being reused for another.
- The HMAC tamper check adds one extra step on each operation, which costs little.
Security:
- Keys stored in ephemeral platform cache (not persisted to database)
- Keys expire after 8 hours maximum (session cache limit)
- Uses AES256 encryption with HMAC-SHA256 (Encrypt-then-MAC)
- Random IV per encryption prevents pattern analysis
- User-scoped keys isolate encryption between users
- HMAC validation detects tampering or corruption
- Keys never exposed in debug logs or API responses
When not to use it: see the list under the warning above.
Data Masking
KernDX includes a built-in data masking framework that rewrites sensitive values on records before they are saved. These are values that should never reach the database in readable form in the first place: a secret, a card number, a piece of personal data that slipped into a free-text field.
- Masking is on by default and already protects the framework's own diagnostic records (API call logs, async-chain payloads, integration error records).
- To cover your own objects, you deploy a small amount of configuration metadata. No Apex is required.
Where the full reference lives. For the setup walkthrough, the rule catalogue, the four matching modes, failure handling, and the no-code Data Masking Advisor, see the Data Masking Guide (or the Fast Start - Data Masking to mask a field in about twenty minutes).
Masking vs. encryption. These two solve opposite problems.
- Session encryption is reversible: you encrypt a value, store it, and decrypt it later. Use it when you need the data back.
- Masking is deliberately one-way: it overwrites the sensitive value with a redacted one, and the original is gone. Use it when the value should never have been stored readably at all (for example, an API request body captured for diagnostics that happens to carry a bearer token).
What Data Masking Does
Masking rewrites the value of text-shaped fields as records are saved, following rules you configure. It can recognise a sensitive value in four ways:
| Mode | What it matches | Typical use |
|---|---|---|
| Regex | A regular expression matched against the whole value; matches are replaced (capture groups $1, $2 supported) | Free-text redaction |
| JSON by Key | A regex matched against JSON keys; the value under each matching key is replaced, at any nesting depth | Redacting password / token values inside a JSON payload |
| Exact Match | A literal substring; every occurrence is replaced | A known fixed string |
| Credit Card | Like Regex, but each match must also pass the Luhn (mod-10) checksum | Card-number redaction without catching ordinary long digit runs |
Out of the box, the logging, web-service, and async-chain subsystems mask their own records. Request and response bodies, async-chain payloads, and integration error records have card numbers and credential-shaped values redacted before they are saved. The shipped rules cover categories such as Contact, Personal, Payment, Health, Credentials, Financial, Identity, and Network.
What Masking Is Not
Masking is a focused tool. Know its boundaries before you rely on it:
- It is destructive. The redacted value replaces the original. KernDX does not keep a copy and there is no "unmask". If you need the original back, use encryption or a separate secure store, not masking.
- It covers text fields only. Masking applies to Text, Text Area, Long Text Area, URL, Email, Phone, and Encrypted Text fields. Numbers, dates, checkboxes, picklists, and lookups are never touched.
- It is not retroactive. A rule masks records as they are inserted or updated after you deploy it. Data already in the database is untouched until the next time each record is written. To clean up historical data, re-save the records (for example, via a one-off batch) so they pass through the masking step.
- It is not access control. Masking decides what is stored, not who can see it. It does not replace field-level security, sharing, or Shield Platform Encryption. Use those for at-rest protection and per-user visibility. Use masking to keep a sensitive value from being written down at all.
- Your custom objects are not masked until you configure them. The shipped rules protect KernDX's own diagnostic records. Masking does not auto-detect sensitive fields at run time: a field is masked only when a Masking Target points a rule at it. The Data Masking Advisor helps you find the fields that need one.
Configuring Masking
You configure masking entirely in metadata. A Masking Rule (MaskingRule__mdt) describes how to redact; you wire it to a Masking Target (MaskingTarget__mdt) that describes where. Masking is gated per object by the Apply Masking switch on that object's Trigger Setting, and globally by the MaskingFramework_Enabled feature flag (on by default).
Two things matter to a security reviewer. First, every masking decision is declarative, version-controlled, and deployable, so there is no imperative "mask this" call buried in Apex to track down. Second, it runs in the before phase with no extra DML, so it is safe to run on large data loads.
The full setup walkthrough, the four matching modes, the rule catalogue, the failure-handling options (Log and Continue, Write Failure Marker, Block DML), and the no-code Data Masking Advisor (which also exports a regulated-field inventory for auditors) all live in the Data Masking Guide.
For how the Advisor's artifacts fit a governance or audit process, and what they deliberately do not prove, see Security Governance Evidence.
Secret Scanning in CI
Runtime masking keeps secrets out of your data. A separate control, this one running at development time, keeps them out of your source code:
- The KernDX delivery pipeline ships a Salesforce-aware
kerndx secret-scangate. It inspects changed files for hardcoded credentials such as API keys, tokens, and private keys, and fails the build before they can merge. - It runs in your own CI, as part of the pipeline workflow
kerndx initsets up. - You can suppress a reviewed false positive inline or by fingerprint.
See the Code Scanning Guide for setup and rule detail.
Who runs a scheduled job
| Job | Runs as |
|---|---|
| A scheduled job in its own mode | The user who saved its record, which is how the platform works |
| A job on the job runner | The user who activated the runner in Health Check, because that user owns the runner's scheduled jobs |
Anyone who works with the job runner needs the Manage Job Runner permission. Without it, anyone who could edit a schedule record could run code as a more privileged user. So these actions all need it:
- putting a job on the runner, changing or deleting a job already on it, taking a job off it, and running it now;
- activating, repairing or deactivating the runner.
A job restored from the Recycle Bin comes back switched off, so it cannot run until someone switches it on through a normal save. If it cannot be switched off, the restore is refused. One of the job runner's own records cannot be restored from the Recycle Bin: use Activate or Repair in Health Check to bring the job runner back.
Grant the permission through the Kern Job Runner Management permission set, which ships assigned to nobody:
- The set also lets its holder open the Scheduled Jobs tab and create and edit scheduled jobs, but not delete them or change how a run went. Record sharing still decides which jobs they can edit.
- Activate the runner as an integration user that holds that set and the permissions every job needs. Health Check will tell you if that user is ever deactivated.
- Pair it with Kern Component Access if you want errors from the Scheduled Jobs pages saved to the log. Without that set, they go only to the browser console.
Running a failed API call again by hand works the same way. The Retry action on an API issue, the resolve action and the bulk retry (Retry Selected on the API Issues list) all run a failed call again, which can make an external system act a second time. So they need the Retry API Issue permission:
- Grant it through the Kern API Issue Resolver permission set, which ships assigned to nobody. The Kern Administrator set grants it too.
- The resolver set also lets its holder read every API issue and every API call (View All Records, so they see records other users made, which are otherwise private to their owner). Give it only to people who may see those calls.
- It grants no edit or delete access: the three retry actions mark an issue resolved for the resolver, and only after checking the Retry API Issue permission.
- Pair it with Kern Component Access if you want errors from the Retry and Dismiss actions saved to the log. Without that set, they go only to the browser console.
Deleting an API call or an API issue needs the Delete API Records permission, which the Kern Administrator set carries.
- These records are the history of calls to and from other systems, so the package refuses the delete to anyone else, a resolver included, with a message that says so.
- A scheduled purge of old API calls or API issues must run as a person who may delete them. Who that is, and how you widen it, is in Who can see the framework's own records?.
The runner's own records are managed by Health Check only. A save re-owns a record's scheduled job to the saving user, so if those records could be edited elsewhere a later edit would silently change who every job on the runner runs as.
Record Sharing
KernDX lets you choose the sharing behaviour when the code runs, so the same logic can enforce sharing for a UI user and bypass it for a system batch.
- A class's own declaration is fixed at compile time. A class declares
with sharing,without sharing, orinherited sharingwhen you write it, and you cannot change that decision later. - The runtime control over Salesforce sharing rules comes from a small "proxy" class pattern.
Who can see the framework's own records?
The framework saves four kinds of record of its own. All four are private by default, so a person sees a record only when they own it, sit above the owner in the role hierarchy, or hold View All Records on the object.
| Object | Sharing default | Who owns a record |
|---|---|---|
API Call (ApiCall__c) | Private | The user whose transaction made the call |
API Issue (ApiIssue__c) | Private | The user whose transaction made the failed call |
Log Entry (LogEntry__c) | Private | The automated user that saves log entries in the background, so no person owns one |
Async Chain Execution (AsyncChainExecution__c) | Private | The user whose transaction started the chain |
Three permission sets open these records to the people who need them:
| Permission set | What it grants | Why |
|---|---|---|
| Kern Administrator | View All Records on these objects | Your administrators see every record |
| Kern API Issue Resolver | View All Records on API issues and API calls | Your support team sees every issue and call without a sharing rule, as the Web Services Guide describes |
| Kern Log Console Read Only | Read and View All Records on log entries, the Log Console tab and the console itself, and nothing else | A reviewer or an operator reads the log without Kern Administrator |
The Kern Log Console Read Only set ships assigned to nobody. A log entry can hold what your code logged for every user's work, so assign the set only to people you would let read that; the Logging Guide explains what an entry holds.
One feature flag, BypassApiRecordDeleteGuard, decides who may delete an API call or an API issue:
It decides for every way in: a record page, a flow, your own Apex and the scheduled purge alike.
A built-in rule turns the flag on for every user who holds the Delete API Records permission, so your administrators can delete with nothing to set up. You do not see that rule in Setup, because it ships as a protected record of the package.
To let more people delete, add a
FeatureFlagStrategy__mdtrecord (a row that says who a flag applies to) for a profile, a permission set or one user.To let everyone delete, set Result On No Match on the flag record to true. Is Enabled By Default has no effect on this flag: a flag reads it only when it has no strategy records, and this one always has the built-in rule.
If you deactivate the flag record, nobody can delete an API call or an API issue, your administrators included, and every scheduled purge of them deletes nothing. The Data Retention check on the Health Check page warns you when that happens.
Record sharing and object permissions still apply on top of the flag: a person the flag is on for deletes only the records Salesforce already lets them delete.
These defaults are what a new install gets. An upgrade never changes your org's sharing default:
- An org that has had the package for a while may still show Public Read/Write for API Issue or Log Entry.
- Check under Sharing Settings, Organization-Wide Defaults, and set them to Private when you choose. The permission sets above keep your administrators and resolvers seeing every record.
Some framework screens read every user's records on purpose, whatever the sharing default:
- The Log Console lists, counts and groups every log entry. A log entry is owned by the background process that saved it, so a read limited to your own records would show nothing at all.
- This is safe because the package gives access to the console only through the Kern Administrator and Kern Log Console Read Only permission sets, and both already include View All on log entries.
- The console also shows each chain's name, number, status and launcher, and the user name of each entry, whoever's work the entry records. A holder sees these even with no access to async chains.
- The Chain Monitor's log stream and a scheduled job's last-run entry show the log entries of the one chain or job on screen. They read only for a user who may read log entries at all.
- The Health Check's Data Retention warning counts every record of each object. A count shows no record's content, and the check is about how much data your whole org holds.
Sharing Architecture
Sharing Control Points
You can control sharing at four points in the framework:
+-----------------------------------------------------------------------------+
| APPLICATION CODE |
+-----------------------------------------------------------------------------+
|
v
+-----------------------------------------------------------------------------+
| FRAMEWORK ENTRY POINTS |
| +---------------------+ +---------------------+ +---------------------+ |
| | QRY_Builder | | DML_Builder | | DML_Transaction | |
| | (Queries) | | (DML Operations) | | (Transactions) | |
| +----------+----------+ +----------+----------+ +----------+----------+ |
+-------------+----------------------------+----------------------------+------+
| | |
v v v
+-----------------------------------------------------------------------------+
| SHARING PROXY LAYER |
| +---------------------------------+ +---------------------------------+ |
| | Query path | | Save path | |
| | +----------------------------+ | | +----------------------------+ | |
| | | inherited: runs inline | | | | inherited sharing proxy | | |
| | | with sharing executor | | | | with sharing proxy | | |
| | | without sharing executor | | | | without sharing proxy | | |
| | +----------------------------+ | | +----------------------------+ | |
| +---------------------------------+ +---------------------------------+ |
+-----------------------------------------------------------------------------+
|
v
+-----------------------------------------------------------------------------+
| SALESFORCE DATABASE |
| Database.insert() / Database.query() / etc. |
+-----------------------------------------------------------------------------+Class Hierarchy
DML Operations:
DML_Transaction (inherited sharing)
+-- DML_Builder (inherited sharing)
+-- base save helper, internal (inherited sharing, virtual base)
+-- without-sharing save helper, internal (without sharing)
+-- with-sharing save helper, internal (with sharing)Query Operations:
QRY_Builder (inherited sharing)
+-- SEL_Base (inherited sharing)
+-- query runner, internal (inherited sharing)
+-- with-sharing query helper, internal (with sharing)
+-- without-sharing query helper, internal (without sharing)DML Sharing Enforcement
DML_Builder
When you save records, DML_Builder is the class that decides whether sharing rules apply. Behind the scenes it keeps a few small helper classes, each declared with a different sharing mode, and picks the right one for your transaction based on the methods you chain (this is the Strategy pattern: swap in different behaviour behind one interface).
Class Declaration:
global inherited sharing class DML_BuilderKey parts:
- Access-mode methods.
.withUserMode()/.withSystemMode()choose the access level (AccessLevel) for the transaction. - Sharing control.
.bypassSharing()switches to thewithout sharinghelper. - Helper classes. These run the actual save with a specific sharing mode (named by an enum inside the package that you never touch).
Per-Transaction Sharing Control
DML_Builder gives you one sharing override in code: .bypassSharing(). In system mode, if you do not call it, the transaction follows the caller's sharing context through the inherited sharing helper.
| Builder Method | Proxy Used | Effect |
|---|---|---|
| (default) | inherited sharing proxy | The proxy inherits the caller's sharing context, and under the shipped UserModeDml_Enabled default the save runs in user mode, where the platform enforces record sharing |
.bypassSharing() | without sharing proxy | The proxy stops enforcing sharing rules. In user mode the user's object and field permissions still apply |
There is no .withSharing() method on DML_Builder. To enforce sharing on a save, call the transaction from a with sharing class (or from one whose inherited sharing caller is itself with sharing). To enforce object and field permissions as well, add .withUserMode() (see Safe by Default).
One thing to know before you reach for .bypassSharing(): the sharing dial and the access mode are separate settings. Under the shipped defaults the save runs in user mode, and .bypassSharing() alone ignores record sharing but keeps the user's object and field permissions:
- A field the user cannot create (on an insert) or edit (on an update) is left out of the save, without an error. One warning in the log names the object and the fields, never their values.
- A save the user has no object permission for is refused, as user mode refuses it. Two more saves are refused: an upsert that matches on a key field the user cannot read or cannot edit, and a save that would leave out the lookup field you registered with its parent record.
If you save through DML_Transaction and call setAccessLevel(AccessLevel.USER_MODE.withPermissionSetId(permissionSetId)), these checks do not run. Salesforce applies the user's permissions plus the permission set's, and record sharing. So commitWork(false), the transaction's own way to ignore record sharing, does not ignore it for that save.
A save that must also write fields the user cannot edit needs .bypassSharing() and .withSystemMode() together. .withSystemMode() turns off the object and field permission checks as well.
How the Proxy Pattern Works
KernDX keeps a small helper class for each sharing mode, each declared with a different sharing keyword, and routes your save through the matching one. The helpers and the list of modes are internal to the package, so you drive the choice through the fluent builder methods rather than touching them yourself:
| Builder Method | Proxy Class (internal) | Sharing Declaration | Effect |
|---|---|---|---|
.bypassSharing() | The without-sharing save helper | without sharing | DML ignores sharing rules |
| (default, any caller) | The base save helper | inherited sharing | DML inherits caller's context: sharing rules apply when the caller is with sharing |
| (only when sharing is enforced explicitly, as the framework does for a save inside a background job) | The with-sharing save helper | with sharing | DML respects sharing rules |
Why this matters:
In plain Apex, the class declaration fixes the sharing behaviour when you compile, and you cannot change it at run time. The helper-class approach gets around that by handing the save to a class that already has the sharing mode you want.
What this buys you: in system mode the save follows the sharing of the class that calls the builder. User mode, the default, always enforces the running user's sharing.
- Enforcing from a
without sharingcodebase. Even if most of your code lives in awithout sharingclass, running a save from inside a dedicatedwith sharingclass that callsDML_Builder.newTransaction()...execute()respects sharing rules. Theinherited sharinghelper takes that class'swith sharingcontext. - The reverse also works:
.bypassSharing()on the builder deliberately picks thewithout sharinghelper. - Add
.withUserMode()to enforce object and field permissions at the database as well. It keeps the object and field checks even if theUserModeDml_Enabledflag is switched off.
AccessLevel Selection
Every DML_Builder transaction settles on an access level (AccessLevel) the moment .execute() runs:
.withUserMode()forcesAccessLevel.USER_MODE(object permissions, field security, and sharing all enforced; with.bypassSharing(), sharing is ignored and the permissions still apply)..withSystemMode()forcesAccessLevel.SYSTEM_MODE(object and field permission checks skipped; sharing still controlled by the helper class).- If you call neither, the
UserModeDml_Enabledfeature flag decides. It shipstrue, so USER_MODE is used; if someone flips it tofalsein metadata, SYSTEM_MODE is used.
// User-facing DML: enforce CRUD, FLS, sharing
DML_Builder.newTransaction()
.doInsert(accountFromUi)
.withUserMode()
.execute();
// Framework-internal DML (log events, orchestration rows): bypass CRUD/FLS
DML_Builder.newTransaction()
.doInsert(logEntryEvent)
.withSystemMode()
.execute();Important:
AccessLevel.SYSTEM_MODEskips field and object permission checks, but it does not turn off sharing. The sharing mode on the helper class (with sharing/without sharing/inherited sharing) still decides which records the code can reach.
Query Sharing Enforcement
QRY_Builder Sharing Control
QRY_Builder uses the same helper-class approach for queries, so you can control sharing one query at a time or set a default for the whole org.
Class Declaration:
global inherited sharing class QRY_BuilderHow Query Sharing Works
Just as with saves, QRY_Builder uses helper classes to control sharing on a query. The method you chain decides which helper runs it, and if you chain neither the query runs inline in whatever context called it:
| Sharing Method | Effect |
|---|---|
| (default) | In user mode (the shipped default) record sharing is always enforced. In system mode the query runs inline, so it inherits the calling class's sharing context |
.withSharing() | The query is handed to a with sharing executor, so sharing rules are enforced. This changes something only in system mode: user mode enforces sharing anyway |
.bypassSharing() | The query is handed to a without sharing executor, so sharing rules are bypassed. In user mode the user's object and field permissions still apply |
The sharing methods give you three distinct behaviours:
- Default (no method called). In user mode, the query always enforces sharing. In system mode, it follows the calling class's own sharing declaration: if your class is
with sharing, the query enforces sharing; ifwithout sharing, it bypasses. .withSharing(). Always enforces sharing, whatever the caller's context. In user mode it changes nothing on its own, because user mode enforces sharing already. It matters in two cases: afterbypassSharing(), where it cancels the bypass, and on a query that also calls.withSystemMode()..bypassSharing(). Always bypasses sharing, whatever the caller's context. Use this for system operations. In user mode the read still checks the user's object and field permissions: see USER_MODE vs Sharing Proxy.
So the same query can run in different security contexts without you editing the query itself.
Org-Wide Access Mode Override
There is no single per-transaction flag that flips every query between with and without sharing at once. When you want consistent behaviour across many queries, use one of the three approaches below.
1. Per call on each query. Chain .withSharing() / .bypassSharing() on individual QRY_Builder calls, or .withUserMode() / .withSystemMode() to also control object and field permissions.
2. Per selector. Your own SEL_* classes that must always run in SYSTEM_MODE (readers of custom metadata, system-schema selectors) override systemModeRequired():
global inherited sharing class SEL_MyInternalCmdt extends SEL_Base
{
global SEL_MyInternalCmdt() { super(MyInternalCmdt__mdt.SObjectType); }
global override Boolean systemModeRequired()
{
return true;
}
}3. Org-wide emergency off-switch. Set the kern__FeatureFlag.UserModeQueries_Enabled custom metadata record to IsEnabledByDefault__c = false. Every query your code can reach falls back to SYSTEM_MODE on the next transaction. The companion flag UserModeDml_Enabled does the same for DML_Builder. See Safe by Default.
Which to use: the per-call override for one-off exceptions, the per-selector override for framework-internal classes, and the metadata off-switch only to roll the secure default back in an emergency. Do not flip the metadata flag as a routine setting: it weakens the protection on every query your code can reach.
QRY_Builder Security Methods
Every read goes through a selector, and a selector's query property is a QRY_Builder (the fluent query builder, configured with short chained calls). So these are the security options you chain on query. They are independent and combinable:
Security Method Summary
| Method | Effect | When to Use |
|---|---|---|
withUserMode() | Runs in USER_MODE (enforces CRUD, FLS, sharing at DB level) | User-facing code requiring full security |
stripInaccessible() | Removes inaccessible fields from results after the query runs, in SYSTEM_MODE. In USER_MODE, the platform refuses a query that selects a field the user cannot read | When you want the rows back without the hidden fields, rather than an error |
withSharing() | Uses with sharing proxy class | Enforce sharing in SYSTEM_MODE queries (USER_MODE enforces sharing anyway) |
bypassSharing() | Uses without sharing proxy class. In USER_MODE the object and field checks still apply and hidden fields are removed | Read records whatever their sharing (use with caution) |
withoutSecurity() | Waives object and field checks and record sharing in one call (SYSTEM_MODE plus the sharing bypass); ignores the flag default | System-level reads that must span every record; audited as both a mode and a sharing bypass |
Default Behaviour
By default, every query your code can reach runs in USER_MODE with inherited sharing, driven by the UserModeQueries_Enabled feature flag (shipped true). USER_MODE enforces object permissions, field security, and sharing at the database.
- Opting out: framework-internal selectors return
truefromsystemModeRequired(), and individual calls use.withSystemMode(). - The emergency off-switch: if someone flips
UserModeQueries_Enabledtofalse, every query falls back to SYSTEM_MODE on the next transaction.
USER_MODE vs Sharing Proxy
In USER_MODE (the default, or withUserMode()), the database always enforces record sharing. So in USER_MODE, withSharing() changes nothing on its own. After bypassSharing(), it cancels the bypass. Otherwise it matters only in SYSTEM_MODE.
bypassSharing() works in both modes. In USER_MODE it ignores record sharing and keeps the user's object and field permissions.
- A hidden field is removed from the rows and not reported when it is a field of the queried object, or the last field of a path whose lookups and parent objects the user can read, such as
PhoneinAccount.Phone. This holds in child rows and in rows taken from the query cache too. - The read is refused, before any query runs, when it selects a path through a lookup or a parent object the user cannot read. This holds wherever the path comes from:
fields(),relatedField(), a field set, a selector's default fields, a child query, or inside a function such astoLabel().- A hidden lookup, such as
What.Namewithout read onWhatId, or a lookup of your own, such asParent__r.Namewithout read onParent__c, givesUTIL_Exceptions.IllegalStateException(labelQueryBuilder_BypassSharingLookup_NotReadable). - A hidden parent object, such as
Account.Nameon a contact for a user who cannot read accounts, gives aQueryExceptionthat names the object. - A
TYPEOFneeds read on its lookup and on each object afterWHEN.
- A hidden lookup, such as
- The read is refused when a child query added with
subselect()goes through a lookup the user cannot read, such asWhatIdfor theEventsof an account, even when the child query selects onlyId. Where one relationship name stands for two lookups, the user must be able to read both. The child query is checked as the object its relationship reads. - Selected text the builder cannot check is refused with
UTIL_Exceptions.IllegalStateException(labelQueryBuilder_BypassSharingSelectedText_NotCheckable), even for a user who can read everything: here KernDX is stricter than a USER_MODE query. Once functions are taken off, each selected item must be a field name or a path such asAccount.Name. So:- add a child query with
subselect(), never as text such as'(SELECT Id FROM Contacts)', and give it a relationship name the object has; - write each
TYPEOFas a field of its own:TYPEOF What WHEN Account THEN Name, Phone ELSE Name END.
- add a child query with
- The read is refused before any query runs, with a
QueryException, when the user cannot read the object (or the object of a child query, or of a query insideisIn()ornotIn()). - The read is refused before any query runs, with
UTIL_Exceptions.IllegalStateException, when a filter or a sort you build with the builder (condition(...),orderBy(...)) uses a field the user cannot read. The rows such a filter lets through would show something about that field. toQueryLocator(),toCursor(),toAggregateList(),getFirstAggregate()and any read of a grouped query (count()included) are refused withUTIL_Exceptions.IllegalStateException, because KernDX cannot remove hidden fields from them. AddwithSystemMode()to such a read.getPage()returns the page without hidden fields and withpage.cursorset to null. Ask for each later page withgetPage().count()andexists()read no fields and no child rows, so the checks on selected fields and on a child query's lookup do not apply to them. They still check a child query's object, as the object its relationship reads, and its filters and sorts.
The filter and sort check also looks inside functions and through parent records, in the main query and in every inner query:
- Functions. A field inside a date function such as
CALENDAR_YEAR(CloseDate)(with or withoutconvertTimezone()inside it),toLabel()orDISTANCE()is checked. This works whether you write the function as text or build it withQRY_Function. - Parent paths. A path such as
Account.Owner.Emailis checked up to five parents deep.- If the user cannot read a parent object on the path, the read is refused with a
QueryExceptionthat names the object. - If the user cannot read a lookup on the path or the last field, the read is refused with
UTIL_Exceptions.IllegalStateExceptionthat names the path.
- If the user cannot read a parent object on the path, the read is refused with a
- Lookups to more than one object. A lookup such as
What(Related To on a task or event),Who(Name) orOwneris read through a shared Name record, as a USER_MODE query reads it. The Name record is one Salesforce record (theNameobject) that stands for the related record, whatever its object. It holds only a few values, such as the record's name and its type. A filter, a sort or a selected field through it, such asWhat.NameorWho.LastName, needs read on the lookup field (WhatId,WhoId) only, not on the objects it can point to.- For some users Salesforce hides the Name record's
ProfileId,UserRoleIdandRecordTypeId. For them a filter or sort on those fields, such asWhat.ProfileId, and a path through them, such asOwner.Profile.NameorWhat.RecordType.Name, is refused. - Because the read ignores sharing, it covers every record of the queried object in the org: for
WhatandWho, every task and event. It can return the name of the related record, or find a row by that name, even when the user cannot open that record or read its object. For a person that includes the first and last name, and for a lead the company.
- For some users Salesforce hides the Name record's
A filter you write in your own QRY_Condition.Evaluable is not checked. Its rows can still show something about a field the user cannot read, so do not filter on such a field that way with bypassSharing().
When a read is refused because of a selected path or a child query, give the user read access to the lookup field or the parent object, or take the related fields (or the child query) out of the read. Or add withSystemMode(), which also turns off the object and field checks for that read.
With withSystemMode(), in either order, bypassSharing() ignores sharing and the object and field checks are off too.
Code Examples
// Default query - USER_MODE (FLS/CRUD/sharing enforced) when UserModeQueries_Enabled is true
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Name', 'Industry'})
.condition(Account.Type).equals('Customer')
.toList();
// USER_MODE - explicit opt-in (overrides flag if kill-switch has disabled it)
List<Account> userModeAccounts = QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Name', 'Industry'})
.withUserMode()
.toList();
// SYSTEM_MODE - explicit opt-out for framework-internal / CMDT reads
List<Account> internalAccounts = QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Name', 'Industry'})
.withSystemMode()
.toList();
// Strip inaccessible fields from results (SYSTEM_MODE: in USER_MODE a hidden field refuses the query)
List<Account> secureAccounts = QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Name', 'AnnualRevenue'})
.withSystemMode()
.stripInaccessible()
.toList();
// Enforce sharing via proxy class (SYSTEM_MODE only — redundant under USER_MODE default)
List<Account> sharedAccounts = QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Name', 'Industry'})
.withSystemMode()
.withSharing()
.toList();
// Bypass sharing via proxy class, USER_MODE: object and field checks kept, hidden fields removed
List<Account> everyAccount = QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Name', 'Industry'})
.bypassSharing()
.toList();
// Bypass sharing via proxy class in SYSTEM_MODE: no object or field checks either
List<Account> allAccounts = QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Name', 'Industry'})
.withSystemMode()
.bypassSharing()
.toList();
// Combine options as needed: system mode, sharing enforced, hidden fields removed instead of refusing the query
List<Account> strippedSharedAccounts = QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Name', 'AnnualRevenue'})
.withSystemMode()
.withSharing()
.stripInaccessible()
.toList();Profile Filtering. With the Enable Profile Filtering release update on, which Salesforce enforces in Winter '27, a user without the View All Profiles permission sees only their own profile:
- A query on
Profilereturns one row, and another user'sProfile.Namereads back as null. - The framework's profile-targeted feature flags and its
kern.SEL_Profileandkern.SEL_Userselectors read profiles in system mode, so what they see does not change. - Your own Apex that reads another user's profile name runs in user mode on API version 67.0 or later. For a user without that permission it gets no row or a null name, silently.
- When the code must see the profile whatever permissions the running user has, read it through
kern.SEL_User, which selectsProfile.Nameon every user it returns, or throughkern.SEL_Profile.
Configuring Sharing at Runtime
Org-Wide Access Mode Kill-Switches
There is no single per-transaction flag for DML sharing. The only org-wide controls are the two configuration records (FeatureFlag__mdt) that drive the secure default:
Setup -> Custom Metadata Types -> FeatureFlag -> UserModeQueries_Enabled
-> IsEnabledByDefault__c = true (package default — USER_MODE for all queries)
-> IsEnabledByDefault__c = false (emergency kill-switch — SYSTEM_MODE for all queries)
Setup -> Custom Metadata Types -> FeatureFlag -> UserModeDml_Enabled
-> IsEnabledByDefault__c = true (package default — USER_MODE for all DML)
-> IsEnabledByDefault__c = false (emergency kill-switch — SYSTEM_MODE for all DML)Flipping a flag takes effect on the next transaction across the org. Treat it as an emergency rollback lever, not a routine setting.
Per-Transaction DML Control
To set the access mode or sharing for one save, chain a method on DML_Builder. What the default and .bypassSharing() do, and what they still check, is in Per-Transaction Sharing Control; the access modes are in AccessLevel Selection. Here is each one in code:
// USER_MODE: enforce CRUD + FLS + sharing for this transaction
DML_Builder.newTransaction()
.doInsert(accountFromUi)
.withUserMode()
.execute();
// SYSTEM_MODE: bypass CRUD + FLS (e.g. framework log writes)
DML_Builder.newTransaction()
.doInsert(logEntryEvent)
.withSystemMode()
.execute();
// Sharing bypass (runs through without-sharing proxy); in USER_MODE the
// object and field checks still apply and fields the user cannot edit are left out
DML_Builder.newTransaction()
.doUpdate(records)
.bypassSharing()
.execute();
// Default (no access-mode or sharing method): follows the
// UserModeDml_Enabled flag (USER_MODE when true) + inherits caller's sharing
DML_Builder.newTransaction()
.doUpdate(records)
.execute();.bypassSharing() covers the whole transaction, so in the first sample below the account and its contact, saved together, both ignore sharing:
// Bypass sharing for the entire transaction (object and field checks still apply in USER_MODE)
DML_Builder.newTransaction()
.doInsert(account)
.doInsert(contact, Contact.AccountId, account)
.bypassSharing()
.execute();
// Default: inherits caller's sharing context
DML_Builder.newTransaction()
.doInsert(account)
.execute();Per-Query Sharing Control
When you want to set the sharing or access mode for one query without touching any others, use the fluent QRY_Builder API:
// USER_MODE: full CRUD + FLS + sharing enforcement for this query only
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Id', 'Name', 'Industry'})
.withUserMode()
.toList();
// SYSTEM_MODE + with-sharing proxy (sharing proxy only has effect in SYSTEM_MODE)
List<Account> sharedAccounts = QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Id', 'Name', 'Industry'})
.withSystemMode()
.withSharing()
.toList();
// SYSTEM_MODE + without-sharing proxy
List<Account> allAccounts = QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Id', 'Name', 'Industry'})
.withSystemMode()
.bypassSharing()
.toList();
// Waive every security check on this builder in one call
// (SYSTEM_MODE with record sharing bypassed, audited as both; opts out of USER_MODE even when the flag is true)
List<Account> unsecuredAccounts = QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Id', 'Name', 'Industry'})
.withoutSecurity()
.toList();Share Object Management
You want to grant a user access to some records by creating Share records (like AccountShare or OpportunityShare), but that needs elevated permissions the granting user may not have. The UTIL_Sharing utility handles this for you by bypassing sharing on the Share-object save.
Why bypass sharing for shares? The person granting access may not have direct access to the Share objects themselves. A manager sharing their Accounts with an assistant, for instance, needs the Share records created even though they cannot query AccountShare directly. The framework absorbs that complexity so you can focus on the business logic.
Usage:
// Grant permanent access to records
List<SObject> shares = UTIL_Sharing.grant(accounts, groupId, 'Read');
// Grant temporary access (auto-revoked after specified minutes)
List<SObject> tempShares = UTIL_Sharing.grantTemporary(accounts, groupId, 'Read', 30);The framework creates the right Share records with BYPASS sharing mode, so the operation succeeds no matter what permissions the calling user has on Share objects.
Sharing recalculation can run in the background. After a large change to groups or roles, Salesforce may recalculate the affected share records asynchronously rather than before the transaction returns. This comes from the "Update Apex Code and Flows for Changed Sharing Recalculation Behavior" release update, available since Spring '26 and enforced in Spring '27.
- The framework's own share records are written directly, so they are unaffected.
- Your own Apex, flows and tests might be affected. Code that changes a user's group or role and then, in the same transaction, expects a record to be visible through the resulting share will see the old answer once the update is on.
- What to do: move that expectation to a later transaction, or assert on the membership row rather than on visibility.
Classes with Explicit Sharing Declarations
Without Sharing Classes
Two framework classes are declared without sharing, which means their own internal operations bypass sharing rules. Only one of them is a class you call:
| Class | Purpose | Rationale |
|---|---|---|
TST_Factory | Test data creation | Tests have to seed records whatever the running user's record access happens to be |
TST_Factory:
global without sharing class TST_Factory- Creates test records, permission set assignments, share records and framework settings
- Has to work no matter how narrow the test user's access is
The second one is internal plumbing rather than API: one background-job processor, the engine that runs your queued and batch work, carries the same declaration.
Important: Even though these classes are declared
without sharing, any save you make through the framework'sDML_Buildermethods still flows through the sharing helper. Awith sharinghelper can override awithout sharingcaller, so you can still enforce sharing from awithout sharingclass:
- call the builder from a dedicated
with sharingwrapper; or- add
.withUserMode()to enforce object permissions, field security, and sharing at the database regardless of the caller's context.
With Sharing Classes
None of the classes you call is declared with sharing. The three that carry the declaration are all internal: the controllers behind the Log Console and the Chain Monitor screens, and the small bridge a component uses to read a feature flag. Each enforces sharing in its own right, whatever context it is called from.
You get the same guarantee in your own code without needing one of those. Declare your class with sharing and the framework's inherited sharing classes follow you into it, or add .withUserMode() to a single query or save (see Safe by Default).
One correction worth stating plainly, because the class name suggests otherwise:
global inherited sharing class UTIL_SessionEncryptionUTIL_SessionEncryption manages session-based encryption and decryption, and it follows the caller's sharing context like almost everything else in the framework. It does not impose sharing of its own.
Inherited Sharing Classes
Most framework classes use inherited sharing so they follow whatever sharing context the caller is in:
| Class | Purpose |
|---|---|
DML_Builder | Bulk DML operations |
DML_Transaction | Transaction management |
SEL_Base | Generic selector methods |
QRY_Builder | Fluent query builder |
UTIL_Sharing | Record sharing management |
All SEL_* selector classes | Object-specific selectors |
Extending Sharing Control
Creating Custom Selectors with Sharing Control
You can build your own selectors that use the same sharing controls, through SEL_Base and QRY_Builder:
public with sharing class SEL_CustomObject extends SEL_Base
{
public SEL_CustomObject()
{
super(CustomObject__c.SObjectType);
}
public override List<SObjectField> getFields()
{
return new List<SObjectField>
{
CustomObject__c.Name,
CustomObject__c.Status__c
};
}
/**
* @description Finds records by status with explicit sharing control. In user mode (the default) sharing
* already applies, so withSharing() changes nothing; it keeps sharing on if the query runs in system mode,
* for example when the UserModeQueries_Enabled flag is turned off.
*
* @param status The status value to filter by.
*
* @return List of matching records.
*/
public List<CustomObject__c> findByStatus(String status)
{
return query.condition(CustomObject__c.Status__c).equals(status)
.withSharing()
.toList();
}
}Specialised Sharing Needs
The three built-in modes (BYPASS, ENFORCE, INHERITED) are fixed, and you cannot add a mode of your own. They cover the usual cases.
For specialised needs, consider these:
Combining with FLS Enforcement
// Enforce both sharing AND FLS via USER_MODE
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Id', 'Name'})
.withUserMode()
.toList();Creating Wrapper Methods
Write the wrapper as a method on your selector for the object, so sharing and field/object security are set in one place. Here it sits in a public with sharing class SEL_Accounts extends SEL_Base of your own that returns Id and Name from getFields(). The running user needs Read on Account and on the Id and Name fields:
public List<Account> findByIdSecure(Id accountId)
{
// Enforce both sharing AND FLS using USER_MODE (a field the user cannot read makes the query throw)
return query
.condition(Account.Id).equals(accountId)
.withUserMode()
.toList();
}Testing Sharing Behavior
Include tests that prove sharing behaves as expected:
@IsTest
private static void shouldEnforceSharingForCommunityUser()
{
// Test with restricted user
// Verify expected records are/aren't accessible
}
@IsTest
private static void shouldBypassSharingForBatchProcess()
{
// Test with restricted user running batch
// Verify batch can access all records
}Testing with Different Users
To prove sharing works, create test users with different permissions and check what each one can see:
@IsTest
private static void shouldRespectSharingRulesWhenEnforced()
{
// Create a restricted user
User restrictedUser = (User)TST_Builder.of(User.SObjectType)
.withOverride(User.ProfileId, getRestrictedProfileId())
.build();
// Create a record the restricted user cannot access
Account privateAccount = (Account)TST_Builder.of(Account.SObjectType)
.withOverride(Account.Name, 'Private Account')
.build();
Test.startTest();
System.runAs(restrictedUser)
{
// Query with sharing enforced
List<Account> results = QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Name'})
.condition(Account.Id).equals(privateAccount.Id)
.withSharing()
.toList();
// Should not find the record due to sharing
Assert.isTrue(results.isEmpty(), 'Restricted user should not see private account');
}
Test.stopTest();
}Verifying Sharing Enforcement
@IsTest
private static void shouldBypassSharingWhenConfigured()
{
User restrictedUser = (User)TST_Builder.of(User.SObjectType)
.withOverride(User.ProfileId, getRestrictedProfileId())
.build();
Account privateAccount = (Account)TST_Builder.of(Account.SObjectType)
.withOverride(Account.Name, 'Private Account')
.build();
Test.startTest();
System.runAs(restrictedUser)
{
// Query with sharing bypassed; the user still needs read access to Account
List<Account> results = QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Name'})
.condition(Account.Id).equals(privateAccount.Id)
.bypassSharing()
.toList();
// Should find the record with sharing bypassed
Assert.areEqual(1, results.size(), 'Should find private account with sharing bypassed');
}
Test.stopTest();
}Sharing Rules & Access
Security vs Sharing
Salesforce access control has three separate layers, and it helps to keep them straight because they answer different questions. KernDX lets you enforce each one on its own:
| Security Layer | What It Controls | Key Framework Class |
|---|---|---|
| Field-Level Security (FLS) | Which fields a user can read/write | QRY_Builder (.withUserMode(), .stripInaccessible()) |
| Object-Level Security (CRUD) | Create/Read/Update/Delete on objects | QRY_Builder (.withUserMode()) |
| Record-Level Security (Sharing) | Which specific records a user can access | DML_Builder / QRY_Builder |
Field-Level Security (FLS)
Field-level security controls which fields a user can read or change. You have two ways to enforce it.
Option 1: Enforce it in the query with withUserMode().
Adding .withUserMode() to a QRY_Builder query runs it in AccessLevel.USER_MODE, which enforces both field security and object permissions inside the SOQL itself:
- Field security: if the query selects, filters or sorts on a field the user cannot read, the query throws an exception.
- Object permissions: if the user lacks Read access to the object, the query throws an exception.
- Cache kept to one transaction: if you ask for the results to be cached, a user-mode read is kept in memory for the current transaction only, never in the shared platform cache. This stops results leaking between users with different access.
- The exception is a read that also calls
.bypassSharing(). Its rows do not depend on the user's sharing, so it may be kept in the shared platform cache, and the fields each user cannot read are removed when the rows are handed to that user.
- The exception is a read that also calls
// If user lacks FLS access to AnnualRevenue, query throws exception
// If user lacks CRUD Read on Account, query throws exception
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Name', 'AnnualRevenue', 'Industry'})
.withUserMode()
.toList();Option 2: Strip unreadable fields after the query with stripInaccessible().
Use this when you want the rows back without the hidden fields, rather than an error. The strip needs a query in system mode: in user mode the platform refuses the query before the strip can run. System mode does not check the object permission, and its record sharing follows the calling class unless you also call .withSharing():
// Strip inaccessible fields after query execution
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Name', 'AnnualRevenue', 'Industry'})
.withSystemMode()
.withSharing()
.stripInaccessible()
.toList();A read with .bypassSharing() in user mode removes the hidden fields on its own (see USER_MODE vs Sharing Proxy).
Object-Level Security (CRUD)
Object-level security controls who can create, read, update, and delete a given object. You have two ways to check it.
Option 1: From a Flow, with FLOW_CheckObjectPermissions.
FLOW_CheckObjectPermissions.DTO_Request request = new FLOW_CheckObjectPermissions.DTO_Request();
request.objectApiName = 'Account';
List<FLOW_CheckObjectPermissions.DTO_Response> perms =
FLOW_CheckObjectPermissions.checkPermissions(new List<FLOW_CheckObjectPermissions.DTO_Request>{request});
if(perms[0].hasCreateAccess)
{
// Proceed with insert
}Option 2: In the query, with withUserMode().
// Enforce CRUD at the query level — throws exception if user lacks Read access
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Name', 'Industry'})
.withUserMode()
.toList();Record-Level Security (Sharing)
Record-level security controls which specific records a user can reach. You control it through the sharing helpers described in the Record Sharing section.
AccessLevel Modes
Salesforce's AccessLevel setting decides whether object and field permissions are enforced on a database operation:
| Mode | FLS/CRUD | Sharing | When Used |
|---|---|---|---|
AccessLevel.USER_MODE | Enforced | Enforced (runs through the user's sharing). With .bypassSharing(), sharing is ignored and the object and field checks still apply | The secure default for the queries and saves your code can reach (shipped package behaviour) |
AccessLevel.SYSTEM_MODE | Bypassed | Controlled by the helper class (class declaration / .withSharing() / .bypassSharing()) | Framework-internal reads, custom-metadata readers, log and orchestration writes. Opt in with .withSystemMode() or systemModeRequired() |
By default, the QRY_Builder and DML_Builder calls your code can reach run in USER_MODE. SYSTEM_MODE is reserved for framework-internal operations and a few narrow, documented opt-outs:
- Framework-internal selectors override
SEL_Base.systemModeRequired()to returntrue; individual calls use.withSystemMode(). - The org-wide flip on
FeatureFlag.UserModeQueries_Enabled/UserModeDml_Enabledis an emergency off-switch only (see Safe by Default).
For how the sharing helper classes layer on top of AccessLevel.SYSTEM_MODE, see Record Sharing > AccessLevel Selection.
Combining All Three Security Layers
For the strongest protection in user-facing features, enforce object permissions, field security, and sharing on both the query and the save with .withUserMode():
public with sharing class SecureAccountController
{
public void createAccount(Account account)
{
// Insert with CRUD + FLS + sharing all enforced at the database level
DML_Builder.newTransaction()
.doInsert(account)
.withUserMode()
.execute();
}
public List<Account> queryAccounts()
{
// Query with CRUD + FLS + sharing all enforced via withUserMode()
return QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Name', 'Industry'})
.withUserMode()
.toList();
}
}Because the secure default already runs both queries and saves in
USER_MODE, the explicit.withUserMode()calls above are not strictly required. They are worth keeping anyway: they document the intent, and they protect you if someone has flipped theUserModeQueries_Enabled/UserModeDml_Enabledoff-switch tofalse.
The same checks in a class that also writes a log entry after the save:
public with sharing class SecureAccountManager
{
public static List<Account> getAccounts()
{
// Layer 1: Enforce CRUD + FLS + sharing via withUserMode()
return QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Name', 'Industry'})
.withUserMode()
.toList();
}
public static void createAccount(String name)
{
// Layer 1: USER_MODE DML enforces CRUD + FLS + sharing at database level
Account account = new Account(Name = name);
DML_Builder.newTransaction()
.doInsert(account)
.withUserMode()
.execute();
// Layer 2: Audit logging
LOG_Builder.build().info('Account created').emitAt('SecureAccountManager.createAccount');
}
}The same checks on one query on its own:
// Enforce complete security for user-initiated operations
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Id', 'Name', 'Industry'})
.withUserMode()
.toList();Common Sharing Patterns
Public Site / Community Controllers
Community and portal users should only see records they are entitled to. Enforce sharing in the controller so every operation respects the user's permissions.
Why enforce sharing here? External users reaching your app through Experience Cloud or a public site must never see records belonging to other users or organisations. Even when the Organization-Wide Default (OWD) is set correctly, enforcing sharing explicitly gives you a second line of defence.
public with sharing class CommunityAccountController
{
public List<Account> getMyAccounts()
{
// USER_MODE enforces CRUD + FLS + sharing at the database level
return QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Name', 'Industry'})
.withUserMode()
.toList();
}
public void updateAccount(Account account)
{
// USER_MODE DML fails if the community user lacks CRUD/FLS/sharing on the record
DML_Builder.newTransaction()
.doUpdate(account)
.withUserMode()
.execute();
}
}
.withUserMode()enforces object permissions, field security, and sharing at the database for everyQRY_Builder/DML_Buildercall inside the controller, andpublic with sharingon the class still applies to a builder call in it that switches to.withSystemMode(): both builders areinherited sharing, so that call keeps the controller'swith sharing. Belt and braces for guest and external-user contexts.
System Batch Processing
A batch job often needs to process every record of an object, whatever the running user can see. This is common for data maintenance, synchronisation, and cleanup.
Why bypass sharing here? A batch job runs as a specific user, usually a service account or whoever scheduled it. If you do not bypass sharing, the job only processes the records that user can see, and the rest go untouched. For a system-level job you want the whole dataset.
public without sharing class BATCH_ProcessAllAccounts implements Database.Batchable<SObject>
{
public Database.QueryLocator start(Database.BatchableContext context)
{
// SYSTEM_MODE + without-sharing proxy: process every record regardless of running user
return QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Id', 'Name', 'Status__c'})
.withSystemMode()
.bypassSharing()
.toQueryLocator();
}
public void execute(Database.BatchableContext context, List<Account> scope)
{
for(Account account : scope)
{
account.Status__c = 'Processed';
}
// SYSTEM_MODE DML + sharing bypass — explicit opt-out from the secure-by-default posture
DML_Builder.newTransaction()
.doUpdate(scope)
.withSystemMode()
.bypassSharing()
.execute();
}
public void finish(Database.BatchableContext context)
{
// No static state to reset — each DML_Builder / QRY_Builder call is scoped to its
// transaction via the fluent methods above. Log bypass rationale for audit:
LOG_Builder.build()
.info('BATCH_ProcessAllAccounts finished with sharing bypass (system maintenance)')
.emitAt('BATCH_ProcessAllAccounts.finish');
}
}
- The query needs
.withSystemMode()here:toQueryLocator()with.bypassSharing()alone is refused, because KernDX cannot remove hidden fields from rows the platform fetches later.without sharingon the class plus.withSystemMode().bypassSharing()on each builder call makes the bypass explicit at every layer. Prefer this to a single flag set at the top of the transaction: the explicit chaining shows up in code review and leaves a record at the exact call site.
Trigger Actions
A trigger action should use inherited sharing so it follows whatever context the trigger is running in. A trigger runs with the permissions of the user who caused the change, but usually has system-level access to the records it processes.
Why inherited sharing here? Trigger actions are reusable pieces that may run in different contexts. inherited sharing keeps them correct whether they are called from a user context (where sharing is enforced) or a system context (where it is bypassed).
To override the caller's context for one query or save, use the fluent .withSystemMode() / .withUserMode() / .bypassSharing() methods on that specific DML_Builder / QRY_Builder call.
public inherited sharing class TRG_AccountSetDefaults extends TRG_Base implements IF_Trigger.BeforeInsert
{
public void beforeInsert(List<SObject> newRecords)
{
// inherited sharing - trigger runs in the caller's sharing context.
// This handler mutates in-memory only (no DML) so no access-mode decisions are needed.
for(Account account : (List<Account>)newRecords)
{
if(String.isBlank(account.Industry))
{
account.Industry = 'Other';
}
}
}
}Logging Operations
LOG_Builder bypasses sharing internally so that logging always succeeds:
// Logging works regardless of current user's sharing context
LOG_Builder.build().error(exception).emitAt('MyClass.myMethod');Why? Error logs have to be captured whatever the current user's permissions are. If logging failed silently, you would lose the diagnostic evidence exactly when you need it.
Security Considerations
When to Bypass Sharing
Bypass sharing with .bypassSharing() on the relevant QRY_Builder / DML_Builder call, and record why with TRG_Base.setBypassReason(String).
- In user mode the user's object and field permissions still apply: a read removes the fields the user cannot read, and a save leaves out the fields the user cannot edit.
- When the code must also reach fields the user cannot read or edit, or must return a query locator, a cursor or totals, use
.withSystemMode().bypassSharing(), which turns off the object and field checks too.
Typical cases:
| Scenario | Example |
|---|---|
| System batch processing | Nightly data cleanup jobs |
| Platform event triggers | Processing events from any context |
| Integration handlers | Receiving data from external systems |
| Logging and auditing | Ensuring all errors are captured |
| Share object management | Creating/deleting share records |
| Scheduled jobs | Jobs running as a specific user but needing full access |
| Test data factories | Tests need to create data regardless of test user |
When to Enforce Sharing
Enforce object permissions, field security, and sharing with .withUserMode() on the relevant QRY_Builder / DML_Builder call. This is already the default for the calls your code can reach; calling it explicitly makes the intent clear and protects you if the off-switch flag is ever flipped. Typical cases:
| Scenario | Example |
|---|---|
| Community/Portal pages | External users accessing data |
| Public sites | Unauthenticated or guest users |
| User-initiated actions | Any UI-driven operation |
| REST APIs exposed to partners | External system access |
| Reports and dashboards | User-facing data views |
| Lightning components | User interface interactions |
Cache Security
When you ask for a query's results to be cached, the framework decides where they may be kept from the query's security settings:
- A user-mode read is cached in memory for the current transaction only. It never goes into the shared platform cache, so another user never receives it.
- A system-mode read that only inherits the caller's sharing (no explicit sharing choice) is not cached at all.
- A read with
.bypassSharing()in user mode may be kept in the shared platform cache, because its rows do not depend on the user's sharing. The fields each user cannot read are removed when the rows are handed to that user.
// A user-mode read: if you also call .withCache(...), the result is kept for this transaction only, so it never reaches another user
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Name'})
.withUserMode()
.toList();Why? A cached result from one user could otherwise be served to another user with different access, leaking data between them.
Security Governance Evidence
KernDX provides durable, version-controlled evidence that feeds the governance process you already run. The benefit: the artifacts an auditor asks for come out of source control and reporting, not out of someone's memory.
KernDX is a framework, not a governance system. It does not store approvals, sign-offs, or decision history, and it is not your security system of record.
Masking Configuration as a Version-Controlled Record
Your masking rules and the fields they protect are defined entirely in metadata (MaskingRule__mdt and MaskingTarget__mdt). Because they are metadata, every change is deployable and lives in source control. So your version history is the change record: who committed it, when, the exact before-and-after, and (in a pull-request workflow) who reviewed it.
The Data Masking Advisor turns this into two exportable artifacts:
- Deployable masking configuration: a ready-to-deploy metadata bundle describing exactly which fields are masked, with which rule, and whether each assignment is active. You commit it to your own repository and deploy it through your pipeline. It is inert text: KernDX performs no deployment and writes no records on your behalf.
- Regulated-field inventory: a read-only census, downloadable as CSV or JSON, of the fields KernDX identifies as sensitive across an object or the whole org, together with their current masking status. This is the inventory you hand to an auditor or load into your system of record.
What this does, and does not, give you.
- They answer what is masked, with which rule, in what state, and as of which deployment. They are inputs to your security system of record; they are not the system of record itself.
- A metadata record cannot tell you who decided to enable or disable masking on a field, under whose authority, or who approved the exception, and you should not treat it as if it can.
- A commit name is not a decision-maker. On most teams the name on a commit belongs to whoever ran the deployment tool, not whoever made or authorised the decision, and many pipelines commit under a single service account.
- Attributable, authorised decisions (with separation between the person who requests a change and the person who approves it) belong in your change-management approval gates or your governance, risk, and compliance (GRC) system. KernDX feeds those systems; it does not replace them.
Recommended use.
- Keep masking configuration in source control and deploy it through a pipeline that requires review and approval, so the approval is captured by that gate.
- Export the regulated-field inventory before each audit and reconcile it into your system of record.
- Reserve direct edits to masking metadata in production Setup for emergencies. Those take effect on the next transaction but are recorded only in the Setup Audit Trail, which is a coarse and time-limited log, so back-port any emergency change to source promptly.
Access-Review Primitives
Confirming that each user's access is still appropriate, certified by a business owner with stale access removed, is a process your organisation owns. KernDX does not run that review or store its sign-offs. It gives you two building blocks that supply the evidence and the remediation the review depends on:
- Login-activity reporting (Login Frequency). A scheduled processor rolls each user's login history up into per-user, per-month records (total logins and unique active days) shown on the Login Frequency tab. This is the "is this person actually using this access?" evidence that makes a review meaningful, and it surfaces dormant accounts before they become an audit finding.
- Automated deactivation of inactive users. The Deactivate Inactive Users scheduled job deactivates users in chosen profiles who have not logged in for a configurable number of days (with batch-size and all-or-nothing controls). Schedule it from the Scheduled Job editor to clear out dormant access continuously, so each review starts from a cleaner baseline.
What this does, and does not, give you. These building blocks produce activity evidence and automate one common remediation. They do not certify access, capture a business owner's approval, or track remediation sign-off; that recertification step remains a documented process in your system of record. KernDX is deliberately not a recertification engine.
Security Boundaries and Portal Hardening
KernDX gives you security mechanisms. It does not run org-wide security monitoring or make an org compliant on its own.
- The full map: for the control-by-control map of what KernDX evidences versus what stays your own configuration, see the Security Benchmark for Salesforce Alignment section.
- The two patterns that benchmark expects you to get right in your own code are Parameter-Based Record Access in Portals and Flow Input-Variable Hygiene. What KernDX Does Not Monitor states plainly what KernDX does not watch for you.
Parameter-Based Record Access in Portals
A page that takes a record Id from the URL or an input parameter and then reads or writes that record without checking the running user lets a guest, community, or portal user reach records they should never see.
Security people call this an insecure direct object reference, or IDOR. This is application-code security, and it is yours to get right.
Here is the KernDX default that helps you: QRY_Builder and DML_Builder run in USER_MODE by default. So a record the running user cannot see is not returned, and a write the running user is not permitted to make is not committed, as long as you do not bypass it.
// Portal/guest-reachable controller: trust the platform, not the parameter.
@AuraEnabled
public static Case getCase(Id caseId)
{
// USER_MODE (the default) enforces the running user's CRUD, FLS, and sharing.
// A guest user who cannot see this Case gets an empty result — not someone else's record.
List<Case> cases = QRY_Builder.selectFrom(Case.SObjectType)
.fields(new List<String>{'Subject', 'Status'})
.condition(Case.Id).equals(caseId)
.withUserMode()
.toList();
return cases.isEmpty() ? null : cases[0];
}The rule of thumb: on any path a guest or external user can reach, keep USER_MODE on.
- Do not reach for
.withSystemMode()/.bypassSharing()to "make the query work," because that access check is exactly what the request needs. - KernDX documents this pattern, but it does not ship a scanner that detects IDOR in your code; finding it is your application-security review's job.
See When to Enforce Sharing for the matching sharing posture.
Flow Input-Variable Hygiene
An autolaunched flow invoked from a portal, guest, or community context carries the same risk: an input record variable can be controlled by the caller, so treat it as untrusted.
- Where the flow calls Apex, route that Apex through
QRY_Builder/DML_BuilderinUSER_MODEso access is enforced on the running user rather than on the flow's running context. - Never pass an input Id straight into a system-mode query.
- Scope the input variable to the records the flow is meant to touch, and validate it before acting on it.
The framework does not change a flow's run context:
- A flow launched from Apex, a trigger action included, inherits its caller's system context even when it is configured to run in user context.
- On API version 68.0 or later, saving the flow with the User Context–Enforces User Permissions option makes it run with the running user's access level whatever launched it; the Triggers guide explains when that is the right choice for a trigger action.
What KernDX Does Not Monitor
KernDX is an accelerator, not an org-security monitor. It deliberately leaves org-wide posture detection to the tools built for it. Concretely:
- Metadata-change governance. KernDX owns the source-control half: repeatable package builds, a refusal to build from a dirty working tree, and the bypass-alert pair on the CI pipeline. Detecting org-wide config drift and unauthorized changes belongs to your deployment platform and to Salesforce Shield or AppOmni. KernDX ships no Setup Audit Trail monitor.
- Backup and recovery. KernDX ships no org backup. Use a dedicated backup-and-recovery solution.
- API and login monitoring.
ApiCall__crecords only the callouts KernDX routes; it is not an org-wide API-usage log. Org-wide API, login, and anomaly monitoring is Salesforce Event Monitoring and your SIEM. - Org security baseline. KernDX's own Health Check verifies KernDX configuration (cache allocation, masking posture, scheduled jobs). It is not the native Salesforce Security Health Check, which scores your org against Salesforce's baseline. Run that separately.
Testing
You test security by checking two things:
- that a permission check throws the right exception for a user who is not allowed;
- that sharing enforcement actually hides records the user should not see.
KernDX tests its own internal security classes, so your tests can focus on what is yours: that your code calls the security APIs correctly and handles the exceptions.
Testing object and field permission enforcement with withUserMode():
@IsTest
private static void shouldEnforceCrudWithUserMode()
{
User restrictedUser = TST_Factory.newUser('Minimum Access - Salesforce');
System.runAs(restrictedUser)
{
try
{
QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Name'})
.withUserMode()
.toList();
Assert.fail('Should throw exception for user without Account read access');
}
catch(Exception error)
{
Assert.isInstanceOfType(error, QueryException.class, 'A user without Account read access should get a QueryException');
}
}
}Testing sharing enforcement with QRY_Builder:
@IsTest
private static void shouldRespectSharingRules()
{
Account privateAccount = (Account)TST_Builder.of(Account.SObjectType).build();
User restrictedUser = TST_Factory.newUser('Standard User');
System.runAs(restrictedUser)
{
List<Account> results = QRY_Builder.selectFrom(Account.SObjectType)
.condition(Account.Id).equals(privateAccount.Id)
.withSharing()
.toList();
Assert.areEqual(0, results.size(), 'Should not see records outside sharing rules');
}
}Testing encryption round-trips:
@IsTest
private static void shouldEncryptAndDecryptSuccessfully()
{
String plainText = 'sensitive-api-token-123';
String encrypted = UTIL_SessionEncryption.encrypt(plainText);
Assert.areNotEqual(plainText, encrypted, 'Encrypted value should differ from plain text');
String decrypted = UTIL_SessionEncryption.decrypt(encrypted);
Assert.areEqual(plainText, decrypted, 'Decrypted value should match original');
}For more detailed sharing test patterns, including System.runAs() and share-record verification, see the Testing Sharing Behavior subsection under Record Sharing.
Anti-Patterns
The common security mistakes (the risky habits worth catching in review):
| Anti-Pattern | Why It's Wrong | Instead |
|---|---|---|
| Performing DML without CRUD/FLS checks in user-facing code | Exposes data to unauthorized access and fails Salesforce security review | Use .withUserMode() on queries or .stripInaccessible() for post-query FLS |
| Using hardcoded field API name strings for security checks | Breaks silently when fields are renamed or deleted | Use SObjectField token references (e.g., Account.Name) for compile-time safety |
| Storing secrets in plain text (custom fields, custom settings) | Credentials are visible to admins and exposed in SOQL queries | Use UTIL_SessionEncryption for runtime encryption or Named Credentials for API secrets |
Relying solely on inherited sharing for security | Sharing context depends on the caller and may be unpredictable | Be explicit: use with sharing for user-facing code and without sharing only when justified |
Using .bypassSharing() without documentation | Unauditable privilege escalation that may violate compliance requirements | Document every sharing bypass with a code comment explaining the business justification |
Best Practices
Always Enforce CRUD/FLS in User-Facing Code
// WRONG: No permission checks
public static List<Account> getAccounts()
{
return [SELECT Id, Name FROM Account]; // Executes even if user lacks read permission
}
// CORRECT: Enforce CRUD/FLS at the query level
public static List<Account> getAccounts()
{
return QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Name', 'Industry'})
.withUserMode()
.toList();
}To add record sharing to these checks, see Combining All Three Security Layers.
Handle Security Exceptions Gracefully
public static List<Account> performSecureQuery()
{
try
{
return QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Name', 'AnnualRevenue'})
.withUserMode()
.toList();
}
catch(Exception e)
{
// Log the error
LOG_Builder.build().error(e).emitAt('MyClass.performSecureQuery');
// Show user-friendly message
throw new AuraHandledException('You do not have permission to perform this operation.');
}
}Encrypt Sensitive Data in Transit
// WRONG: Passing sensitive data in plain text between controllers
String token = userProvidedToken;
Cache.Session.put('api_token', token);
// CORRECT: Encrypt before passing through session state
String encryptedToken = UTIL_SessionEncryption.encrypt(userProvidedToken);
Cache.Session.put('api_token', encryptedToken);
// For persistent storage, use Shield Platform Encryption or Crypto.encrypt()
// with external key management instead of UTIL_SessionEncryptionBe Explicit About Sharing Context
Declare sharing explicitly on the class, and call the relevant access-mode method on each DML_Builder / QRY_Builder call where it matters for the feature:
// DO: Explicit sharing declaration + explicit USER_MODE on secure calls
public with sharing class MyController
{
@AuraEnabled
public static List<Account> getAccounts()
{
return QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Name', 'Industry'})
.withUserMode()
.toList();
}
@AuraEnabled
public static void saveAccount(Account account)
{
DML_Builder.newTransaction()
.doUpdate(account)
.withUserMode()
.execute();
}
}
// DON'T: Rely on implicit/unknown sharing
public class MyController
{
// Missing sharing declaration — defaults are org-dependent
}Keep Sharing Decisions at the Call Site
You choose the access mode and sharing per call, through the fluent methods. Each builder chain keeps its own choice, and the choice does not leak into other calls. There is no transaction-wide flag to save and restore, so make the bypass explicit at the exact call that needs it:
// Temporary, localised system operation — no cleanup needed
DML_Builder.newTransaction()
.doUpdate(records)
.withSystemMode()
.bypassSharing()
.execute();
// Surrounding calls still follow the secure-by-default posture (USER_MODE)
List<Account> userVisibleAccounts = QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Id', 'Name'})
.toList();Don't Log Sensitive Data
// WRONG: Logs plain text password
LOG_Builder.build().debug('User password: ' + password).emitAt('MyClass.login');
// CORRECT: Never log sensitive data
LOG_Builder.build().debug('Password validation completed').emitAt('MyClass.login');Decrypt Only When Necessary
// WRONG: Decrypt and store in memory longer than needed
String decryptedToken = UTIL_SessionEncryption.decrypt(encryptedToken);
// ... many lines of code ...
makeApiCall(decryptedToken);
// CORRECT: Decrypt just before use
makeApiCall(UTIL_SessionEncryption.decrypt(encryptedToken));Use Inherited Sharing for Reusable Code
For a utility method that gets called from different contexts:
// DO: Use inherited sharing for utilities
public inherited sharing class MyUtility
{
public static void processRecords(List<SObject> records)
{
// USER_MODE (the default) enforces the user's sharing; in SYSTEM_MODE sharing is determined by caller's context
DML_Builder.newTransaction().doUpdate(records).execute();
}
}
// DON'T: Hardcode sharing in reusable code
public without sharing class MyUtility // Always bypasses - may be security riskFor a class that holds security code, the same keyword respects the caller's sharing model:
// CORRECT: Respect caller's sharing model
public inherited sharing class SecureDataAccess
{
public static List<Account> getAccounts()
{
// USER_MODE (the default) enforces the user's sharing; in SYSTEM_MODE the query follows the calling context's sharing rules
return QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Id', 'Name'})
.toList();
}
}Document Sharing Decisions
Add ApexDoc comments that explain why a specific sharing mode is used, and record the bypass reason with TRG_Base.setBypassReason(String) so it lands on the LogEntryEvent__e audit trail under category BypassEvent:
/**
* @description Processes all accounts regardless of user access.
* Uses sharing bypass because this is a system-level batch operation that must
* process every record for data-integrity reconciliation.
*/
public void execute(Database.BatchableContext context, List<Account> scope)
{
TRG_Base.setBypassReason('Nightly data-integrity reconciliation batch');
DML_Builder.newTransaction()
.doUpdate(scope)
.withSystemMode()
.bypassSharing()
.execute();
}After you document a sharing choice, prove it in a test: see Testing Sharing Behavior.
Audit Sharing Bypasses
Keep a list of the places in your code that bypass sharing, and review it periodically:
| Class | Method | Bypass Reason |
|---|---|---|
BATCH_ProcessAllAccounts | execute() | System batch requires full access |
TRG_MyLogEvents | afterInsert() | Logging must always succeed |
API_IntegrationHandler | processPayload() | Integration data from trusted source |
Quick Reference
Encryption/Decryption
| Operation | Method | Returns |
|---|---|---|
| Encrypt plain text | UTIL_SessionEncryption.encrypt(String) | Base64-encoded encrypted string |
| Decrypt encrypted text | UTIL_SessionEncryption.decrypt(String) | Plain text string |
Key Management:
- Algorithm: AES256 with an HMAC-SHA256 tamper check
- Key Storage: Platform cache (session cache preferred, org cache fallback)
- Key Expiry: 8 hours (28,800 seconds)
- Automatic rotation: Yes
Sharing Reference Table
| Class | Sharing Declaration | Purpose |
|---|---|---|
DML_Builder | inherited sharing | Bulk DML operations with sharing proxy factory |
| The framework's base save helper (internal) | inherited sharing | Base DML proxy (virtual) |
| The framework's without-sharing save helper (internal) | without sharing | DML with sharing bypassed |
| The framework's with-sharing save helper (internal) | with sharing | DML with sharing enforced |
QRY_Builder | inherited sharing | Fluent query builder |
| The framework's query runner (internal) | inherited sharing | Query executor |
| The framework's with-sharing query helper (internal) | with sharing | Query with sharing enforced |
| The framework's without-sharing query helper (internal) | without sharing | Query with sharing bypassed |
DML_Transaction | inherited sharing | Transaction management |
TST_Builder | inherited sharing | Test data builder |
TST_Factory | without sharing | Test data factory |
UTIL_Sharing | inherited sharing | Share record management |
UTIL_SessionEncryption | inherited sharing | Session encryption |
Common Patterns
Secure Query Pattern (CRUD + FLS + Sharing):
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Name', 'AnnualRevenue'})
.withUserMode()
.toList();Secure Query Pattern (Strip Inaccessible, preserves partial results):
The strip needs SYSTEM_MODE, which does not check the object permission. In USER_MODE, the query fails if it selects a hidden field.
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Name', 'AnnualRevenue'})
.withSystemMode()
.withSharing()
.stripInaccessible()
.toList();Sharing-Bypass Query Pattern (object and field permissions kept):
List<Account> accounts = QRY_Builder.selectFrom(Account.SObjectType)
.fields(new List<String>{'Name', 'AnnualRevenue'})
.bypassSharing()
.toList();Secure DML Pattern (CRUD + FLS + Sharing):
DML_Builder.newTransaction()
.doInsert(accountList)
.withUserMode()
.execute();Sharing-Bypass DML Pattern (object and field permissions kept; fields the user cannot create or edit are left out):
DML_Builder.newTransaction()
.doInsert(accountList)
.bypassSharing()
.execute();Sharing-Bypass DML Pattern with no permission checks (system operations only):
DML_Builder.newTransaction()
.doInsert(accountList)
.withSystemMode()
.bypassSharing()
.execute();Encryption Pattern (Session-Scoped):
// Encrypt for secure session-scoped passing
String encrypted = UTIL_SessionEncryption.encrypt(sensitiveData);
Cache.Session.put('secure_payload', encrypted);
// Decrypt within the same session
String decrypted = UTIL_SessionEncryption.decrypt(
(String)Cache.Session.get('secure_payload')
);Related Documentation
- DML - Guide -
TST_Builderfor secure test data, DML_Transaction and bulk DML patterns - Utilities - Guide -
LOG_Builderfor security event logging - Web Services - Guide - API integration patterns
- Selectors - Guide - Query patterns with
QRY_Builder - Logging - Guide - Error logging that bypasses sharing
- Triggers - Guide - Trigger action patterns with inherited sharing
External References:
- Salesforce Apex Security Guide
- Salesforce Crypto Class Reference
- Shield Platform Encryption
- OWASP Top 10
- Salesforce Sharing and Visibility Designer Guide
Framework Classes:
UTIL_SessionEncryption- Encryption/decryptionDML_Builder- DML operations with sharing proxyQRY_Builder- Fluent query builder with sharing and CRUD/FLS controlDML_Transaction- Transaction managementUTIL_Sharing- Share record managementTST_Builder- Test data factoryFLOW_CheckObjectPermissions- Object permission checks for Flows
This guide is part of the KernDX Developer Documentation. For questions or contributions, please contact the library maintainers.