Sub topic 3
What User Mode Enforces
This chapter assumes you can read basic Apex and SOQL, you know how profiles and permission sets grant object permissions (CRUD) and field-level security (FLS), and you have seen with sharing in a class declaration. The earlier chapters covered why Apex runs in system mode and how sharing differs from CRUD and FLS. Here you learn exactly which checks user mode adds, which it leaves out, and how it behaves in the places that surprise people.
The short definition
User mode is an access level for a single database operation. When a SOQL query or DML statement runs in user mode, Salesforce evaluates it against the permissions of the running user. It checks three things:
- Object permissions: can the user read, create, edit, or delete this object?
- Field-level security: can the user read, or create and edit, each field the operation touches?
- Sharing: can the user see or modify each individual record?
System mode, the default for Apex, skips the first two checks. It applies the third only if the class declares with sharing or inherited sharing and inherits a sharing context. User mode applies all three, every time.
| Check | System mode (default) | System mode in a `with sharing` class | User mode |
|---|---|---|---|
| Object permissions (CRUD) | Not checked | Not checked | Checked |
| Field-level security | Not checked | Not checked | Checked |
| Record sharing | Not checked | Checked | Checked |
The table shows why with sharing is not a substitute. It fills in only one row.
The checks, in order
Think of user mode as a gate with three checks. A failure at any one stops the operation.
The third check behaves differently from the first two. A sharing failure on a query does not throw. The records the user cannot see are left out of the result, exactly as in a with sharing class. Object and field failures stop the whole operation.
Object permissions
For each object the operation touches, the user needs the matching permission:
- Querying needs Read.
insertneeds Create.updateneeds Edit.deleteneeds Delete.undeleteneeds Delete, andupsertneeds both Create and Edit.
Permissions that act as overrides count too. If the user's profile or a permission set grants View All Data or Modify All Data (or the per-object View All and Modify All), user mode honors them. User mode does not apply stricter rules than the user's real permissions. It applies those permissions.
Field-level security
Field checks depend on the kind of operation:
- A query needs the field to be readable.
- An
insertneeds each populated field to be createable by the user. - An
updateneeds each changed field to be updateable by the user.
Two details matter in practice.
First, user mode checks every field the statement references, not only the ones in the SELECT list. A field used in WHERE or ORDER BY must be readable too. This closes a leak. Without it, a user could infer the value of a hidden field by filtering on it and watching which rows come back.
Second, relationship fields are checked along the path. A query that reaches through a lookup, such as Account.Owner.Email, needs access to the related object and the field at the end of the path.
Here is a query that reads a field in WHERE that it never selects:
public with sharing class HighValueAccounts {
public static List<Account> findLarge() {
return [
SELECT Id, Name
FROM Account
WHERE AnnualRevenue > 1000000
WITH USER_MODE
];
}
}AnnualRevenue does not appear in the SELECT list. If the running user has no read access to it, the query still fails. The check follows the field wherever it is used.
Sharing, even without `with sharing`
This is the most important point to take away. User mode enforces the running user's sharing, whatever the class declares.
public without sharing class AuditReader {
public static List<Account> visibleToCurrentUser() {
return [SELECT Id, Name FROM Account WITH USER_MODE];
}
}The class says without sharing, so ordinary queries in it see every account. This one query asks for user mode, so it returns only the accounts the running user can see under the organization-wide defaults, role hierarchy, sharing rules, and manual shares. The per-operation access level overrides the class-level default for that statement.
The reverse also holds. Marking a class with sharing adds record filtering but still ignores object and field permissions. Using both is common and harmless. The with sharing declaration then protects the code that does not use user mode, and the user mode keywords protect the operations that do.
Scope: one operation at a time
User mode applies to the statement that requests it, and nothing else. It does not change the mode of the surrounding method, the class, or any code that method calls.
public with sharing class MixedModes {
public static void demo() {
// Checked against the user's permissions.
List<Account> checked = [SELECT Id, Name FROM Account WITH USER_MODE];
// Not checked for CRUD or FLS. Runs in system mode.
List<Contact> unchecked = [SELECT Id, Email FROM Contact];
System.debug(checked.size() + ' accounts, ' + unchecked.size() + ' contacts');
}
}The first query is gated. The second reads Email with no field check, even though both are in the same method of a with sharing class. If you want a method to be safe, every query and DML statement in it needs the keyword or an access-level argument. A single missed statement is a gap.
The same goes for helper code. If your user-mode method calls another class that runs its own system-mode queries, those queries are not checked.
DML in user mode
Writes follow the same three checks. The as user keyword requests user mode for one DML statement:
public with sharing class ContactWriter {
public static void create(String lastName, String email) {
Contact c = new Contact(LastName = lastName, Email = email);
insert as user c;
}
public static void rename(Id contactId, String newLastName) {
Contact c = [SELECT Id, LastName FROM Contact WHERE Id = :contactId WITH USER_MODE];
c.LastName = newLastName;
update as user c;
}
}For create, the user needs Create on Contact and create access to LastName and Email. For rename, the query needs Read on Contact and LastName. The update needs Edit on Contact, edit access to LastName, and sharing that allows editing that record. If the user can see the record but only has read access through sharing, the update is rejected.
Only the fields you actually set count. An insert that leaves Email empty does not need create access to Email. This makes the checks follow the data you send, not the full field list of the object.
What user mode does not do
Knowing the limits prevents false confidence.
- It does not check access to Apex classes. That is controlled by the user's class access settings and applies before any code runs.
- It does not restrict triggers, validation rules, flows, or other automation that fire as a result of the DML. Those still run in their normal system context, and that is intended. A user who can create a record should still trigger the logic that normally goes with it.
- It does not filter fields from a result. A query either passes or throws. If you want to silently drop inaccessible fields, that is the job of
Security.stripInaccessible, covered in a later chapter. - It does not enforce permissions on data that your code already holds in memory. If a system-mode query loaded a record, user mode does not check it later when you pass it to a method.
- It does not change what the user is allowed to do through the UI. It only makes your Apex follow the same rules the UI follows.
For some of these, other chapters give the remedy. The practical rule is to put the access level on the operation that touches the data.
What happens when a check fails
Object and field failures raise exceptions. A query in user mode throws a QueryException. A DML statement throws a DmlException. The Database methods that take an access level can instead report failures per record when you pass allOrNone as false. The next chapters cover catching these errors and the Database overloads in detail. For now, a short example shows the shape:
public with sharing class AccessProbe {
public static String tryRead() {
try {
List<Account> rows = [SELECT Id, Name, AnnualRevenue FROM Account WITH USER_MODE];
return 'Read ' + rows.size() + ' accounts';
} catch (QueryException e) {
return 'Blocked: ' + e.getMessage();
}
}
}The message names the object or field that caused the failure, which makes it a useful signal in logs. Do not show it to end users as it stands, because it can reveal field names the user was not meant to know about.
Common mistakes
- Assuming
with sharingis enough. It checks records only. A user with no read access toAccountcan still read accounts through awith sharingclass that uses system-mode queries. - Securing the
SELECTlist and forgettingWHERE. In user mode this is safe, becauseWHEREfields are checked. In older approaches it is not, which is one reason to prefer user mode. - Protecting one statement in a method with many. Each query and DML statement needs its own access level.
- Testing as the administrator. An administrator usually has every permission, so the test passes while a real user would fail. Tests need a low-privilege user, as the testing chapter shows.
- Using user mode in a context where the running user is not the person you mean. In a scheduled job or an asynchronous process, the running user is whoever the job runs as. User mode then enforces that user's permissions.
Exercise
A class is declared without sharing. One method runs [SELECT Id, Name FROM Account WITH USER_MODE]. The running user has Read on Account but can see only some of the accounts through sharing. What does the query return, and does it throw?
Show answer
It returns only the accounts the user can see under sharing, and it does not throw. User mode enforces the running user's sharing for that statement even though the class is without sharing. Object permission and field access both pass, so the only effect is that the unseen records are left out.
Exercise
A user has Read access to Account and to Account.Name, but not to Account.AnnualRevenue. A method runs [SELECT Id, Name FROM Account WHERE AnnualRevenue > 1000000 WITH USER_MODE]. Does it succeed? Explain why.
Show answer
It fails with a QueryException. User mode checks every field the query references, including fields in the WHERE clause. Because the user cannot read AnnualRevenue, the query is rejected even though AnnualRevenue is not in the SELECT list.
Exercise
A method in a with sharing class runs one user-mode query and then one plain insert statement on the same object. Which of the two statements checks the user's object permission and FLS, and which checks sharing?
Show answer
Only the user-mode query checks object permission and FLS. The plain insert runs in system mode, so it skips both. Sharing applies to the query because of user mode, and it applies to the insert only as far as the with sharing declaration affects that operation. To check CRUD and FLS on the write, use insert as user.