Newer Version Available

This content describes an older version of this product. View Latest

Enforce User Mode for Database Operations

You can run database operations in user mode rather than in the default system mode by using SOQL or SOSL queries with special keywords or by using DML method overloads.

Apex code runs in system mode by default, which means that it runs with substantially elevated permissions over the user running the code. To enhance the security context of Apex, you can specify user-mode access for database operations. Field-level security (FLS) and object permissions of the running user are respected in user mode, unlike in system mode. User mode always applies sharing rules, but in system mode they’re controlled by sharing keywords on the class. See Using the with sharing, without sharing, and inherited sharing Keywords.

You can indicate the mode of the operation by using WITH USER_MODE or WITH SYSTEM_MODE in your SOQL or SOSL query. This example specifies user mode in SOQL.
1List<Account> acc = [SELECT Id FROM Account WITH USER_MODE];
2

This feature is available in scratch orgs where the ApexUserModeWithPermset feature is enabled. If the feature isn’t enabled, Apex code with this feature can be compiled but not executed.

Note

Salesforce recommends that you enforce Field Level Security (FLS) by using WITH USER_MODE rather than WITH SECURITY-ENFORCED because of these additional advantages.

  • WITH USER_MODE accounts for polymorphic fields like Owner and Task.whatId.
  • WITH USER_MODE processes all clauses in the SOQL SELECT statement including the WHERE clause.
  • WITH USER_MODE finds all FLS errors in your SOQL query, while WITH SECURITY ENFORCED finds only the first error. Further, in user mode, you can use the getInaccessibleFields() method on QueryException to examine the full set of access errors.
Database operations can specify either user or system mode. This example inserts a new account in user mode.
1Account acc = new Account(Name='test');
2insert as user acc;

The AccessLevel class represents the two modes in which Apex runs database operations. Use this class to define the execution mode as user mode or system mode. An optional accessLevel parameter in Database and Search methods specifies whether the method runs in system mode (AccessLevel.SYSTEM_MODE) or user mode (AccessLevel.USER_MODE). Use these overloaded methods to perform DML and query operations.

When Database DML methods are run with AccessLevel.USER_MODE, you can access errors via SaveResult.getErrors().getFields(). With insert as user, you can use the DMLException method getFieldNames() to obtain the fields with FLS errors.

Note

These methods require the accessLevel parameter.

Using Permission Sets to Enforce Security in DML and Search Operations (Developer Preview)

In Developer Preview, you can specify a permission set that is used to augment the field-level and object-level security for database and search operations. Run the AccessLevel.withPermissionSetId() method with a specified permission set ID. Specific user mode DML operations that are performed with that AccessLevel, respect the permissions in the specified permission set, in addition to the running user’s permissions.

This example runs the AccessLevel.withPermissionSetId() method with the specified permission set and inserts a custom object.
1@isTest
2public with sharing class ElevateUserModeOperations_Test {
3    @isTest
4    static void objectCreatePermViaPermissionSet() {
5        Profile p = [SELECT Id FROM Profile WHERE Name='Minimum Access - Salesforce'];
6        User u = new User(Alias = 'standt', Email='standarduser@testorg.com',
7            EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
8            LocaleSidKey='en_US', ProfileId = p.Id,
9            TimeZoneSidKey='America/Los_Angeles',
10            UserName='standarduser' + DateTime.now().getTime() + '@testorg.com');
11
12        System.runAs(u) {
13            try { 
14                Database.insert(new Account(name='foo'), AccessLevel.User_mode); 
15                Assert.fail(); 
16            } catch (SecurityException ex) { 
17                Assert.isTrue(ex.getMessage().contains('Account'));
18            }
19            //Get ID of previously created permission set named 'AllowCreateToAccount'
20            Id permissionSetId = [Select Id from PermissionSet 
21                where Name = 'AllowCreateToAccount' limit 1].Id;
22
23            Database.insert(new Account(name='foo'), AccessLevel.User_mode.withPermissionSetId(permissionSetId)); 
24
25            // The elevated access level is not persisted to subsequent operations
26            try { 
27                Database.insert(new Account(name='foo2'), AccessLevel.User_mode); 
28                Assert.fail(); 
29            } catch (SecurityException ex) { 
30                Assert.isTrue(ex.getMessage().contains('Account')); 
31            } 
32            
33        } 
34    } 
35}
36

Checkmarx, the AppExchange Security Review source code scanner, hasn’t been updated with this new Apex feature. Until it’s updated, Checkmarx can generate false positives for field or object level security violations that require exception documentation.

Note