grzmol/vibe-force/sf-security-model

Claude Code and agent skill by grzmol/vibe-force

Trust tier 3
  • community
  • ext:[{"type":"hook","description":"Pre/post lifecycle hooks"}]
Source check pending

Checking that the SKILL.md file is still in the repository.

Salesforce security model and secure-coding enforcement for Apex, LWC, and metadata - org/object/field/record layers, permission sets vs profiles vs permission set groups vs muting permission sets, CRUD and FLS enforcement with WITH USER_MODE, AccessLevel.USER_MODE, Security.stripInaccessible, and Schema describe checks, sharing keywords and Apex managed sharing __Share records, Lightning Web Security and CSP, SOQL injection, XSS, open redirect and CSRF fixes, Named Credentials and protected custom metadata for secrets, Shield Platform Encryption impacts, and Event Monitoring. Use when writing or reviewing @AuraEnabled controllers, triggers, dynamic SOQL, lwc:dom="manual" markup, permission set metadata, integration users, or when running vf-check analyzer or the sf-security-reviewer agent.

Install

npx vskill@latest install grzmol/vibe-force/sf-security-model

Semi-extensibleMentions customization, but needs skill-specific knowledge. Read the extensible skills standard

SKILL.md

The same SKILL.md was published earlier as grzmol/vibe-force/sf-security-model.

Salesforce Security Model

When to use

  • Any Apex class that queries or writes data, especially @AuraEnabled, @InvocableMethod, @RestResource, global, or Visualforce controller entry points.
  • Building or reviewing permission metadata (permissionsets/, permissionsetgroups/, object/field permissions).
  • Dynamic SOQL/SOSL, Database.query, string-concatenated queries, lwc:dom="manual", innerHTML, redirects, HTTP callouts with credentials.
  • Wave 2 of the vibe-force workflow: sf-security-reviewer reads this skill before reviewing a diff; vf-check analyzer enforces the machine-verifiable subset.
  • Auditing the standing posture of a whole org rather than one change: skill sf-org-security-audit, which reuses the permission queries in references/permission-architecture.md.

API version 67.0 default-mode change (read this first)

config/vibe-force.defaults.json pins apiVersion 67.0. That version changed the Apex security defaults:

BehaviourAPI 66.0 and earlierAPI 67.0 and later
Database operation access modesystem mode (FLS/object perms ignored)user mode (FLS, object perms, sharing enforced)
Class with no sharing declarationresolved per inheritance chain / entry point, often without sharing`with sharing`
Trigger body DML/SOQLsystem modeuser mode, which overrides the trigger's own without sharing context
Anonymous Apex, Connect in Apexwith sharingwith sharing
WITH SECURITY_ENFORCED in a SOQL SELECT in Apexallowed, with limitationsnot allowed - the compiler rejects it; use WITH USER_MODE

Consequences for vibe-force code: never rely on the default. Declare with sharing / inherited sharing / without sharing explicitly on every class with data access, and set an explicit access mode (WITH USER_MODE, WITH SYSTEM_MODE, as user, as system, AccessLevel.*) on every database operation so the code reads the same on any API version. Triggers cannot carry a sharing declaration: they always run without sharing, so delegate to a handler class (see skill sf-apex-development).

Security layer decision table

LayerControlsConfigured withEnforced in Apex by
Orglogin IP ranges, hours, MFA, session settingsSetup, security policiesnothing in code
Object (CRUD)create/read/edit/delete per objectpermission sets, permission set groups, profilesuser mode, Schema.DescribeSObjectResult.isCreateable/isAccessible/isUpdateable/isDeletable, stripInaccessible
Field (FLS)read/edit per fieldpermission sets (fieldPermissions)user mode, Schema.DescribeFieldResult, stripInaccessible
Recordwhich rows a user seesOWD, role hierarchy, sharing rules, manual shares, Apex managed sharing, restriction rulesclass sharing keyword + user mode
Apex/VF classwho may invoke the classclassAccesses / pageAccesses in permission setsruntime access check on @AuraEnabled and VF entry points
ClientDOM/script isolationLightning Web Security, CSPLWS sandbox, lightning/ui*Api (enforces FLS server-side)

