Sub topic 2
Why Apex ignores sharing unless told otherwise
This chapter assumes you can read basic Apex (classes, methods, SOQL) and know the record access model: organization-wide defaults, roles, and sharing rules. It also assumes you know that profiles and permission sets grant object and field permissions. If any of that is unfamiliar, review it first, because this chapter depends on keeping those layers apart.
The surprise
A user opens a Lightning page. The page calls an Apex method that runs SELECT Id, Name FROM Account. The user's organization-wide default for Account is Private, and the user owns three accounts. You might expect the method to return three records. If the class has no sharing keyword and the method is the entry point, the query can return every Account in the org.
The platform does not treat this as a bug. It is the default behavior of Apex, and the rest of this tutorial depends on it.
Apex runs in system mode
Most Salesforce features run in user mode. A list view, a report, or a record page shows only what the signed-in user is allowed to see. Apex works differently. By default, Apex code runs in system mode (also called system context). In system mode the code acts with broad access to the data, no matter who triggered it.
System mode ignores three things that a user's access normally includes:
- Record-level sharing. This covers organization-wide defaults, role hierarchy, sharing rules, manual shares, and teams.
- Object permissions (CRUD). These are the create, read, update, and delete permissions on an object.
- Field-level security (FLS). This controls whether a user can read or edit a given field.
System mode does not make everything permitted. Some rules still apply:
- The user must have access to the Apex class to start it from an entry point.
- Validation rules, required fields, triggers, and governor limits still run.
- Unique constraints and data type checks still apply.
The access that is ignored is the access the user's profile, permission sets, and sharing settings would otherwise grant or deny.
Why the platform works this way
Apex is often used for work the user is not directly allowed to do. A few examples:
- A trigger that rolls up values to a parent record the user cannot see.
- A scheduled job that has no interactive user.
- A service that assigns a case to a queue the user cannot read.
- An integration that must write to records owned by other people.
If every Apex class automatically obeyed the user's access, many of these tasks would fail. So Salesforce made system mode the default and left the decision about restricting access to the developer. This puts the burden of secure design on you. Code you write does not protect data unless you ask it to.
What the sharing keywords change
The keywords with sharing, without sharing, and inherited sharing control only one of the three ignored items: record-level sharing. They decide whether SOQL queries and DML statements in the class apply the running user's sharing access.
| Layer | Ignored by default in Apex? | Enforced by a sharing keyword? |
|---|---|---|
| Record-level sharing (OWD, roles, sharing rules) | Yes | Yes, with `with sharing` |
| Object permissions (CRUD) | Yes | No |
| Field-level security | Yes | No |
This table is the key to the chapter. A class declared with sharing still reads fields the user is forbidden to see, and it can still update objects the user has no edit permission on. Later chapters cover how to enforce those layers. For now, remember that the keyword narrows the rows returned, and it does not narrow the columns or the actions allowed.
Seeing system mode in action
The next class has no sharing keyword. It queries a sensitive field and counts the records returned.
public class DefaultModeDemo {
public static Integer countAccounts() {
return [SELECT COUNT() FROM Account];
}
public static List<Contact> readEmails() {
// Runs in system mode: succeeds even if the user has no FLS read access to Email
return [SELECT Id, LastName, Email FROM Contact LIMIT 10];
}
}Suppose a user whose profile has no read access to Contact.Email calls readEmails(). In system mode the query succeeds and the Email values come back. Compare that with the same query asked to run in user mode:
public with sharing class UserModeDemo {
public static List<Contact> readEmailsAsUser() {
// WITH USER_MODE applies object permissions and FLS.
// If the user cannot read Email, this throws a System.QueryException.
return [SELECT Id, LastName, Email FROM Contact WITH USER_MODE LIMIT 10];
}
}The two methods use almost the same query. The difference is the access mode. In the first, system mode applies, and the user's field permissions are ignored. In the second, WITH USER_MODE makes the platform check them, and the query fails for a user without access. User-mode operations get a full treatment later in this tutorial.
How a request flows
The diagram shows where system mode sits between a user's request and the data. The sharing keyword is one switch on one of the checks.
Entry points that run system mode code
System mode is not limited to one kind of Apex. These typical entry points all run in system mode unless you add controls:
- Lightning component controllers (methods marked
@AuraEnabled) - Visualforce page controllers and extensions
- Apex REST and SOAP web services
- Triggers
- Batch, queueable, and scheduled Apex
- Invocable methods called from flows
For several of these, there is no human user at the moment of execution, or the "user" is an automated process. The sharing keywords become meaningful when the code serves a person whose access should limit what the code shows.
A worked example
Consider a controller used by sales reps. Reps should see only their own opportunities, as set by sharing.
public class OpportunityController {
@AuraEnabled(cacheable=true)
public static List<Opportunity> getOpenOpportunities() {
return [
SELECT Id, Name, Amount, StageName
FROM Opportunity
WHERE IsClosed = false
];
}
}This class has no keyword. When a Lightning component calls it, the class is the entry point, and the query is not filtered by the rep's record access. A rep could see opportunities that belong to other teams. Nothing in the code looks wrong, and a quick test as an admin would pass. The leak appears only when a restricted user runs it.
The fix at the sharing level is one word:
public with sharing class OpportunityController {
@AuraEnabled(cacheable=true)
public static List<Opportunity> getOpenOpportunities() {
return [
SELECT Id, Name, Amount, StageName
FROM Opportunity
WHERE IsClosed = false
];
}
}Now the query returns only the opportunities the running user can access through sharing. The rest of this chapter's lesson still applies: if Amount is hidden from the rep by field-level security, this class still returns it. Combine the keyword with WITH USER_MODE when you need both.
Common misunderstandings
- "Apex respects the user's profile." Only partly. Profiles and permission sets decide who can run an entry point, such as a class or page, and they do not restrict the data operations inside it.
- "
with sharingmakes my class secure." It enforces record sharing and nothing else. CRUD and FLS stay unenforced. - "I tested as an administrator, so it works." Administrators with View All Data and Modify All Data see all records anyway, so a test as an admin cannot reveal a missing keyword. Test as a restricted user.
- "The default is safe." The default favors functionality over restriction. Treat a missing keyword as a decision you have not made yet.
Summary of the key idea
Apex starts from broad access and lets you narrow it. There are two separate controls for narrowing it:
- Sharing keywords, which limit rows through record-level sharing.
- User-mode operations, which add object permissions and field-level security.
Understanding that these are separate controls makes the next chapters easier. Each keyword is a specific answer to the question "Whose record access should this class respect?"
Exercise
A class has no sharing keyword. A user with a Private Account sharing setting and no read access to the field Account.AnnualRevenue calls a method that runs SELECT Id, AnnualRevenue FROM Account as the entry point. Name the two kinds of access the query ignores, and say which of the two the keyword with sharing would restore.
Show answer
The query ignores record-level sharing (the user can see only some Account rows) and field-level security (the user cannot read AnnualRevenue). Adding with sharing restores only record-level sharing, so the query returns just the accounts the user can access, but it still returns AnnualRevenue. Enforcing FLS needs WITH USER_MODE or AccessLevel.USER_MODE.
Exercise
Why can a developer who tests an Apex controller only as a System Administrator miss a missing with sharing keyword?
Show answer
A System Administrator with View All Data or Modify All Data can see all records regardless of sharing, so the output looks the same with or without the keyword. The difference appears only when a restricted user runs the code, so you must test as a user with limited access.