March 10, 2011

A Common Myth : Triggers “always” play in GOD Mode (System Context) !

I recently came across an interesting problem, reported by one of my peer colleague working on salesforce app. That salesforce app has a trigger that suddenly started failing for INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY error, more details below :

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, abhinav.TestSharingInTrigger: execution of AfterInsert caused by: System.DmlException: Update failed. First exception on row 1 with id a00900000018AKfAAM; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id

The question came out why this happened ? Triggers always play in God Mode i.e. SYSTEM CONTEXT, so how come a insufficient access rights problem come ?

Note: Similar to above error, one can also see INSUFFICIENT_ACCESS_OR_READONLY in trigger/apex code execution. This post reproduces both these errors and tell the resolution.

Why this problem occurred ?

This problem can very much happen, when

  • Sobject Sharing Rules in your org expose all records for PUBLIC READ and open limited set of records for WRITE. A good example of that is an Sobject with Sharing setting “Public Read Only”, this setting means any one can read all the records, but only owners can do the updates.
  • The user for which this code is executing is not having “Modify All” permissions on the Sobject. This is very powerful permission it by passes all sharing rules and opens all records of that Sobject for read/write access to that user.
  • A Apex Code/Trigger in Org calls a class demarcated as “WITH SHARING”, this class in turn queries the same “public read” Sobject and updates a record for whom current user is not owner.

Reproducing this issue

Now we will go thru some steps to reproduce this problem in minimal steps

Step 1 - Setting up fixture !

To discuss and reproduce this issue, following fixture was created

  • A custom sobject called “TestObj__c”, which has
    • single Date field named “A_Date_Field__c”
    • sharing settings of “Public read only”. (This is important)
    • a trigger that invokes a “with sharing” code that tries to update all TestObjs.A_Date_Field__c to something else, like 2 days from now.
  • Two users
    • One user with “System Admin” profile. This will give him all God Mode permissions, like “View/Modify” all data on sobject TestObj.
    • One user with custom “Standard Custom User” profile. This guy just has CRUD permissions on sobject TestObj.
TestSharing.trigger on TestObj__c

This trigger simply delegates the call to an apex class called “TestSharing.cls”

trigger TestSharing on TestObj__c (after insert) {
  TestSharing.handle(Trigger.new);
}
Apex Class TestSharing.cls

This class is called by the Trigger TestSharing on TestSobj and does all the arithmetic around sharing rules.

public class TestSharing {
  // Method called by Trigger 
  public static void handle(TestObj__c[] a)   {
  // try to change references in "with" sharing context 
   new WithSharingHandler().manipulateAll();
  }
  
  /*
    WITH SHARING wrapper for the above call
  */
  with sharing class WithSharingHandler {
    public void manipulateAll() {
    // query all TestObj records
    TestObj__c[] objs = [Select Id,A_Date_Field__c from TestObj__c];
    
  // iterate over each and change the date field to anything.
    for (TestObj__c ob : objs)      
      ob.A_Date_Field__c = System.today().addDays(2);         
    // Update the objs
    if (!objs.isEmpty()) 
       update objs;    
    }
  }
}

Step 2 – Reproducing issue using the fixture

One can reproduce this problem easily, via Salesforce interface or Apex Test class. We will see both. In both the cases we will follow these steps to stumble upon the problem

  • As system admin profile user, create a Testobj record.
  • After that as “Standard Custom User” profile user, try creating another TestObj record. This will flow fail.

You must be wondering why one can’t create records as “Standard Custom User” ??? because

  • We are querying all TestObj records in the Org, using “WITH SHARING” context. That is fine because TestObj’s sharing rules are “Public read only”. Note, here we can get handle to some of those records, which are not OWNED by current user. 

    TestObj__c[] objs = [Select Id,A_Date_Field__c from TestObj__c]; 
  • With in same WITH SHARING context. For all queried records, we are changing the date field and updating all TestObj records in org.

    // iterate over each and change the date field to anything.
        for (TestObj__c ob : objs)      
          ob.A_Date_Field__c = System.today().addDays(2);         
        // Update the objs
        if (!objs.isEmpty()) 
           update objs;    
        }
  • This operation failed because
    • We are in WITH SHARING Context
    • Sharing setting says the records are “Public Read Only”, that means one can query all, but can update only those he is owner or has permission to.
    • The “Standard Custom User” profile doesn’t have “Modify All” permission on TestObj, like “System Admins”. So any user belonging to that profile can only update his records, not all those are visible to him.
    • Based on above three points, in the above use case.
      • We first created a record using System Admin profile
      • when “Standard Custom User” profile user attempted the same, it got the record created by System admin in this SOQL result : [Select Id,A_Date_Field__c from TestObj__c]
      • So, when “Standard Custom User” profile user tried to update that Admin owned record in WITH SHARING context the stuff failed.
