Sub topic 11
Sharing and Data Access
This chapter covers what data your invocable method can see and change when a flow calls it. It assumes you can write Apex classes and SOQL, and that you know what record-level sharing, object permissions (CRUD), and field-level security (FLS) are. It also assumes you have seen the request and result classes from earlier chapters.
Why this matters for invocable methods
Apex runs in system mode by default. System mode ignores the running user's object and field permissions. Sharing rules are a separate setting that you control with a keyword on the class.
A flow can run in several contexts. A record-triggered flow often runs in system context, and a screen flow often runs as the signed-in user. That is why the Apex author must decide what the method enforces. You cannot assume the flow's run mode protects the data.
The Apex class controls its own behavior. The flow's run mode decides how the flow's own elements behave, such as Get Records and Update Records. It does not turn on sharing in your Apex class. A class without the right declarations can read and write records the user could never see.
Three layers of access control
Salesforce checks three separate things. Each one needs its own handling in Apex.
| Layer | What it controls | How Apex enforces it |
|---|---|---|
| Record sharing | Which rows the user can see or edit | `with sharing` on the class, or `WITH USER_MODE` on a query |
| Object permissions (CRUD) | Whether the user can read, create, edit, or delete an object | `WITH USER_MODE`, `AccessLevel.USER_MODE`, or `Schema` describe checks |
| Field-level security (FLS) | Which fields the user can read or edit | `WITH USER_MODE`, `AccessLevel.USER_MODE`, or `Security.stripInaccessible` |
The sharing keyword enforces only the first layer. A class declared with sharing can still read a field the user has no permission to see. This is the most common misunderstanding about it.
Declaring the sharing mode
Always write a sharing keyword on the class that holds the @InvocableMethod. A class with no keyword depends on how it was reached, so its behavior is harder to predict. There are three options.
with sharingenforces the running user's sharing rules for queries and DML in the class. Use it as your default.without sharingignores sharing rules. Use it only when the method must see or change records that the user cannot, and document why.inherited sharingtakes the mode of whatever calls the class. When the class is the entry point, it runs aswith sharing. This suits utility classes that other Apex calls, but an invocable class is almost always an entry point, sowith sharingstates the intent more directly.
The wrapper classes (Request and Result) hold data and no logic. They do not query or update records, so their sharing mode has no effect.
A user-mode example
The class below looks up account names from a list of IDs. It uses with sharing and also runs the query WITH USER_MODE, so it enforces record sharing, object access, and field access together.
public with sharing class AccountNameLookup {
public class Request {
@InvocableVariable(label='Account Id' required=true)
public Id accountId;
}
public class Result {
@InvocableVariable(label='Account Name')
public String accountName;
@InvocableVariable(label='Is Found')
public Boolean isFound;
}
@InvocableMethod(
label='Get Account Names'
description='Returns the name of each account the running user can see.'
category='Account'
)
public static List<Result> getNames(List<Request> requests) {
Set<Id> accountIds = new Set<Id>();
for (Request req : requests) {
if (req.accountId != null) {
accountIds.add(req.accountId);
}
}
Map<Id, Account> accountsById = new Map<Id, Account>(
[SELECT Id, Name FROM Account WHERE Id IN :accountIds WITH USER_MODE]
);
List<Result> results = new List<Result>();
for (Request req : requests) {
Result res = new Result();
Account acc = accountsById.get(req.accountId);
res.isFound = acc != null;
res.accountName = acc?.Name;
results.add(res);
}
return results;
}
}The method returns one result per request, in the same order as the input. A record the user cannot see produces isFound = false. It does not throw an error, and the flow can branch on the value.
WITH USER_MODE can also throw. If the user lacks read access to the Account object or to the Name field, the query throws a QueryException. The flow then follows its fault path, as described in the error handling chapter. If you want a per-record message instead, catch the exception and return a failed result for each request.
Enforcing access on DML
WITH USER_MODE applies to queries. For inserts, updates, and deletes, pass an access level to the Database method.
public with sharing class SecureTaskCreator {
@InvocableMethod(label='Create Tasks As User')
public static List<Boolean> createTasks(List<Id> accountIds) {
List<Task> tasks = new List<Task>();
for (Id accountId : accountIds) {
tasks.add(new Task(WhatId = accountId, Subject = 'Follow up'));
}
List<Database.SaveResult> saveResults =
Database.insert(tasks, false, AccessLevel.USER_MODE);
List<Boolean> outcomes = new List<Boolean>();
for (Database.SaveResult sr : saveResults) {
outcomes.add(sr.isSuccess());
}
return outcomes;
}
}With partial success enabled (false for the all-or-none argument), a record that fails a permission check comes back as a failed SaveResult. The other records still save. With all-or-none left on, a permission failure throws an exception for the whole call.
Other tools exist for specific cases:
Security.stripInaccessibleremoves fields the user cannot access from a record list before you use or return it. It suits cases where you build records in code and want to drop forbidden fields silently.WITH SECURITY_ENFORCEDis an older query clause. It throws if any selected field is inaccessible. PreferWITH USER_MODEin new code, because it also applies sharing rules and covers filter fields.
When system mode is the right choice
Some automation must act beyond the user's own permissions. An example is a flow that writes a case-routing record the user never sees. Plan for these cases deliberately.
- Keep the elevated code in the smallest possible method or class.
- Declare the class
without sharingonly if you need to bypass record sharing. If you only need to bypass object or field permissions, leave the classwith sharingand run that query or DML in system mode. - Validate the input before acting. A flow passes IDs in, and the method should not assume the user is allowed to act on them.
- Return only what the flow needs. Do not return fields the user could not otherwise read.
public without sharing class CaseRoutingWriter {
@InvocableMethod(label='Record Routing Decision')
public static void record(List<Id> caseIds) {
List<Routing_Log__c> logs = new List<Routing_Log__c>();
for (Id caseId : caseIds) {
logs.add(new Routing_Log__c(Case__c = caseId));
}
insert logs;
}
}Routing_Log__c is a custom object used here as an example. Replace it with your own object. The class does one narrow job and returns nothing sensitive, which is the pattern to follow when you use without sharing.
Input values are not trusted
The flow supplies IDs and field values, and a user can influence them. An ID in a request does not prove the user may act on that record. If the method runs in system mode, it will act on any ID it receives. Query the records in user mode first, or compare against a query that applies sharing, before changing them.
Also check who can run the flow. For a flow run in user context, the user needs access to the Apex class through a profile or permission set. Grant that access to the people who should run the flow, and not to everyone.
Testing sharing behavior
Apex tests run in system mode by default, so a plain test never shows a sharing problem. Use System.runAs to run the call as a specific user.
The test below assumes the Account organization-wide default is Private. Under that setting, a Standard User cannot see an account owned by someone else.
@IsTest
private class AccountNameLookupTest {
@IsTest
static void hidesAccountsTheUserCannotSee() {
Profile standardProfile = [
SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1
];
String uniqueName = 'sharing' + String.valueOf(Crypto.getRandomInteger()).replace('-', 'n');
User standardUser = new User(
Alias = 'shrtst',
Email = uniqueName + '@example.com',
EmailEncodingKey = 'UTF-8',
LastName = 'SharingTest',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = standardProfile.Id,
TimeZoneSidKey = 'America/Los_Angeles',
Username = uniqueName + '@example.com'
);
insert standardUser;
Account hidden = new Account(Name = 'Owned By Admin');
insert hidden;
AccountNameLookup.Request req = new AccountNameLookup.Request();
req.accountId = hidden.Id;
List<AccountNameLookup.Result> results;
System.runAs(standardUser) {
results = AccountNameLookup.getNames(
new List<AccountNameLookup.Request>{ req }
);
}
Assert.areEqual(1, results.size(), 'One result per request');
Assert.isFalse(results[0].isFound, 'The user should not see this account');
}
}The test inserts the account as the test-running user, so the standard user does not own it. If your org uses a different default sharing model, adjust the setup so the record is truly hidden from the test user.
Add a second test that runs as a user who does see the record and asserts isFound is true. Two tests together show that the method both blocks and allows access correctly.
Common mistakes
- Leaving the sharing keyword off an invocable class, then relying on how it happens to be called.
- Assuming
with sharingalso enforces field-level security. It does not. - Using
without sharingon a large class when only one query needs it. - Trusting IDs from the flow in system mode without checking the user's access.
- Writing only system-mode tests, which pass even when the method would fail for a real user.
Exercise
A record-triggered flow calls your invocable method, which is declared public with sharing and queries Contact records with a plain SOQL query, with no WITH USER_MODE. A user without read access to the Contact Salary__c field triggers the flow, and the query selects that field. Does the method return the salary value? What two changes would make the method enforce both sharing and field access, and how would you test it?
Show answer
Yes, it returns the value. with sharing enforces only record sharing, and a plain query does not check field-level security, so the field is readable. To enforce everything, keep with sharing and add WITH USER_MODE to the query, or use Security.stripInaccessible on the results. User mode then throws a QueryException for the inaccessible field, which the flow can handle on its fault path. To test it, create a user whose profile lacks read access to Salary__c, call the method inside System.runAs for that user, and assert that the exception is thrown or that the field is absent. Add a second test with a permitted user to confirm the normal path still works.