Sub topic 12
When system mode is deliberate, and its pitfalls
User mode should be your default. A few jobs still need system mode, and those are where permission bugs tend to come from. This chapter covers when system mode is the right choice, how to keep it contained, and the mistakes that most often turn it into a data leak.
It assumes you know WITH USER_MODE, as user, and AccessLevel.USER_MODE, and that you can write a basic Apex test with System.runAs.
When system mode is the right choice
System mode means the code ignores the running user's object permissions (CRUD) and field-level security (FLS). Whether sharing rules apply depends on the class's sharing keyword. Use it only when the user is not the right authority for the data access. Common cases:
- System-owned records. An audit log, an integration log, or a consent record that users must not read or edit directly, but that your code must write on their behalf.
- Aggregates over data the user cannot see. A count, a total, or a "seats remaining" value computed across all records, returned without exposing any individual record.
- System-managed fields. A status, score, or timestamp that a user action triggers but the user must never set directly. The field is read-only to the user in their permission sets, and your code sets it.
- Platform automation. Triggers, batch jobs, and scheduled jobs that process data for the whole org. No single user's permissions describe what these jobs should do.
- Limited exposure to guest or community users. A public form that must create a lead or look up a store location, where the user's profile cannot be widened safely.
In each case, the code decides what is exposed. The user's permissions do not. That makes the code a security boundary, and it should be small enough to review in one sitting.
Make system mode explicit
An unmarked query in a class that never mentions permissions looks the same as one a developer forgot to secure. Write the mode out, so reviewers and static analysis can tell intent from oversight.
| Operation | Explicit system mode form |
|---|---|
| Static SOQL | `WITH SYSTEM_MODE` clause |
| Dynamic SOQL | `Database.queryWithBinds(soql, binds, AccessLevel.SYSTEM_MODE)` |
| Count queries | `Database.countQueryWithBinds(soql, binds, AccessLevel.SYSTEM_MODE)` |
| DML statement | `insert as system record;` |
| Database DML methods | `Database.insert(records, allOrNone, AccessLevel.SYSTEM_MODE)` |
The explicit form does not change behavior compared with leaving it out. It changes what a reader can tell at a glance, and it gives you a string to search for in a security review.
System mode and sharing are separate settings. Under AccessLevel.SYSTEM_MODE, record sharing is still decided by the class's sharing keyword. User mode enforces sharing no matter which keyword the class uses.
Keep the system-mode code small and narrow
Put system-mode work in its own class with a narrow method signature. Do the user-facing work in user mode, then call the helper for the one step that needs elevated access.
The example assumes a custom object Audit_Log__c with two text fields, Action__c and Record_Ref__c. Standard users have no access to this object.
public with sharing class AccountService {
public static void rename(Id accountId, String newName) {
Account acct = [
SELECT Id, Name
FROM Account
WHERE Id = :accountId
WITH USER_MODE
LIMIT 1
];
acct.Name = newName;
update as user acct;
AuditWriter.record('Account renamed', accountId);
}
}public without sharing class AuditWriter {
public static void record(String action, Id recordId) {
Audit_Log__c entry = new Audit_Log__c(
Action__c = action,
Record_Ref__c = String.valueOf(recordId)
);
Database.insert(entry, true, AccessLevel.SYSTEM_MODE);
}
}The user's access to the account is checked in user mode. If they cannot edit Name, the update as user throws before the audit entry is written. Only the log write runs in system mode, and the helper accepts two values, an action label and an Id. It cannot be turned into a general-purpose "read anything" method.
An aggregate helper follows the same pattern. It returns a number and no records:
public without sharing class TerritoryStats {
public static Integer countAccounts(String industry) {
Map<String, Object> binds = new Map<String, Object>{ 'industry' => industry };
return Database.countQueryWithBinds(
'SELECT COUNT() FROM Account WHERE Industry = :industry',
binds,
AccessLevel.SYSTEM_MODE
);
}
}Rules that keep these helpers safe:
- Give each helper one job and a name that says what it does.
- Take typed, minimal inputs. Avoid passing in a query string, an object name, or a field name.
- Return the least data that answers the question: a number, a boolean, or a small wrapper class.
- Never put
@AuraEnabledor@InvocableMethodon a system-mode method that takes arbitrary input. Call it from a user-mode method that validates the request first. - Leave a short comment saying why system mode is needed, so the next reader does not "fix" it.
The last branch matters. If a user legitimately needs the access, a permission set is the correct fix. Code that works around a missing permission hides the gap from admins and tends to outlive the business reason for it.
Pitfalls
The sharing keyword does not check CRUD or FLS
with sharing limits which records a query returns. It does not check object permissions or field-level security. A with sharing class that runs SELECT Salary__c FROM Employee__c without WITH USER_MODE still returns the salary field to a user who has no read access to it.
The reverse also holds. without sharing removes record-level filtering but says nothing about fields. Treat the two settings independently and decide both for every class.
Sharing is inherited in confusing ways
- An inner class does not inherit the sharing setting of its outer class. Declare it on the inner class too.
- A
with sharingclass that calls awithout sharingclass runs that callee without sharing. Control returns to the caller's setting afterward. - A class with no sharing keyword takes the sharing of whatever calls it. When it is the entry point, the result depends on the context, so do not rely on it.
Use inherited sharing when you want a class to adopt its caller's setting on purpose. As an entry point it runs with sharing, which is the safer default. Write with sharing or without sharing on every class so the choice is visible.
Triggers run in system mode
A trigger does not follow the user's CRUD or FLS. This has a consequence for user-mode DML. insert as user checks the user's permissions on the records in that statement, but triggers fired by the statement run in system mode. If a trigger updates a second object, nothing checks the user's access to that object, unless the trigger code uses user mode itself.
For the same reason, as user does not guarantee that the user could have made every change in the transaction. It guarantees that the DML statement you wrote was permitted.
Tests and anonymous Apex run in system mode
Test methods and anonymous Apex run without enforcing the current user's CRUD and FLS unless your code asks for it. System.runAs switches the user context, which affects record sharing and the user identity the code sees. It does not turn a system-mode query into a user-mode one.
A test can therefore pass when a query has no WITH USER_MODE at all. To test enforcement, run the production code under System.runAs with a low-privilege user and assert that it throws, as shown in the testing chapter. Add a test for each system-mode helper too, confirming it still works for that low-privilege user.
Returning too much from a system-mode method
The usual leak is the return value. A helper that loads whole Account records in system mode and hands them to a Lightning component exposes every field it queried, whatever the user's FLS says. Return a wrapper class with only the fields the screen needs.
public with sharing class StoreLocator {
public class StoreInfo {
@AuraEnabled public String name;
@AuraEnabled public String city;
}
@AuraEnabled(cacheable=true)
public static List<StoreInfo> findStores(String city) {
List<StoreInfo> result = new List<StoreInfo>();
for (Account a : StoreReader.byCity(city)) {
StoreInfo info = new StoreInfo();
info.name = a.Name;
info.city = a.BillingCity;
result.add(info);
}
return result;
}
}StoreReader.byCity would be the narrow system-mode helper. The controller copies two fields into the wrapper, so nothing else reaches the browser.
User mode does not stop injection
System mode and user mode both run whatever query string you give them. A dynamic query built by concatenating user input can still be altered by that input, and in system mode the altered query reads data the user could never reach. Use bind variables, as in the examples above. If you must accept an object or field name from the caller, check it against an allow-list you control.
Failures pass silently
With Database.insert(records, false, AccessLevel.SYSTEM_MODE) or any allOrNone = false call, failures come back as SaveResult errors and no exception is thrown. A helper that ignores the result array loses data without any sign of it. Check isSuccess() on each result, or use allOrNone = true when a partial write would be worse than none.
Review checklist
Before approving a class that uses system mode, check these:
- Is every system-mode query or DML statement marked explicitly?
- Does the class declare
with sharing,without sharing, orinherited sharing, and does the choice match the intent? - Does the entry point, such as an
@AuraEnabledmethod, validate the caller's request in user mode before calling the helper? - Does the return type expose only what the caller needs?
- Is there a test with a low-privilege
System.runAsuser?
Exercise
A with sharing class runs SELECT Id, Salary__c FROM Employee__c with no WITH USER_MODE. A user without read access to Salary__c calls it. Does the user receive the salary values, and why?
Show answer
Yes. The with sharing keyword only filters which records are returned according to sharing rules. It does not check object permissions or field-level security, so the query returns Salary__c values. Adding WITH USER_MODE makes the query enforce FLS and throw a QueryException.
Exercise
A trigger on Contact inserts an Audit_Log__c record. A user inserts a Contact with insert as user, and the user has no access to Audit_Log__c. Does the insert fail? What should the trigger do if it needs to enforce the user's permissions on the log object?
Show answer
The insert succeeds. The trigger runs in system mode, so as user on the Contact insert does not extend to the trigger's DML. If the log write should respect the user's permissions, the trigger code must use user mode itself, for example insert as user. Usually the log object is meant to be system-owned, so the better choice is to keep the write in system mode, mark it with AccessLevel.SYSTEM_MODE, and put it in a small helper class.
Exercise
Why does a test that calls a query without WITH USER_MODE inside System.runAs(lowPrivilegeUser) still pass, and how do you make the test prove enforcement?
Show answer
System.runAs changes the user context and record sharing, but the code still runs in system mode for CRUD and FLS unless the query asks for user mode. To prove enforcement, the production code must use WITH USER_MODE (or AccessLevel.USER_MODE), and the test must assert that a QueryException is thrown when the low-privilege user calls it.