Sub topic 6
Respecting Sharing and Field-Level Security
This chapter assumes you can write basic Apex, run SOQL, and know the Salesforce sharing model (org-wide defaults, roles, sharing rules) and field-level security (FLS). It also assumes you have built the invocable method from the earlier chapters.
Why security matters more for agent actions
An Agentforce agent acts for a user. If your action returns data that user cannot see, the agent will repeat it in plain language. Apex does not enforce record sharing, object permissions, or FLS by default, so you must opt in. Three separate controls apply:
| Control | What it decides | How Apex enforces it |
|---|---|---|
| Sharing | Which records the user can see | `with sharing` on the class |
| CRUD | Whether the user can read, create, edit, or delete the object | User mode on queries and DML |
| FLS | Which fields the user can read or edit | User mode on queries and DML |
The with sharing keyword covers only record visibility. A class that is with sharing but queries in system mode can still return fields the user has no permission to read.
Sharing: declare it on the class
The action from earlier chapters starts with this line:
public with sharing class GetOpenCasesAction {with sharing makes the class respect the running user's record access. If you omit the keyword, the class inherits the sharing mode of whatever called it. For an agent action, the caller is the platform, so do not rely on inheritance. State the mode explicitly.
CRUD and FLS: use user mode
The query in the action ends with WITH USER_MODE:
for (Case c : [
SELECT Id, CaseNumber, Subject, AccountId
FROM Case
WHERE AccountId IN :accountIds AND IsClosed = false
WITH USER_MODE
ORDER BY CreatedDate DESC
LIMIT 200
]) {
// build the map
}WITH USER_MODE applies the running user's object permissions, FLS, and sharing rules to the query. If the user cannot read a field in the SELECT or WHERE clause, the query throws a QueryException. It does not silently drop the field.
Use the same idea for DML. Add as user to a DML statement, or pass AccessLevel.USER_MODE to a Database method:
Case c = new Case(Subject = 'Follow-up call', Status = 'New');
insert as user c;
Database.SaveResult[] results = Database.update(casesToUpdate, AccessLevel.USER_MODE);Dynamic SOQL
Dynamic queries need the same protection. Pass the access level to Database.queryWithBinds:
Id acctId = '001000000000001AAA';
List<Case> cases = Database.queryWithBinds(
'SELECT Id, Subject FROM Case WHERE AccountId = :acctId',
new Map<String, Object>{ 'acctId' => acctId },
AccessLevel.USER_MODE
);Using bind variables here also avoids SOQL injection.
Which user is "the running user"?
The agent's running user depends on how the agent is deployed. An employee-facing agent usually runs as the employee who is chatting. A service agent may run as a specific user configured for the agent. User mode enforces the permissions of that user, so check which user your agent runs as and what that user's profile and permission sets allow. Test with that user, not only with an administrator.
Common mistakes
- Using
without sharingto "make the action work". This hides a permissions problem and exposes data to anyone who can talk to the agent. - Using
with sharingand assuming FLS is covered. It is not. - Catching the
QueryExceptionfrom user mode and returning an empty list. The agent then says "no cases found" when the real problem is missing access. Return a message that says access was denied, as the error-handling chapter describes. - Testing only as a System Administrator, where every check passes.
Flow of a secured request
Testing as a restricted user
Use System.runAs with a user who lacks access, then assert the behavior:
@IsTest
private class GetOpenCasesActionSecurityTest {
@IsTest
static void restrictedUserSeesNoCases() {
Profile p = [SELECT Id FROM Profile WHERE Name = 'Minimum Access - Salesforce' LIMIT 1];
User u = new User(
Alias = 'restr', Email = '[email protected]', EmailEncodingKey = 'UTF-8',
LastName = 'Restricted', LanguageLocaleKey = 'en_US', LocaleSidKey = 'en_US',
ProfileId = p.Id, TimeZoneSidKey = 'America/Los_Angeles',
UserName = 'restr' + System.currentTimeMillis() + '@example.com'
);
insert u;
Account acct = new Account(Name = 'Secured Account');
insert acct;
insert new Case(AccountId = acct.Id, Subject = 'Hidden', Status = 'New');
GetOpenCasesAction.Request req = new GetOpenCasesAction.Request();
req.accountId = acct.Id;
Boolean denied = false;
System.runAs(u) {
try {
GetOpenCasesAction.getOpenCases(new List<GetOpenCasesAction.Request>{ req });
} catch (QueryException e) {
denied = true;
}
}
Assert.isTrue(denied, 'User without Case access should be denied');
}
}The "Minimum Access - Salesforce" profile has no Case read access, so user mode throws.
Exercise
A class is declared with sharing, and its query selects Subject from Case without WITH USER_MODE. The running user cannot read the Subject field. What happens, and how do you fix it?
Show answer
The query succeeds and returns Subject, because with sharing only filters which records the user can see and does not enforce FLS. Add WITH USER_MODE to the query so a user without read access to Subject gets a QueryException. Then handle that exception and return a clear access message to the agent.