By default Apex code executes without checking permissions. Hence the code will not enforce field level security, sharing rules and user permissions during execution of Apex code in Triggers, Classes and Controllers. This creates the risk that unauthorized users may get access to sensitive data records or fields.


It is possible to specify different level of sharing via the keywords "with sharing", "without sharing" or "inherited sharing". The last two should be used very carefully as they can create security risks.


This rule raises an issue whenever a DML, SOSL or SOQL query is executed in a class marked as ``++without sharing++`` or ``++inherited sharing++``.


== Ask Yourself Whether

* this code gives access to or modifies restricted records.
* this code may be executed by users who shouldn't have access to those records.
* if the class is marked as ``++inherited sharing++``, it may be called by a class marked as ``++without sharing++``.

There is a risk if you answered yes to any of those questions.


== Recommended Secure Coding Practices

* Use ``++with sharing++`` whenever possible.
* Use ``++without sharing++`` only after checking that the code is not accessible to unauthorized users.
* Use ``++inherited sharing++`` only when all calling ``++without sharing++`` classes are safe.


== Sensitive Code Example

----
public without sharing class MyClass {
  List<List<SObject>> sList = [FIND 'TEST' IN ALL FIELDS 
                                      RETURNING Case(Name), Contact(FirstName,LastName)]; // Sensitive 
}

public inherited sharing class MyClass {
  List<Case> lstCases = new List<Case>();
  for(Case c:[SELECT Id, Status FROM Case WHERE Status = 'In Progress']){ // Sensitive
      c.Status = 'Closed';
      lstCasesToBeUpdated.add(c);
  }
  Update lstCasesToBeUpdated; // Sensitive
}
----


== Compliant Solution

[source,apex]
----
public with sharing class MyClass { // Compliant
  List<Case> lstCases = new List<Case>();
  for(Case c:[SELECT Id FROM Case WHERE Status = 'In Progress']){
      // ...
  }
}
----


== See

* https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_keywords_sharing.htm[Using the with sharing, without sharing, and inherited sharing Keywords]

ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

=== Message

Make sure that executing SOQL, SOSL or DML queries without sharing or with inherited sharing is safe here


endif::env-github,rspecator-view[]
