Sub topic 14
Pitfalls and review checklist
This chapter collects the mistakes that most often appear in Apex sharing code and turns them into a checklist for code review. It assumes you know the three keywords (with sharing, without sharing, inherited sharing), how a sharing mode follows a call chain, and the difference between record-level sharing and object or field permissions.
Pitfall 1: Declaring no keyword
A class with no sharing keyword has no fixed sharing mode of its own. When another class calls it, it uses the mode already in effect, so it behaves like inherited sharing. When it is the entry point of a transaction, it runs without sharing. Entry points include an Apex trigger calling it, anonymous Apex, and an @AuraEnabled method called from a component.
An unmarked controller therefore reads every record, whatever the user can see.
// Pitfall: no keyword. As an @AuraEnabled entry point, this ignores record-level sharing.
public class OpportunityController {
@AuraEnabled(cacheable=true)
public static List<Opportunity> getOpportunities() {
return [SELECT Id, Name, Amount FROM Opportunity];
}
}The fix is to choose a keyword on purpose:
public with sharing class OpportunityController {
@AuraEnabled(cacheable=true)
public static List<Opportunity> getOpportunities() {
return [SELECT Id, Name, Amount FROM Opportunity WITH USER_MODE];
}
}Two points make this pitfall hard to see. The code works in testing, because the developer usually sees every record. A missing keyword also produces no warning, so only a review catches it.
A related trap is inherited sharing, which is not the same as an omitted keyword. With inherited sharing, an entry point runs with sharing. With no keyword, an entry point runs without sharing. Use inherited sharing when you want a safe default for a reusable class.
Pitfall 2: Assuming the caller's keyword protects the callee
Each method runs under the sharing mode of the class that defines it. If a with sharing controller calls a without sharing helper, the helper's queries still ignore record-level sharing.
public with sharing class CaseController {
public static Integer countAllCases() {
// Looks safe, but CaseCounter decides the mode for its own code.
return CaseCounter.countAll();
}
}
public without sharing class CaseCounter {
public static Integer countAll() {
return [SELECT COUNT() FROM Case];
}
}The opposite also holds. A with sharing helper called from a without sharing class enforces sharing inside the helper's methods.
During review, trace each query to the class where it is written. Do not stop at the keyword on the entry class.
Pitfall 3: Reaching for `without sharing` to fix a missing-data bug
A common bug report says, "The user sees no records in the component." The quick fix is to change the class to without sharing. That fix removes the symptom by removing the protection. The user can now see records that the organization-wide defaults, roles, and sharing rules were set up to hide.
Before you use without sharing, find out why the records are missing. The usual causes are:
- The sharing model really does hide those records, and the business rule should change (a sharing rule, a role change, or a permission set).
- The code needs one narrow cross-user operation, such as checking for duplicates across all accounts.
For the second cause, confine the exception to a small class that does only that operation:
public with sharing class AccountService {
public static Boolean isDuplicateName(String name) {
// Only a boolean leaves the privileged class, not the records.
return DuplicateChecker.exists(name);
}
}
public without sharing class DuplicateChecker {
public static Boolean exists(String name) {
return ![SELECT Id FROM Account WHERE Name = :name LIMIT 1].isEmpty();
}
}Return the smallest result that answers the question. A without sharing method that returns a List<Account> to a UI class leaks record data. One that returns a Boolean or a count leaks far less. Add a comment that states why the class bypasses sharing, so a reviewer can judge the reason.
Pitfall 4: Treating sharing as the whole security model
The sharing keywords control which records a user can see. They do not check object permissions (create, read, update, delete) or field-level security. A with sharing class can still return a field the user has no permission to read.
This is wrong, despite the keyword:
public with sharing class ContactReader {
public static List<Contact> getContacts() {
// Record-level sharing applies, but field-level security does not.
return [SELECT Id, LastName, Email, Birthdate FROM Contact];
}
}Add user-mode operations to cover the other layers:
public with sharing class ContactService {
public static List<Contact> getContacts() {
return [SELECT Id, LastName, Email FROM Contact WITH USER_MODE];
}
public static void saveContacts(List<Contact> contacts) {
Database.update(contacts, AccessLevel.USER_MODE);
}
}User mode enforces object permissions and field-level security. It also applies the user's sharing rules to that operation, whatever keyword the class declares. If a user lacks access, the operation throws an exception. Catch it and return a clear message.
User mode is not a replacement for the keyword. Keep with sharing on the class as well, so any query that does not use user mode is still record-restricted.
Pitfall 5: Forgetting inner classes and other entry points
Inner classes do not take the sharing setting of the class that contains them. A with sharing outer class with an unmarked inner class can run the inner class's queries under a different mode. Declare the keyword on every inner class that runs queries or DML. Wrapper classes that hold only data do not need one.
Also watch the other entry points that skip your class-level choice:
- Triggers run in system mode. A trigger has no sharing keyword. The classes it calls apply their own keywords, so a trigger handler should declare one.
- Anonymous Apex and batch or queueable jobs start in a new entry point. Declare
with sharingorinherited sharingon those classes. A batch class with no keyword runs without sharing. - Visualforce and Lightning controllers are entry points. Their keywords matter most, because user input reaches them directly.
Pitfall 6: Tests that hide sharing bugs
A test runs as the user who started the test run, who often has broad access. A test like this passes even when the class ignores sharing:
@IsTest
private class AccountReaderTest {
@IsTest
static void returnsOnlyVisibleAccounts() {
Profile p = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];
User u = new User(
Alias = 'tstusr',
Email = '[email protected]',
EmailEncodingKey = 'UTF-8',
LastName = 'Tester',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = 'tstusr' + System.currentTimeMillis() + '@example.com'
);
insert u;
insert new Account(Name = 'Created by admin');
System.runAs(u) {
// Assumes the org-wide default for Account is Private for this profile.
List<Account> visible = AccountReader.getAccounts();
System.assertEquals(0, visible.size(), 'User should not see the admin-owned account');
}
}
}Use System.runAs with a user whose access is limited, and assert both what the user can see and what the user cannot see. If your org's default access lets the user see the record anyway, the test proves nothing, so confirm the sharing setup that the test relies on.
Review checklist
Use this table when you review a pull request that adds or changes an Apex class.
| Check | What to look for | Fix |
|---|---|---|
| Keyword declared | Every outer class has `with sharing`, `without sharing`, or `inherited sharing` | Add the keyword on purpose |
| Entry points | Controllers, `@AuraEnabled` classes, and batch or queueable classes do not use the omitted keyword | Use `with sharing` for user-facing code |
| `without sharing` justified | A comment names the reason, and the class is small | Move the privileged query into a narrow class |
| Output of privileged code | Returns a flag or count, not full records | Reduce what leaves the class |
| Call chain traced | Each query is checked in the class where it is defined | Review helpers, not just the entry class |
| Inner classes | Inner classes with queries or DML declare a keyword | Add the keyword |
| Object and field access | User-facing queries and DML use user mode | Add `WITH USER_MODE` or `AccessLevel.USER_MODE` |
| Tests | A `System.runAs` test covers a restricted user | Add a positive and a negative assertion |
Exercise
A with sharing class named ReportController calls ReportData.load(). ReportData has no sharing keyword. ReportController.run() is an @AuraEnabled method. Which sharing mode applies to the query inside ReportData.load(), and what changes if ReportData is called directly from an anonymous Apex block?
Show answer
When ReportController.run() is the entry point, the transaction runs with sharing. ReportData has no keyword, so it uses the mode already in effect, and its query enforces record-level sharing. If an anonymous Apex block calls ReportData.load() directly, ReportData is the entry point with no keyword, so it runs without sharing. Declaring inherited sharing on ReportData would make the direct call run with sharing.
Exercise
A reviewer finds a with sharing service that returns [SELECT Id, Name, Salary__c FROM Employee__c] to a Lightning component. A user without read access to Salary__c can still see the value. Why, and what is the fix?
Show answer
with sharing limits which records are returned, but it does not check field-level security. Add WITH USER_MODE to the query, so the user's field permissions apply. The query then throws an exception for a user who cannot read Salary__c, and the service should handle that case.