Object/field permissions and sharing are independent and can coexist; where they conflict, object-level and field-level permissions take precedence over sharing rules.

Core patterns

1. Query in user mode (default choice)
apex
public with sharing class ExpenseSelector {
public static List<Expense__c> recent(Integer rowLimit) {
return [
SELECT Id, Name, Amount__c, Client__c, Date__c
FROM Expense__c
WHERE Date__c = LAST_N_DAYS:30
WITH USER_MODE
ORDER BY Date__c DESC
LIMIT :rowLimit
];
}
}

WITH USER_MODE processes every clause including WHERE, supports polymorphic fields (Owner, Task.WhatId), reports all FLS errors, and exposes them through QueryException.getInaccessibleFields(). It is the only clause-based option at our target version: in API 67.0 and later a SOQL SELECT in Apex cannot use WITH SECURITY_ENFORCED at all. Legacy (pre-67.0) code that still carries WITH SECURITY_ENFORCED must be migrated to WITH USER_MODE when its class is raised to 67.0; that clause also reported only the first error, skipped the WHERE clause, ignored polymorphic fields, and was never allowed in AppExchange packages.

2. DML in user mode, with error introspection
apex
public with sharing class ExpenseWriter {
public static void save(List<Expense__c> expenses) {
List<Database.SaveResult> results = Database.insert(expenses, false, AccessLevel.USER_MODE);
for (Database.SaveResult r : results) {
if (!r.isSuccess()) {
for (Database.Error e : r.getErrors()) {
System.debug(LoggingLevel.WARN, e.getStatusCode() + ' on ' + e.getFields());
}
}
}
}
}

Statement form: insert as user expenses; / update as system expenses;. On a user-mode DmlException, getDmlFieldNames() returns the fields that failed FLS.

3. Graceful degradation with stripInaccessible
apex
SObjectAccessDecision decision = Security.stripInaccessible(
AccessType.READABLE,
[SELECT Name, BudgetedCost, ActualCost FROM Campaign WITH SYSTEM_MODE]
);
if (decision.getRemovedFields().get('Campaign')?.contains('ActualCost') == true) {
// render the table without ActualCost instead of throwing
}
List<Campaign> safe = (List<Campaign>) decision.getRecords();

AccessType values: READABLE, CREATABLE, UPDATABLE, UPSERTABLE. Id is never stripped. AggregateResult is unsupported and throws. Use getModifiedIndexes() to detect that anything was stripped, and sObject.isSet('Field__c') to test a specific field.

4. Dynamic SOQL without injection
apex
Map<String, Object> binds = new Map<String, Object>{ 'title' => '%' + userInput + '%' };
List<Personnel__c> rows = Database.queryWithBinds(
'SELECT Id, Name, Title__c FROM Personnel__c WHERE Title__c LIKE :title',
binds,
AccessLevel.USER_MODE
);

Database.queryWithBinds (API 57.0+) resolves binds from a map, so the variables need not be in scope. Bind map keys are compared case-insensitively; duplicate case-variant keys throw QueryException. String.escapeSingleQuotes only helps inside single-quoted literals and is explicitly not the recommended defence. Field and object names cannot be bound: allowlist them (Set<String> of permitted API names) plus a describe accessibility check.

5. Record access beyond sharing rules: Apex managed sharing
apex
Job__Share share = new Job__Share(
ParentId = job.Id,
UserOrGroupId = job.Recruiter__c,
AccessLevel = 'Edit',
RowCause = Schema.Job__Share.RowCause.Recruiter__c
);
Database.SaveResult sr = Database.insert(share, false, AccessLevel.USER_MODE);

Share objects are <Object>Share / MyObject__Share. Access levels: Read, Edit, All (All is managed-sharing only; None applies to AccountShare only). Apex sharing reasons (RowCause) are custom-object-only and survive owner changes; RowCause = 'Manual' shares are deleted when the owner changes. The object's OWD must not already be the most permissive setting, otherwise insert fails with FIELD_FILTER_VALIDATION_EXCEPTION. Details and the recalculation batch pattern: references/sharing-and-record-access.md.

6. Ship permission sets, not profiles

