Back to insights

Apex Security, Sharing & Authorization

‘with sharing’ does not make Apex secure

JSBC Labs8 min read

The keyword passed review; the service still leaked authority

A team adds `with sharing` to an Apex controller and closes the security-review finding. A sales user can no longer query another region's Opportunities, yet the same method still returns a margin field the user cannot see in Salesforce and accepts an update to a restricted approval field. Record visibility improved. The service is still over-authorised.

The JSBC Labs position is that `with sharing` does not make Apex secure. Salesforce defines sharing declarations as controls for record-level access. They do not, by themselves, prove that a user may access the object, read or change each field, invoke the business capability or supply the requested values. Secure Apex is an authorization design in which every boundary states which identity may perform which operation on which data—and why any exception is necessary.

Treat access as four separate gates

Design the service around four questions. May the caller enter this Apex capability? May the caller act on this record? May the caller read or change these objects and fields? Is the requested business transition valid for this actor and record state? Apex class access, sharing, CRUD and field-level security, and domain authorization answer different questions. Passing one gate must never be treated as evidence that the others passed.

Write the authorization contract beside the use case. A user might be allowed to invoke `submitDiscount`, see the Opportunity and update a Comments field while still being forbidden to change Discount Percent or submit after approval. Conversely, a scheduled reconciliation may legitimately need records outside one user's sharing scope but still require a tightly bounded field set and an auditable service identity. The requirement determines the context; convenience must not.

Make sharing intent explicit

Salesforce's current Apex guide recommends an explicit sharing declaration on classes that query or change data. Use `with sharing` as the normal service boundary. Use `inherited sharing` only when the class is designed and tested to adopt the caller's context. Reserve `without sharing` for a documented system-level requirement. The sharing mode is generally determined by the class where the method is defined, not the class that called it, so moving a query into a helper can change the effective security contract.

API version matters. Salesforce documents that in API version 67.0 and later, classes without an explicit declaration default to `with sharing`; older versions have different, more complex rules. Inherited sharing also behaves deliberately at transaction entry points, while triggers cannot declare a sharing mode. Do not rely on an omitted keyword or tribal knowledge about a caller chain. Explicit declarations make intent reviewable across version upgrades, asynchronous boundaries and refactoring.

Declare query and DML mode at the operation boundary

Sharing answers which records are visible. Object permissions and field-level security answer what data can be used. Salesforce's versioned guidance says that API 67.0 and later run database operations in user mode by default, whereas API 66.0 and earlier defaulted to system mode. It also removes `WITH SECURITY_ENFORCED` for Apex SOQL in API 67.0 and directs developers to `WITH USER_MODE`. That is a material platform change, not permission to stop thinking about access.

Specify `WITH USER_MODE` or `WITH SYSTEM_MODE` on queries and use explicit user or system mode for DML and Database methods. This makes the operation's privilege visible in code review and stable across mixed-version classes. User mode applies sharing, object permissions and field-level security. System mode is an elevation: document the business reason, narrow the selected fields and affected records, validate inputs, and keep the privileged operation behind a small interface rather than spreading system mode through utility methods.

Choose failure or graceful degradation deliberately

A permission failure can be the correct outcome. If a user requests a confidential field or attempts an unauthorised update, failing closed with a safe message is clearer than silently producing a misleading result. User-mode SOQL and DML provide a direct enforcement path and expose inaccessible-field information through query and DML exceptions. Translate those failures into stable application errors without returning schema details, record values or stack traces to the client.

For experiences that can remain useful with fewer fields, Salesforce provides `Security.stripInaccessible()`. It can remove inaccessible fields from query results, sanitise deserialised sObjects and strip fields before DML while reporting what was removed. Use that deliberately, not as a blanket wrapper that hides a broken contract. A table may omit an optional cost field; an approval command must not quietly discard the approval amount and continue. Decide per use case whether missing access means reject, redact or offer a reduced capability.

Class access protects only the entry point

Profiles and permission sets can grant access to top-level Apex classes and transaction entry points such as `@AuraEnabled` controllers, Apex REST services and asynchronous classes. Salesforce also documents an important boundary: when an authorised entry class calls another class, the user can execute that secondary class through the entry point even without separate class access to it. Class access is therefore not a per-method authorization system for the internal call graph.

Keep entry classes thin. Parse and validate the request, establish the actor and business command, then call services whose contracts enforce data and domain access. Never assume that hiding an LWC button protects its Apex method, or that permission to call a controller implies permission to perform every operation it exposes. Split materially different capabilities into separate entry points or enforce explicit custom permissions inside the authoritative service. Treat all client-supplied IDs, field names and sObjects as untrusted input.

Put elevation behind narrow privileged services

Some operations must cross normal sharing boundaries: assigning a case to a central queue, reconciling orphaned records or applying a compliance hold. The mistake is not elevation; it is unbounded elevation. A broad `without sharing` repository that accepts arbitrary SOQL filters or field maps turns one valid exception into a reusable bypass for every caller.

Create a purpose-specific privileged service with a typed request, strict record scope, allow-listed fields, explicit business authorization and an auditable outcome. Separate discovery from execution: the caller can identify a candidate record in user context, while the privileged service revalidates eligibility before acting. Record the actor, reason, target and correlation reference. Review system-mode and `without sharing` code as security-sensitive architecture, and remove the elevation when the platform or data model no longer requires it.

Test the access matrix—not the happy path

Security tests must use realistic personas and records they own, can read through sharing, and cannot access. Salesforce's `System.runAs()` changes test user context and enforces that user's sharing, object and field permissions. Build cases for a fully authorised user, a user missing record access, one missing object access, one missing a sensitive field, and a caller who can invoke the entry class but lacks the business entitlement. Assert both permitted outcomes and the absence of forbidden data or side effects.

Add regression tests around mixed API versions, asynchronous entry points and every deliberate elevation. Inventory database operations that omit an access mode and classes that omit a sharing declaration, then migrate them with behaviour tests rather than mechanical search-and-replace. `with sharing` remains an essential default because it protects record visibility. It becomes trustworthy only when it is one explicit layer in a complete authorization contract that survives new callers, new fields and future platform versions.

Official references

Continue reading