Sub topic 10
Enforcing permissions inside Apex and Flow actions
This chapter assumes you can read basic Apex and Flow, and that you know what a permission set, object permission, and field-level security (FLS) are. It builds on the earlier chapters about the agent user, permission sets, and sharing. Here the focus is on the layer that most often breaks the least-privilege model: the code and flows an agent calls.
Why actions are the weak point
An agent does not query data directly. It calls actions, and an action is often an invocable Apex method, a Flow, or a prompt template. The action's code decides what data is read or changed. If that code ignores the agent user's permissions, then the permission set you wrote in the previous chapters has no effect.
Apex does not enforce permissions by default. By default, Apex runs in system mode. That means it ignores object permissions and field-level security. Sharing is a separate setting that depends on the class declaration. A class that runs in system mode can read an Order the agent user cannot see.
The result is a quiet failure. The agent works in testing, because the test user usually has broad access. In production the action returns data the agent user should never see.
| Concern | What controls it | Default in Apex |
|---|---|---|
| Object permissions (CRUD) | Permission sets and profile | Not enforced |
| Field-level security | Permission sets and profile | Not enforced |
| Record sharing | Sharing rules, org-wide defaults, role hierarchy | Depends on the class keyword |
Sharing keywords versus user mode
Two separate Apex features are often confused. They answer different questions.
- The sharing keyword (
with sharing,without sharing,inherited sharing) controls record-level access. It decides which records the code can see. - The database operation mode (
WITH USER_MODEorWITH SYSTEM_MODE) controls object permissions, field-level security, and sharing together for a single query or DML statement.
with sharing alone does not enforce CRUD or FLS. A with sharing class can still read a field the user has no access to. For this reason, use both: declare the class with sharing as the safe default, and add WITH USER_MODE to every query and DML operation that handles agent-requested data.
A complete example
The following invocable action returns the status of an order. It uses with sharing and WITH USER_MODE, so the query respects the running user's object permissions, field-level security, and sharing. If the user cannot see the order, the status stays empty.
public with sharing class OrderStatusAction {
public class Request {
@InvocableVariable(required=true label='Order Number')
public String orderNumber;
}
public class Result {
@InvocableVariable(label='Order Status')
public String status;
}
@InvocableMethod(label='Get Order Status' description='Returns the status of an order the running user can access')
public static List<Result> getStatus(List<Request> requests) {
Set<String> numbers = new Set<String>();
for (Request r : requests) {
numbers.add(r.orderNumber);
}
Map<String, String> statusByNumber = new Map<String, String>();
for (Order o : [
SELECT OrderNumber, Status
FROM Order
WHERE OrderNumber IN :numbers
WITH USER_MODE
]) {
statusByNumber.put(o.OrderNumber, o.Status);
}
List<Result> results = new List<Result>();
for (Request r : requests) {
Result res = new Result();
res.status = statusByNumber.get(r.orderNumber);
results.add(res);
}
return results;
}
}Several design choices in this code matter for agents.
- Bulk-safe input. An invocable method receives a list of requests. The code gathers all order numbers first and runs one query, so it stays inside governor limits.
- Narrow output. The result exposes only a status. It does not return the whole Order record. The agent cannot leak a field the action never returns.
- Silent absence. When the order is missing or hidden,
statusisnull. The agent then follows its instructions for "cannot find the order", which the topic instructions define. - Descriptive labels. The method description tells the reasoning engine what the action does and who it serves. A vague description leads to wrong action selection.
Pair the code with the permission set
The Apex above works only if the agent user holds the right access. This permission set grants read access to Order and the Status field, and nothing more.
<?xml version="1.0" encoding="UTF-8"?>
<PermissionSet xmlns="http://soap.sforce.com/2006/04/metadata">
<label>Agent Order Read</label>
<description>Read-only access to orders for the service agent user</description>
<hasActivationRequired>false</hasActivationRequired>
<objectPermissions>
<allowCreate>false</allowCreate>
<allowDelete>false</allowDelete>
<allowEdit>false</allowEdit>
<allowRead>true</allowRead>
<modifyAllRecords>false</modifyAllRecords>
<object>Order</object>
<viewAllRecords>false</viewAllRecords>
</objectPermissions>
<fieldPermissions>
<editable>false</editable>
<field>Order.Status</field>
<readable>true</readable>
</fieldPermissions>
</PermissionSet>This permission set does not grant read access to Order.OrderNumber. Look again at the query: it selects OrderNumber and filters on it. In user mode, a field the user cannot read causes the query to fail with an exception. OrderNumber is a standard name field and is generally readable when the object is readable, but you should never assume this. Verify the access of every field in the SELECT and WHERE clauses against the permission set, and add any custom field explicitly.
What happens when access is missing
User mode turns a silent leak into a visible failure. That is the intent, but your action must handle the failure well.
For queries, a missing object or field permission throws a System.QueryException. For DML in user mode, missing permissions throw a System.DmlException. If the action does not catch the exception, the agent gets a generic error and may retry or improvise.
A safer pattern is to catch the exception, and return a clear, non-sensitive message that the agent can act on.
public with sharing class SafeOrderLookup {
public class Result {
@InvocableVariable public String status;
@InvocableVariable public String message;
}
@InvocableMethod(label='Look Up Order Status Safely')
public static List<Result> lookup(List<String> orderNumbers) {
List<Result> results = new List<Result>();
Map<String, String> found = new Map<String, String>();
String problem;
try {
for (Order o : [
SELECT OrderNumber, Status
FROM Order
WHERE OrderNumber IN :orderNumbers
WITH USER_MODE
]) {
found.put(o.OrderNumber, o.Status);
}
} catch (QueryException e) {
problem = 'The order lookup is not available. Transfer to a human agent.';
}
for (String n : orderNumbers) {
Result r = new Result();
r.status = found.get(n);
if (r.status == null) {
r.message = problem != null ? problem : 'Order not found.';
}
results.add(r);
}
return results;
}
}Do not put the raw exception text in the message. It can reveal field and object names that the user was never meant to know about.
Other ways to enforce permissions in Apex
WITH USER_MODE is the current recommended approach. You will see older code that uses other patterns.
| Approach | What it does | Notes |
|---|---|---|
| `WITH USER_MODE` | Enforces CRUD, FLS, and sharing in one clause | Preferred. Works in SOQL and in DML. |
| `WITH SECURITY_ENFORCED` | Checks FLS and object access on SELECT fields | Older. It does not check the WHERE clause and does not apply to DML. |
| `Security.stripInaccessible()` | Removes fields the user cannot access from records | Useful when you want partial results instead of an exception. |
| `Schema` describe checks | Manual `isAccessible()` and `isUpdateable()` tests | Verbose and easy to forget. |
For DML, use the as user keyword form, for example insert as user records; or Database.insert(records, AccessLevel.USER_MODE);.
When system mode is justified
Some actions must read data the agent user cannot see. An example is a lookup in an internal configuration object. Running that code in system mode is allowed, but treat it as a deliberate exception.
- Isolate the privileged query in its own small class marked
without sharingor usingWITH SYSTEM_MODE. - Return only the minimum data the agent needs.
- Add a comment that states why the privilege is needed.
- Review the class in every security review.
Enforcing permissions in Flow
Flow has the same problem. A flow that an agent calls runs in a context that you choose, and the choice changes what the agent can reach.
A flow can run in one of three contexts:
- User context respects the running user's permissions. The agent user's object permissions, FLS, and sharing apply.
- System context with sharing ignores object permissions and FLS but still applies sharing.
- System context without sharing ignores all of them.
Record-triggered and autolaunched flows default to system context for record operations such as Get Records, Create Records, Update Records, and Delete Records. Automation that runs in system context behaves like Apex without user mode. Set the flow's run mode to user context unless you have a documented reason.
In the flow's settings, the field How to Run the Flow controls this. For flows used as agent actions, choose User or System Context only after checking what the flow does, and prefer the user-context option when it is available for the flow type. Retest after any change.
Flow gotchas
- A flow can call Apex. If the Apex action runs in system mode, the flow's own run mode does not protect you.
- A subflow has its own run mode. A user-context parent can call a system-context child.
- Get Records returns whole records by default. Select only the fields you need, and map only those fields to the flow's output variables.
- Fault paths matter. An unhandled flow error returns a message to the agent that may contain internal detail. Add a fault connector that sets a safe message.
How the layers combine
The agent user's permission set is the ceiling. Your action code can narrow that ceiling, but it must never raise it without a deliberate decision.
Testing that enforcement works
A test class that runs as an admin proves nothing about the agent user. Test the action while running as a user who has only the agent permission set.
@IsTest
private class OrderStatusActionTest {
@IsTest
static void returnsNullWhenUserHasNoAccess() {
Profile p = [SELECT Id FROM Profile WHERE Name = 'Minimum Access - Salesforce' LIMIT 1];
User noAccess = new User(
Alias = 'noacc',
Email = '[email protected]',
EmailEncodingKey = 'UTF-8',
LastName = 'NoAccess',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = 'noaccess' + System.currentTimeMillis() + '@example.com'
);
insert noAccess;
OrderStatusAction.Request req = new OrderStatusAction.Request();
req.orderNumber = '00000100';
Boolean denied = false;
System.runAs(noAccess) {
try {
List<OrderStatusAction.Result> out =
OrderStatusAction.getStatus(new List<OrderStatusAction.Request>{ req });
denied = out[0].status == null;
} catch (QueryException e) {
denied = true;
}
}
System.assert(denied, 'A user without access must not receive an order status');
}
}This test accepts either outcome: an empty result or a QueryException. Both show that the data stayed protected. To test the positive path, create a second user, assign the Agent Order Read permission set with PermissionSetAssignment, and assert that the status is returned.
For flows, use the Debug option in Flow Builder with Run flow as another user enabled, and select the agent user. A debug run as your own admin account does not show permission problems.
Common errors
- Assuming
with sharingis enough. It enforces record access only. AddWITH USER_MODE. - Testing as an admin. Admins bypass most checks, so failures appear only in production.
- Returning whole records. The action then exposes every field the user can read. Return a small result class.
- Granting broad rights to make a test pass. Fix the specific missing permission instead.
- Forgetting the WHERE clause. User mode checks filter fields too.
- Leaking exception text. Return a safe message and let the instructions handle escalation.
Exercise
An Apex action declared public with sharing class runs SELECT Id, Status, Notes__c FROM Order WHERE Id = :orderId with no WITH USER_MODE clause. The agent user can read Order and Order.Status, but has no access to Order.Notes__c. What does the action return, and how do you fix it?
Show answer
The query succeeds and returns Notes_c, because with sharing enforces only record sharing and not field-level security. The agent could then pass private notes to the customer. Fix it by adding `WITH USERMODE` so the query throws a QueryException for the inaccessible field, or by removing Notes__c from the query if the action does not need it. Also catch the exception and return a safe message so the agent can escalate.
Exercise
A flow used as an agent action has a Get Records element that reads Contact records. The flow runs in system context without sharing. Name two risks and two changes that reduce them.
Show answer
Risks: the flow can return contacts the agent user is not allowed to see because sharing and FLS are ignored, and it may return more fields than the agent needs. Changes: run the flow in user context so the agent user's permissions apply, and select only the required fields and map only those to output variables. Adding a fault path with a safe message also helps.