Grant all functional access through permission sets and compose them with permission set groups; use muting permission sets to subtract from a group rather than forking a permission set. Profiles stay minimal (Minimum Access - Salesforce plus license/defaults). Metadata shapes, retrieval caveats, and deployment ordering: references/permission-architecture.md.

7. Secrets never live in source
NeedUseNever
Outbound HTTP authNamed Credential + External Credential (callout:MyNC/path)hardcoded tokens, setHeader('Authorization', 'Bearer ...')
Package-scoped secretprotected custom metadata type in a namespaced managed packagecustom setting readable by users
Org-local operational secretprotected custom setting / custom metadata restricted by permission setApex constant, static resource
Crypto keys/IVsCrypto.generateAesKey, stored via the aboveliteral key/IV in Apex (ApexBadCrypto)

Credentials in ExternalCredential are encrypted by the platform with org-specific keys. vibe-force hooks scan writes for credential-looking literals and block them in standard and strict hook modes; vf-check analyzer flags ApexSuggestUsingNamedCred and ApexBadCrypto.

8. Client-side security
  • Lightning Web Security is the default architecture for orgs created in Winter '23 and later and GA for all orgs since Summer '23; it replaces Lightning Locker with per-namespace JavaScript virtualization. Components must not override window/document functions, must load libraries via lightning/platformResourceLoader from a static resource, and must not use inline <script>.
  • CSP for Lightning is default-src 'self', script-src 'self', object-src 'self', style-src 'self' https:, img-src 'self' http: https: data:, connect-src 'self', frame-src https:, frame-ancestors https:, font-src https: data:. Enable the stricter CSP org setting and develop against it. unsafe-inline and unsafe-eval are not blocked by CSP today but are rejected in AppExchange security review.
  • lightning/uiRecordApi, lightning-record-form, and the other Lightning Data Service wire adapters apply sharing, CRUD, and FLS for you. Prefer them over custom @AuraEnabled data plumbing (skill sf-lwc-development).
  • Every @AuraEnabled method is a public web service: assume an attacker calls it with arbitrary parameters, regardless of what your component sends.

Anti-patterns

Anti-patternWhy it failsFix
public class Svc { ... } with DMLsharing mode depends on API version and call chaindeclare with sharing (or inherited sharing for reusable services)
[SELECT ... FROM Account] in a class saved at 66.0 and callers assuming FLSpre-67.0 default is system modeadd WITH USER_MODE
Database.query('... WHERE Name = \'' + input + '\'')SOQL injectionDatabase.queryWithBinds with AccessLevel.USER_MODE
String.escapeSingleQuotes(input) on an unquoted boolean/number positionescaping does nothing outside quotestypecast or allowlist
with sharing used as an FLS controlsharing keywords set record access onlyadd user mode or stripInaccessible
stripInaccessible result discarded (insert original;)inaccessible fields still writteninsert decision.getRecords()
WITH SECURITY_ENFORCED anywhere in new Apexrejected by the compiler at API 67.0 and laterWITH USER_MODE
this.template.querySelector('div').innerHTML = serverHtmlXSS inside the componentrender with template directives, or sanitize before lwc:dom="manual"
PageReference(ApexPages.currentPage().getParameters().get('retURL'))open redirect (ApexOpenRedirect)allowlist relative paths
DML in a constructor or @AuraEnabled(cacheable=true) getterCSRF-on-GET (ApexCSRF)move state changes to an explicit POST-style action
System.debug(userRecord) with PII, APEX_CODE=FINEST in proddebug logs leak PII; FINEST logs every variable assignmentscrub logs, cap log level (skill sf-debugging-logs)
Integration user with Modify All Datano least privilege, blast radius on token leakdedicated integration permission set, object-scoped

Verification

bash
# security-tagged static analysis (PMD + ESLint + Flow + Regex engines)
sf code-analyzer run --workspace . --rule-selector Security --view detail

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

7-day trend score
0

Not refreshed yet.

Extension points

  • hookPre/post lifecycle hooks

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/grzmol/vibe-force/sf-security-model/badge)](https://verified-skill.com/skills/grzmol/vibe-force/sf-security-model)

Something wrong with this skill or its page? Tell us.