Sub topic 8
inherited sharing: letting the caller decide
This chapter assumes you know basic Apex syntax and SOQL, and that you understand organization-wide defaults, roles, and sharing rules. It also assumes you have read the chapters on with sharing and without sharing, and the one on what happens when you declare no keyword. Here you will learn what inherited sharing does, when it applies, and why it is the usual choice for reusable data-access code.
The problem it solves
Some classes have no good fixed answer to the question "should this respect record sharing?" A query helper is a typical example. Called from a Lightning component controller, it should show only the records the user can see. Called from a system maintenance job that has to touch every record, it should see all of them.
You have three options without inherited sharing:
- Mark the helper
with sharing. The maintenance job can then never see all records through it. - Mark the helper
without sharing. User-facing code can then leak records. - Write two copies of the helper, which is a maintenance burden.
inherited sharing removes this choice. The class takes on the sharing mode of whatever code called it.
The rule
A class declared inherited sharing runs under the sharing mode of the class that calls it.
- If the caller runs
with sharing, the inherited class runswith sharing. - If the caller runs
without sharing, the inherited class runswithout sharing. - If the inherited class is the entry point of the transaction, it runs
with sharing.
An entry point is the first Apex code to run in a transaction. Examples are an @AuraEnabled method, a Visualforce controller action, an Apex REST method, or the execute method of a batch or queueable job.
public inherited sharing class AccountRepository {
public static List<Account> findByName(String name) {
return [SELECT Id, Name FROM Account WHERE Name = :name];
}
}The class contains no sharing logic of its own. Its behavior depends entirely on who calls it.
Two callers, two results
Here are two callers of the same repository.
public with sharing class AccountController {
@AuraEnabled
public static List<Account> search(String name) {
// AccountRepository runs with sharing here
return AccountRepository.findByName(name);
}
}public without sharing class AccountMaintenance {
public static List<Account> findForCleanup(String name) {
// AccountRepository runs without sharing here
return AccountRepository.findByName(name);
}
}Suppose a user cannot see an Account named Acme because the organization-wide default for Account is Private. A call to AccountController.search('Acme') returns an empty list. A call to AccountMaintenance.findForCleanup('Acme') returns the record. The query text is identical. Only the inherited sharing mode differs.
How the mode is decided
The mode is resolved at the moment each method is called, by looking at the calling class's mode. Here is the decision flow.
The decision is made again on every call. One inherited sharing class can run with sharing in one call and without sharing in the next, even within a single transaction.
Chains of calls
The mode passes down a chain, and each class that declares a fixed keyword resets it.
public with sharing class OrderController {
@AuraEnabled
public static Integer countOrders() {
return OrderService.countAll();
}
}
public inherited sharing class OrderService {
public static Integer countAll() {
return OrderRepository.countAll();
}
}
public inherited sharing class OrderRepository {
public static Integer countAll() {
return [SELECT COUNT() FROM Order];
}
}OrderController is with sharing, so OrderService runs with sharing. OrderService is now running with sharing, so OrderRepository does too. The query counts only the orders the user can see.
If a without sharing class sits in the middle, it changes the result:
public without sharing class OrderBypass {
public static Integer countEverything() {
return OrderRepository.countAll();
}
}If OrderController called OrderBypass.countEverything(), the repository would run without sharing. The caller of the repository is OrderBypass, and the repository inherits from its immediate caller, not from the original entry point.
inherited sharing versus an omitted keyword
A class with no keyword can look similar, because the current sharing rules often remain in effect when it is called from another class. The two differ in two ways.
| Situation | `inherited sharing` | No keyword |
|---|---|---|
| Called from a `with sharing` class | Runs with sharing | Runs with sharing |
| Called from a `without sharing` class | Runs without sharing | Runs without sharing |
| Entry point of the transaction | Runs with sharing | Runs without sharing |
| Intent visible in code | Yes, explicit | No, easy to miss |
The entry point row is the important one. A class with no keyword that is the first code to run in a transaction is not restricted by the user's record access. A class marked inherited sharing is restricted. Adding the keyword makes the safe behavior the default for the case where no caller exists.
The last row matters for reviews. Code reviewers and security scanners can tell that inherited sharing was a deliberate choice. A missing keyword could be a deliberate choice or an oversight.
When to use it
inherited sharing fits classes that hold logic reused from several places and do not decide for themselves how much data a user should see:
- Data-access or repository classes that wrap SOQL queries.
- Utility and service classes called from both controllers and background jobs.
- Selector classes in a layered architecture.
It does not fit a class whose job is to bypass sharing for a specific reason, such as a service that must read all records to compute a roll-up. Declare that class without sharing, keep it small, and document why.
Trade-offs and gotchas
- The class has no sharing identity of its own. Reading
AccountRepositoryalone does not tell you what it can see. You must look at its callers. This is the price of reuse. - A
without sharingcaller silently widens access. If someone later calls your repository from awithout sharingclass, the repository runs without sharing. That is by design, but the author of the repository may not know it happened. - It does not enforce object or field permissions. Like the other keywords, it covers record-level sharing only. A
with sharingresult can still include fields the user is not allowed to read. UseWITH USER_MODEandAccessLevel.USER_MODEfor that, as covered in the chapter on user-mode operations. - Entry points are not always obvious. A trigger, a batch job, or a Flow-invoked action can start the chain. Check how your code is actually reached before assuming the caller's mode.
Verifying the behavior
Test the same helper under both callers. Create a user with limited access, then run the code as that user with System.runAs. Assert that the with sharing caller returns fewer records than the without sharing caller. The chapter on testing sharing behavior covers this in full. A sketch of the idea:
@IsTest
private class AccountRepositoryTest {
@IsTest
static void respectsCallerSharingMode() {
Profile p = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];
User u = new User(
Alias = 'tuser',
Email = '[email protected]',
EmailEncodingKey = 'UTF-8',
LastName = 'Tester',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = 'tuser' + System.currentTimeMillis() + '@example.com'
);
insert u;
// The default owner is the test runner, so the new user cannot see this
// record when the Account organization-wide default is Private.
insert new Account(Name = 'Acme Hidden');
System.runAs(u) {
Integer withSharing = AccountController.search('Acme Hidden').size();
Integer withoutSharing = AccountMaintenance.findForCleanup('Acme Hidden').size();
System.assert(withoutSharing >= withSharing,
'The without sharing caller should see at least as many records');
}
}
}The assertion uses >= because the result depends on your org's sharing settings. Where Account is Private, the first count is 0 and the second is 1.
Summary of the rules
inherited sharingtakes the mode of the calling class.- As the entry point of a transaction, it runs
with sharing. - The mode is resolved per call, from the immediate caller.
- It is safer than an omitted keyword because its entry-point behavior is
with sharing. - It controls record-level sharing only. Use user-mode operations for object and field permissions.
Exercise
A class ReportHelper is declared inherited sharing. A without sharing class NightlyJob calls ReportHelper.build(). ReportHelper.build() then calls a method on a with sharing class named ReportFormatter. In which sharing mode does each of the three classes run its method?
Show answer
NightlyJob runs without sharing, because that is its declared mode. ReportHelper runs without sharing, because it inherits from its caller, NightlyJob. ReportFormatter runs with sharing, because a class with a fixed keyword uses its own mode no matter who calls it.
Exercise
A Lightning component calls an @AuraEnabled method directly on a class that has no sharing keyword. A second Lightning component calls an @AuraEnabled method directly on a class marked inherited sharing. Which class respects the user's record access, and why does the difference matter?
Show answer
The inherited sharing class respects it, because as the entry point of the transaction it runs with sharing. The class with no keyword is not restricted by the user's record access at the entry point, so it can return records the user cannot see. This is why inherited sharing is the safer way to say "use the caller's mode".