Sub topic 11
Enforcing sharing, CRUD and field-level security with user mode
This chapter assumes you can write Apex classes and static SOQL, and that you know what sharing rules, object permissions and field-level security (FLS) are. It also assumes you have read the earlier chapters on Database.query, bind variables and allowlisting.
Injection defenses control what a query says. Permission enforcement controls what the query is allowed to return, whatever it says. You need both. If a mistake lets a query change shape, user mode limits what the changed query can read.
Why a `with sharing` class is not enough
Apex runs in system mode by default. The code can read and write anything, regardless of the running user's permissions. The with sharing keyword narrows this in one way only:
| Control | Enforced by `with sharing`? | Enforced by user mode? |
|---|---|---|
| Record visibility (sharing rules, role hierarchy) | Yes | Yes |
| Object permissions (CRUD) | No | Yes |
| Field-level security (FLS) | No | Yes |
So this method, in a with sharing class, still returns fields that the running user cannot see:
public with sharing class AccountSearch {
public static List<Account> findByName(String name) {
return Database.query('SELECT Id, Name, AnnualRevenue FROM Account WHERE Name = :name');
}
}Records are filtered by sharing. A user whose profile hides AnnualRevenue still gets it, because the query runs without FLS checks. Dynamic SOQL makes this worse. Field names often come from callers, such as a Lightning component that sends a list of columns. Without enforcement, the caller can ask for any field.
User mode and system mode
An access level tells the platform whose permissions to apply. Apex has the AccessLevel class with two values:
AccessLevel.USER_MODEapplies the running user's sharing, object permissions and FLS.AccessLevel.SYSTEM_MODEapplies none of the user's CRUD or FLS limits. Sharing still follows the class declaration, so awith sharingclass stays record-filtered.
In static SOQL you write the mode in the query:
List<Account> rows = [SELECT Id, Name FROM Account WITH USER_MODE LIMIT 50];In dynamic SOQL you pass an access level to the Database method. Database.query has an overload that takes the query string and an AccessLevel. Database.queryWithBinds takes the query, the bind map and an AccessLevel. Database.countQueryWithBinds follows the same pattern for counts.
public with sharing class AccountSearch {
public static List<Account> searchByName(String input) {
String term = '%' + (input == null ? '' : input) + '%';
Map<String, Object> binds = new Map<String, Object>{ 'term' => term };
return Database.queryWithBinds(
'SELECT Id, Name, Industry FROM Account WHERE Name LIKE :term LIMIT 50',
binds,
AccessLevel.USER_MODE
);
}
}This one call gives you two protections. The bind map keeps the input as a value, and USER_MODE limits the result to what this user may see.
What happens when access is missing
User mode treats each missing permission differently:
- Record sharing: Records the user cannot see are left out of the result, as in any
with sharingquery. No error occurs. - Object CRUD: If the user cannot read the object, the query throws a
QueryException. - Field-level security: If the query references a field the user cannot read, the query throws a
QueryException. It does not return the row with that field blanked out. FLS applies to fields in theSELECTlist and also to fields used in filters and sorting.
This failure behavior is useful. A query that asks for a hidden field fails loudly, so you will not return partial data by accident. You still need to handle the exception.
public with sharing class AccountSearch {
public class SearchException extends Exception {}
public static List<Account> searchByName(String input) {
String term = '%' + (input == null ? '' : input) + '%';
Map<String, Object> binds = new Map<String, Object>{ 'term' => term };
try {
return Database.queryWithBinds(
'SELECT Id, Name, AnnualRevenue FROM Account WHERE Name LIKE :term LIMIT 50',
binds,
AccessLevel.USER_MODE
);
} catch (QueryException e) {
// Log the detail on the server, return a generic message to the caller.
System.debug(LoggingLevel.WARN, 'Search blocked: ' + e.getMessage());
throw new SearchException('You do not have access to run this search.');
}
}
}The exception message can name objects and fields. Do not send it straight to the client, since that tells the caller which fields exist.
Combining user mode with an allowlist
A common dynamic case is a list view where the caller picks the columns. Allowlisting and user mode answer different questions:
| Question | Defense |
|---|---|
| Is this a field name I meant to expose through this feature? | Allowlist |
| Is this a real field on this object? | Schema describe lookup |
| May this user read it? | User mode |
The describe check in an earlier chapter used isAccessible() to do the third job by hand. You can still use it to give a friendly message before the query runs. But user mode is the authoritative check, and it also covers sharing and fields you did not think to check.
public with sharing class AccountColumns {
private static final Set<String> ALLOWED = new Set<String>{ 'name', 'industry', 'annualrevenue', 'phone' };
public static List<Account> load(List<String> requested) {
List<String> columns = new List<String>{ 'Id' };
Map<String, Schema.SObjectField> fieldMap = Schema.SObjectType.Account.fields.getMap();
for (String raw : requested == null ? new List<String>() : requested) {
String key = raw == null ? '' : raw.toLowerCase();
if (ALLOWED.contains(key) && fieldMap.containsKey(key)) {
columns.add(fieldMap.get(key).getDescribe().getName());
}
}
String soql = 'SELECT ' + String.join(columns, ', ') + ' FROM Account LIMIT 50';
return Database.query(soql, AccessLevel.USER_MODE);
}
}The allowlist decides which fields this feature may ever expose. The describe lookup turns the input into the canonical API name. User mode then rejects the query if this particular user cannot read one of those fields.
User mode does not stop injection
User mode limits damage, and it does not fix injection. Consider the original vulnerable query with the attacker's ' OR Name != ' payload. In user mode, the attacker's rewritten query still returns every account this user can see. If the feature was meant to show one account, the user has still seen more than intended. An injection can also reach any field and any record the user can legitimately read, which may be far more than the feature meant to expose.
Treat the layers as independent:
- Bind values and allowlist identifiers so the query keeps its intended shape.
- Run it in user mode so a flaw in step 1 cannot exceed the user's own permissions.
- Test both.
When system mode is justified
Some features need data the running user cannot see. An example is a guest-facing form that checks whether a record exists, or a rollup across records owned by others. In those cases:
- Keep the system-mode query in a small, separate class with a clear name and a comment explaining why.
- Return only what the caller needs, such as a count or a Boolean, and not the raw sObjects.
- Do not pass any caller-controlled field or object names into it.
- Declare the class
with sharingunless you have a documented reason not to. Sharing and CRUD/FLS are separate settings.
public with sharing class DuplicateCheck {
// System mode on purpose: guests cannot read Account, but the form must
// tell them whether a name is already registered. Returns only a Boolean.
public static Boolean nameExists(String name) {
Map<String, Object> binds = new Map<String, Object>{ 'name' => name };
Integer count = Database.countQueryWithBinds(
'SELECT COUNT() FROM Account WHERE Name = :name',
binds,
AccessLevel.SYSTEM_MODE
);
return count > 0;
}
}Related options and how they compare
Older code may use other mechanisms:
| Mechanism | Notes |
|---|---|
| `WITH SECURITY_ENFORCED` | Checks FLS on fields in the `SELECT` clause and throws on failure. Does not cover filter and sort fields as user mode does. |
| `Security.stripInaccessible` | Removes inaccessible fields from results after the query instead of throwing. Useful when partial results are acceptable. |
| Manual `isAccessible()` checks | Accurate but easy to forget on one field or one code path. |
| `AccessLevel.USER_MODE` | One setting covering sharing, CRUD and FLS. Preferred for new code. |
Use stripInaccessible when a page should render with whatever the user can see. Use user mode when a missing permission should stop the operation.
User mode for DML
The same access levels apply when you write data. Database.insert(records, AccessLevel.USER_MODE) and the static forms insert as user records; and update as user records; check the user's create and edit permissions and FLS before saving. Dynamic queries often lead to a DML step, such as updating the rows you just fetched. Use user mode on both ends, or you can read as the user and then write as the system.
Testing permission enforcement
Test classes run in system mode by default, so a query in a test sees everything. To check enforcement you have to run as a user with limited access, using System.runAs.
@IsTest
private class AccountSearchPermissionTest {
@IsTest
static void userWithoutAccountAccessIsBlocked() {
Profile p = [SELECT Id FROM Profile WHERE Name = 'Minimum Access - Salesforce' LIMIT 1];
String uniq = String.valueOf(System.currentTimeMillis());
User u = new User(
Alias = 'lowpriv',
Email = 'lowpriv' + uniq + '@example.com',
Username = 'lowpriv' + uniq + '@example.com',
LastName = 'Limited',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
LocaleSidKey = 'en_US',
EmailEncodingKey = 'UTF-8',
LanguageLocaleKey = 'en_US'
);
insert u;
insert new Account(Name = 'Acme');
Boolean blocked = false;
System.runAs(u) {
try {
AccountSearch.searchByName('Acme');
} catch (AccountSearch.SearchException e) {
blocked = true;
}
}
Assert.isTrue(blocked, 'A user without Account access must not be able to search');
}
}The profile name is the standard one in current orgs. If your org lacks it, create a profile or use a permission-set-based setup that grants no access to Account. Pair this with the injection-payload test from the testing chapter, so both the query shape and the permissions have coverage.
Common mistakes
- Assuming
with sharingenforces CRUD and FLS. It enforces record sharing only. - Passing
AccessLevel.USER_MODEto some queries and forgetting it on theDatabase.countQueryor follow-up queries in the same method. - Catching
Exceptionbroadly and returning an empty list. The caller cannot tell "no matches" from "not allowed." - Returning
e.getMessage()to the client. - Writing tests only as the admin who runs deployments, so enforcement is never exercised.
- Using system mode "temporarily" in a shared helper that other classes then call with user-supplied names.
Exercise
A with sharing class runs Database.query('SELECT Id, Name, AnnualRevenue FROM Account') for a user whose profile has no read access to AnnualRevenue. What does the user get, and how do you change the call so that the missing permission is enforced?
Show answer
In system mode, which is the default, the query succeeds and returns AnnualRevenue, because with sharing only filters records by sharing and does not check FLS. Change the call to Database.query('SELECT Id, Name, AnnualRevenue FROM Account', AccessLevel.USER_MODE). The query then throws a QueryException because the user cannot read AnnualRevenue, and the caller should catch it and return a generic error.
Exercise
Your code binds all values and allowlists the sort field, and runs in user mode. A colleague says user mode makes the allowlist unnecessary. Give one reason the allowlist is still needed.
Show answer
User mode only checks what this user is permitted to read. It does not decide what this feature should expose. Without an allowlist, a caller could sort by or select any field the user can read, including ones the feature was never meant to reveal, and could pass names that are not fields at all. The allowlist defines the feature's intended surface, and user mode is a second layer behind it.
Exercise
Why does a test that calls AccountSearch.searchByName directly, without System.runAs, fail to prove that user-mode enforcement works?
Show answer
Test methods run in system mode with the permissions of the running developer or admin context, so the query sees everything and never hits a permission failure. You must use System.runAs with a user who lacks the relevant object or field access, and then assert that the query is blocked.