Step 2.1 Reproducing issue via Salesforce UI

Here are the steps

  1. Login as “System Admin” profile user and create one TestObj record. Enter any date value you want.
  2. Login as “Standard Custom User” profile and try creating the record now. You will get an error (INSUFFICIENT_ACCESS_OR_READONLY)

Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger abhinav.TestSharingInTrigger caused an unexpected exception, contact your administrator: abhinav.TestSharing: execution of AfterInsert caused by: System.DmlException: Update failed. First exception on row 1 with id a00900000018ANNAA2; first error: INSUFFICIENT_ACCESS_OR_READONLY, insufficient access rights on object id: []:

Step 2.2 Reproducing issue via Apex Test Class

We will do the same steps as above to reproduce the problem

public static testMethod void testSharings() {
  // Query Standard User 
  Profile p = [SELECT Id FROM profile WHERE name='Standard Custom User'];
  // Create a in-memory mock user for 
  // running tests in limited data access context
  User mockUser = new User(alias = 'newUser1', email='newuser@testorg.com',
  emailencodingkey='UTF-8', lastname='Testing', 
  languagelocalekey='en_US', localesidkey='en_US', profileid = p.Id,
  timezonesidkey='America/Los_Angeles', username='newuser1234@testorg.com');

  // Create a record as Admin User
  insert new TestObj__c(A_Date_Field__c = System.today());
    
  System.runAs(mockUser) {    
    // Create a record as Standard Custom User Profile
  // It will fail at this point.
    insert new TestObj__c(A_Date_Field__c = System.today());
  }          
}

On executing above test case it fails for this error

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, abhinav.TestSharing: execution of AfterInsert caused by: System.DmlException: Update failed. First exception on row 0 with id a00900000018ALhAAM; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: []

 

Open Question ?

Why I’m getting different error codes in Salesforce UI(INSUFFICIENT_ACCESS_OR_READONLY) vs Apex Test case(CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY). I am doing exactly the same in both Apex Test and UI. If you have idea about what’s causing this difference, please share !

Conclusion – Take “Sharing Settings” seriously !

  • When creating new Sobjects, take sharing settings into consideration. Specially when you not using “Private” sharing. Similar to “Public read only”, other sharing settings like “Controlled by Parent” can lead to similar crash on different user profiles.
  • Developers use System Admin profile for creating and testing Apex/Trigger code. This is fine, but apex test cases should be crafted in way to simulate as all possible user profiles in the system. This will save you for sure from nightmares coming from production orgs.
    • Query and create mock users for each Custom Profile you app is going to support.
    • For simulating as mock users try using System.runAs(), note  you don’t need to insert user record. For more details on this, please check cookbook, this post.
  • Apex Triggers always run in GOD Mode (System Context) irrespective of sharing settings, is a myth !
    • If your apex trigger is calling a class declared using “WITH SHARING”, then all sharing rules for the context user will apply during trigger execution.
    • If you apex triggers is expecting to query all records and that code is running under WITH SHARING context, then user’s profile will come into play. For ex. With sharing setting of “Private”, a trigger querying records in WITH SHARING context might see lesser number of records, if the user profile is not having “View All” permission. This applied to both SOQL and SOSL queries
  • Their are exceptions to WITH SHARING context also, i.e. : all SOQL or SOSL queries that use PriceBook2 ignore the with sharing keyword. All PriceBook records are returned, regardless of the applied sharing rules. More details here
  • Current sharing rules can make DML operations fail, because the current user does not have the correct permissions. For example, if the user specifies a foreign key value that exists in the organization, but which the current user does not have access to.