@cclabsnz/sf-audit 1.15.1 → 1.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +143 -1
- package/README.md +100 -24
- package/config/scoring.sample.json +104 -5
- package/lib/apps/analyzeApps.d.ts +8 -2
- package/lib/apps/analyzeApps.js +7 -2
- package/lib/apps/apiLogSource.d.ts +39 -0
- package/lib/apps/apiLogSource.js +75 -0
- package/lib/apps/appResolver.js +30 -4
- package/lib/apps/grantedAccess.js +16 -3
- package/lib/apps/leastPrivilege.d.ts +3 -1
- package/lib/apps/leastPrivilege.js +7 -3
- package/lib/apps/permissionSetGenerator.d.ts +22 -0
- package/lib/apps/permissionSetGenerator.js +100 -0
- package/lib/apps/types.d.ts +6 -0
- package/lib/apps/usageCollector.d.ts +7 -1
- package/lib/apps/usageCollector.js +57 -26
- package/lib/chains/CapabilityRegistry.js +26 -0
- package/lib/chains/namedChains.js +110 -3
- package/lib/checks/CheckEngine.d.ts +3 -1
- package/lib/checks/CheckEngine.js +11 -3
- package/lib/checks/impl/AgentInventoryCheck.js +8 -3
- package/lib/checks/impl/AgentOutboundActionsCheck.d.ts +13 -0
- package/lib/checks/impl/AgentOutboundActionsCheck.js +155 -0
- package/lib/checks/impl/AgentQueryReachCheck.d.ts +11 -0
- package/lib/checks/impl/AgentQueryReachCheck.js +88 -0
- package/lib/checks/impl/ApexCrudFLSCheck.js +45 -10
- package/lib/checks/impl/ApexSharingCheck.js +16 -25
- package/lib/checks/impl/AuthProviderRegistrationHandlerCheck.d.ts +10 -0
- package/lib/checks/impl/AuthProviderRegistrationHandlerCheck.js +131 -0
- package/lib/checks/impl/ConnectedAppsCheck.js +47 -1
- package/lib/checks/impl/DataCloudDataSpaceIsolationCheck.d.ts +10 -0
- package/lib/checks/impl/DataCloudDataSpaceIsolationCheck.js +116 -0
- package/lib/checks/impl/DelegatedAdministrationGroupsCheck.d.ts +10 -0
- package/lib/checks/impl/DelegatedAdministrationGroupsCheck.js +75 -0
- package/lib/checks/impl/DelegatedAuthenticationExposureCheck.d.ts +10 -0
- package/lib/checks/impl/DelegatedAuthenticationExposureCheck.js +98 -0
- package/lib/checks/impl/ExternalAccountHierarchyExposureCheck.d.ts +10 -0
- package/lib/checks/impl/ExternalAccountHierarchyExposureCheck.js +73 -0
- package/lib/checks/impl/FlowHttpCalloutCredentialBypassCheck.d.ts +10 -0
- package/lib/checks/impl/FlowHttpCalloutCredentialBypassCheck.js +115 -0
- package/lib/checks/impl/GenAiPromptTemplateGroundingCheck.d.ts +10 -0
- package/lib/checks/impl/GenAiPromptTemplateGroundingCheck.js +227 -0
- package/lib/checks/impl/GuestExecutableApexCheck.d.ts +1 -1
- package/lib/checks/impl/GuestExecutableApexCheck.js +105 -14
- package/lib/checks/impl/HardcodedCredentialsCheck.js +7 -2
- package/lib/checks/impl/InboundEmailHandlerExposureCheck.d.ts +10 -0
- package/lib/checks/impl/InboundEmailHandlerExposureCheck.js +136 -0
- package/lib/checks/impl/OauthDeviceAndAssetTokenFlowsCheck.d.ts +10 -0
- package/lib/checks/impl/OauthDeviceAndAssetTokenFlowsCheck.js +84 -0
- package/lib/checks/impl/OrgWideEmailSpoofingCheck.d.ts +10 -0
- package/lib/checks/impl/OrgWideEmailSpoofingCheck.js +106 -0
- package/lib/checks/impl/PackagePostInstallSupplyChainCheck.d.ts +10 -0
- package/lib/checks/impl/PackagePostInstallSupplyChainCheck.js +89 -0
- package/lib/checks/impl/PlatformEventSubscriberContextCheck.d.ts +10 -0
- package/lib/checks/impl/PlatformEventSubscriberContextCheck.js +84 -0
- package/lib/checks/impl/RestrictionRulesIntegrityCheck.d.ts +10 -0
- package/lib/checks/impl/RestrictionRulesIntegrityCheck.js +105 -0
- package/lib/checks/impl/ShieldTenantSecretLifecycleCheck.d.ts +10 -0
- package/lib/checks/impl/ShieldTenantSecretLifecycleCheck.js +90 -0
- package/lib/checks/registry.js +34 -0
- package/lib/checks/support/agentGraph.d.ts +49 -0
- package/lib/checks/support/agentGraph.js +87 -0
- package/lib/checks/support/apexAccess.d.ts +56 -0
- package/lib/checks/support/apexAccess.js +127 -0
- package/lib/checks/support/missingObject.d.ts +13 -0
- package/lib/checks/support/missingObject.js +35 -0
- package/lib/commands/audit/apps.d.ts +1 -0
- package/lib/commands/audit/apps.js +83 -29
- package/lib/commands/audit/diff.js +2 -2
- package/lib/commands/audit/history.js +2 -2
- package/lib/commands/audit/incident/report.js +2 -2
- package/lib/commands/audit/security.d.ts +3 -0
- package/lib/commands/audit/security.js +58 -9
- package/lib/commands/audit/timeline.js +2 -2
- package/lib/compliance/mapping.js +35 -7
- package/lib/findings/AuditResult.d.ts +8 -0
- package/lib/findings/CheckMeta.js +17 -0
- package/lib/findings/Finding.d.ts +4 -0
- package/lib/findings/ScoringConfig.d.ts +10 -8
- package/lib/findings/ScoringConfig.js +12 -5
- package/lib/findings/coverage.d.ts +28 -0
- package/lib/findings/coverage.js +30 -0
- package/lib/findings/exitCode.js +1 -1
- package/lib/findings/loadScoringConfig.js +51 -8
- package/lib/findings/scoring.js +14 -5
- package/lib/history/HistoryStore.js +9 -3
- package/lib/history/archivePolicy.d.ts +19 -0
- package/lib/history/archivePolicy.js +34 -0
- package/lib/incident/bundleIo.js +4 -3
- package/lib/incident/collect/collectBundle.d.ts +1 -1
- package/lib/incident/collect/collectBundle.js +4 -3
- package/lib/incident/collect/streamGuestLogs.d.ts +1 -1
- package/lib/incident/collect/streamGuestLogs.js +3 -2
- package/lib/incident/csv.js +4 -4
- package/lib/incident/render/evidence.js +3 -3
- package/lib/incident/render/html.js +2 -3
- package/lib/index.d.ts +2 -0
- package/lib/index.js +2 -0
- package/lib/lib/packageInfo.d.ts +6 -0
- package/lib/lib/packageInfo.js +19 -0
- package/lib/renderers/AttackChainDagRenderer.d.ts +7 -0
- package/lib/renderers/AttackChainDagRenderer.js +139 -0
- package/lib/renderers/ClientReportRenderer.d.ts +2 -0
- package/lib/renderers/ClientReportRenderer.js +34 -6
- package/lib/renderers/DiffHtmlRenderer.js +2 -7
- package/lib/renderers/HistoryRenderer.js +19 -11
- package/lib/renderers/HtmlRenderer.js +19 -6
- package/lib/renderers/MarkdownRenderer.js +7 -0
- package/lib/renderers/SarifRenderer.d.ts +43 -0
- package/lib/renderers/SarifRenderer.js +250 -0
- package/lib/report/ExecutivePriorities.js +1 -1
- package/lib/report/RemediationRoadmap.js +1 -1
- package/lib/waivers/WaiverLoader.d.ts +28 -0
- package/lib/waivers/WaiverLoader.js +103 -0
- package/lib/waivers/WaiverModel.d.ts +32 -0
- package/lib/waivers/WaiverModel.js +28 -0
- package/lib/waivers/applyWaivers.d.ts +22 -0
- package/lib/waivers/applyWaivers.js +85 -0
- package/package.json +3 -3
|
@@ -29,7 +29,7 @@ export const NAMED_CHAINS = [
|
|
|
29
29
|
return null;
|
|
30
30
|
const steps = byIds(active, [
|
|
31
31
|
'guest-user-read-access', 'guest-user-write-access', 'guest-user-sharing-exposure', 'guest-user-baseline',
|
|
32
|
-
'guest-executable-apex-unprotected', 'guest-executable-apex-exposed',
|
|
32
|
+
'guest-executable-apex-unprotected', 'guest-executable-apex-exposed', 'guest-executable-apex-system-mode',
|
|
33
33
|
'guest-object-exposure-public-owd', 'guest-object-exposure-guest-owned',
|
|
34
34
|
'guest-api-access-enabled', 'guest-api-hard-delete', 'classic-sites-active',
|
|
35
35
|
'guest-user-visibility-view-all-users', 'guest-user-visibility-owd', 'guest-user-visibility-object-read',
|
|
@@ -39,8 +39,15 @@ export const NAMED_CHAINS = [
|
|
|
39
39
|
// analogue of portal-exposed Apex running without sharing.
|
|
40
40
|
'guest-record-access-policy-not-enforced',
|
|
41
41
|
'flows-autolaunched-without-sharing', 'flows-screen-without-sharing',
|
|
42
|
+
// An open inbound email handler grants unauth-foothold, so it must appear whenever it
|
|
43
|
+
// is what opened the gate.
|
|
44
|
+
'inbound-email-handler-unauthenticated-execution',
|
|
42
45
|
]);
|
|
43
|
-
|
|
46
|
+
if (steps.length < 2)
|
|
47
|
+
return null;
|
|
48
|
+
// Internal-only weaknesses that widen what a foothold reaches. They join as evidence but
|
|
49
|
+
// never count toward the floor: without a guest-side step they describe no unauthenticated path.
|
|
50
|
+
return [...steps, ...byIds(active, ['data-cloud-data-space-default-overshared', 'restriction-rules-inactive'])];
|
|
44
51
|
},
|
|
45
52
|
},
|
|
46
53
|
{
|
|
@@ -95,8 +102,21 @@ export const NAMED_CHAINS = [
|
|
|
95
102
|
// An integration account holding Author Apex, Customize Application or user-management
|
|
96
103
|
// permissions it does not use has the same escalation reach as users-author-apex above.
|
|
97
104
|
'integration-least-privilege-escalation-permissions',
|
|
105
|
+
// Grants unauth-foothold, so it must appear whenever it is what opened the gate.
|
|
106
|
+
'inbound-email-handler-unauthenticated-execution',
|
|
98
107
|
]);
|
|
99
|
-
|
|
108
|
+
if (steps.length < 2)
|
|
109
|
+
return null;
|
|
110
|
+
// Further escalation paths. They join as evidence but never count toward the floor, so two of
|
|
111
|
+
// them alone, with no low-trust step, cannot claim a standard-user path to takeover.
|
|
112
|
+
return [
|
|
113
|
+
...steps,
|
|
114
|
+
...byIds(active, [
|
|
115
|
+
'delegated-administration-groups-active',
|
|
116
|
+
'auth-provider-registration-handler-admin-exec', 'auth-provider-registration-handler-unverified-email-linking',
|
|
117
|
+
'delegated-authentication-admin-assigned', 'platform-event-subscriber-escalation',
|
|
118
|
+
]),
|
|
119
|
+
];
|
|
100
120
|
},
|
|
101
121
|
},
|
|
102
122
|
{
|
|
@@ -113,6 +133,7 @@ export const NAMED_CHAINS = [
|
|
|
113
133
|
'hardcoded-credentials-found', 'custom-labels-credential-value-match', 'custom-labels-credential-name-match',
|
|
114
134
|
'debug-log-active-traces', 'cors-wildcard-origin', 'cors-broad-origin',
|
|
115
135
|
'named-credentials-inventory', 'named-credentials-http-endpoint', 'remote-sites-inventory',
|
|
136
|
+
'flow-http-callout-hardcoded-secret', 'oauth-device-flow-enabled', 'oauth-password-flow-enabled',
|
|
116
137
|
// A user who can stand up connected apps and bypass API access control has provisioned
|
|
117
138
|
// their own egress path.
|
|
118
139
|
'separation-of-duties-external-exfil-channel',
|
|
@@ -189,6 +210,39 @@ export const NAMED_CHAINS = [
|
|
|
189
210
|
return [...agents, ...staleUrl, ...noCapture];
|
|
190
211
|
},
|
|
191
212
|
},
|
|
213
|
+
{
|
|
214
|
+
id: 'salesbleed-pattern',
|
|
215
|
+
title: 'SalesBleed pattern',
|
|
216
|
+
severity: 'HIGH',
|
|
217
|
+
narrative: 'An active agent can run open-ended record queries (the General CRM topic or Query Records action) and ' +
|
|
218
|
+
'the org has a way to send data out: agent actions that do so (Slack, email, external services) without ' +
|
|
219
|
+
'user confirmation, or a CSP Trusted URL whose domain is parked or no longer resolves, which anyone can ' +
|
|
220
|
+
'register and then receive whatever the agent puts in a link or image it returns. ' +
|
|
221
|
+
'That is two of the three ingredients in SalesBleed (Zenity Labs, Sept 2026) and PipeLeak (Capsule ' +
|
|
222
|
+
'Security, Apr 2026); the third, text an outsider wrote, arrives through Web-to-Lead, Web-to-Case, email or ' +
|
|
223
|
+
'chat in almost every org. One injected instruction in a lead can query Accounts and send the result out.',
|
|
224
|
+
remediation: 'Break any one link: remove open-ended querying from agents that read untrusted records, require user ' +
|
|
225
|
+
'confirmation on every outbound action, remove CSP Trusted URLs whose domains you no longer control, or ' +
|
|
226
|
+
'keep the agent that queries separate from the agent that sends.',
|
|
227
|
+
match(_present, active) {
|
|
228
|
+
const reach = byPrefixes(active, ['agent-query-reach-']);
|
|
229
|
+
// Egress: an outbound action that needs no confirmation, or a trusted domain anyone can claim.
|
|
230
|
+
const outbound = [
|
|
231
|
+
...byIds(active, ['agent-outbound-actions-unconfirmed', 'agent-outbound-actions-unverified']),
|
|
232
|
+
...byPrefixes(active, ['trusted-url-hygiene-parked-', 'trusted-url-hygiene-unresolvable-']),
|
|
233
|
+
];
|
|
234
|
+
if (reach.length === 0 || outbound.length === 0)
|
|
235
|
+
return null;
|
|
236
|
+
// Where outsider text enters, when the org shows it. Evidence only: the chain fires without
|
|
237
|
+
// it, since Web-to-Lead, Web-to-Case and email exist in almost every org.
|
|
238
|
+
const untrusted = byIds(active, [
|
|
239
|
+
'inbound-email-handler-unauthenticated-execution',
|
|
240
|
+
'guest-user-write-access',
|
|
241
|
+
'guest-object-exposure-guest-owned',
|
|
242
|
+
]);
|
|
243
|
+
return [...untrusted, ...reach, ...outbound];
|
|
244
|
+
},
|
|
245
|
+
},
|
|
192
246
|
{
|
|
193
247
|
id: 'sandbox-pii-exposure',
|
|
194
248
|
title: 'Unmasked production PII in a weakly-controlled sandbox',
|
|
@@ -383,6 +437,7 @@ export const NAMED_CHAINS = [
|
|
|
383
437
|
'portal-exposed-apex-without-sharing',
|
|
384
438
|
'flows-autolaunched-without-sharing', 'flows-screen-without-sharing',
|
|
385
439
|
'apex-rest-without-sharing',
|
|
440
|
+
'external-account-hierarchy-super-users', 'external-account-hierarchy-active',
|
|
386
441
|
]);
|
|
387
442
|
if (reach.length === 0)
|
|
388
443
|
return null;
|
|
@@ -525,5 +580,57 @@ export const NAMED_CHAINS = [
|
|
|
525
580
|
return [...vector, ...weakened, ...targets];
|
|
526
581
|
},
|
|
527
582
|
},
|
|
583
|
+
{
|
|
584
|
+
id: 'inbound-email-rce',
|
|
585
|
+
title: 'Unauthenticated inbound email to privileged code execution',
|
|
586
|
+
severity: 'CRITICAL',
|
|
587
|
+
narrative: 'An unauthenticated inbound email service address with no sender allowlist and no SPF/DKIM verification ' +
|
|
588
|
+
'accepts messages from any internet sender, executing Apex logic under a privileged running user or in a class ' +
|
|
589
|
+
'that bypasses CRUD/FLS and sharing. Attackers can trigger unattended data manipulation or code execution without credentials.',
|
|
590
|
+
remediation: 'Populate AuthorizedSenders on each email service address, set AuthenticationFailureAction to reject spoofed email, ' +
|
|
591
|
+
'and ensure email handler Apex classes enforce sharing, validate input, and execute as a dedicated least-privilege user.',
|
|
592
|
+
match(present, active) {
|
|
593
|
+
if (!has(present, 'unauth-foothold', 'code-exec'))
|
|
594
|
+
return null;
|
|
595
|
+
const vector = byIds(active, ['inbound-email-handler-unauthenticated-execution']);
|
|
596
|
+
if (vector.length === 0)
|
|
597
|
+
return null;
|
|
598
|
+
const followOn = byIds(active, [
|
|
599
|
+
'apex-crud-fls-without-sharing', 'soql-injection-risk', 'portal-exposed-apex-without-sharing',
|
|
600
|
+
'flows-autolaunched-without-sharing', 'users-modify-all-data', 'users-super-admin-combo',
|
|
601
|
+
'privileged-access-shadow-admins',
|
|
602
|
+
]);
|
|
603
|
+
return followOn.length > 0 ? [...vector, ...followOn] : null;
|
|
604
|
+
},
|
|
605
|
+
},
|
|
606
|
+
{
|
|
607
|
+
id: 'platform-event-priv-esc',
|
|
608
|
+
title: 'Guest or low-trust platform event publish to automated process escalation',
|
|
609
|
+
severity: 'CRITICAL',
|
|
610
|
+
narrative: 'A guest or portal user publishes a custom Platform Event that triggers an Apex trigger or Flow subscriber ' +
|
|
611
|
+
'executing as the Automated Process system user or an administrator. This bypasses normal user sharing, CRUD, and FLS, ' +
|
|
612
|
+
'providing an unauthenticated or low-trust path to system-context privilege escalation and state tampering.',
|
|
613
|
+
remediation: 'Revoke Create permissions on Platform Events from guest and Experience Cloud profiles. Configure ' +
|
|
614
|
+
'PlatformEventSubscriberConfig to run event triggers as a dedicated least-privilege user rather than Automated Process or an admin.',
|
|
615
|
+
match(present, active) {
|
|
616
|
+
if (!hasAny(present, 'unauth-foothold', 'low-trust-authenticated'))
|
|
617
|
+
return null;
|
|
618
|
+
if (!hasAny(present, 'priv-esc', 'data-write'))
|
|
619
|
+
return null;
|
|
620
|
+
const escalation = byIds(active, ['platform-event-subscriber-escalation']);
|
|
621
|
+
if (escalation.length === 0)
|
|
622
|
+
return null;
|
|
623
|
+
const foothold = byIds(active, [
|
|
624
|
+
'guest-user-read-access', 'guest-user-write-access', 'guest-user-sharing-exposure', 'guest-user-baseline',
|
|
625
|
+
'sharing-model-external-read', 'sharing-model-external-write', 'experience-cloud-site-self-registration',
|
|
626
|
+
]);
|
|
627
|
+
if (foothold.length === 0)
|
|
628
|
+
return null;
|
|
629
|
+
const targets = byIds(active, [
|
|
630
|
+
'users-super-admin-combo', 'users-modify-all-data', 'privileged-access-shadow-admins',
|
|
631
|
+
]);
|
|
632
|
+
return [...foothold, ...escalation, ...targets];
|
|
633
|
+
},
|
|
634
|
+
},
|
|
528
635
|
];
|
|
529
636
|
//# sourceMappingURL=namedChains.js.map
|
|
@@ -2,11 +2,13 @@ import type { SecurityCheck } from './SecurityCheck.js';
|
|
|
2
2
|
import type { AuditContext } from '@cclabsnz/sf-core';
|
|
3
3
|
import type { AuditResult } from '../findings/AuditResult.js';
|
|
4
4
|
import type { ScoringConfig } from '../findings/ScoringConfig.js';
|
|
5
|
+
import type { WaiverLoader } from '../waivers/WaiverLoader.js';
|
|
5
6
|
export declare class CheckEngine {
|
|
6
7
|
private readonly checks;
|
|
7
8
|
private readonly ctx;
|
|
8
9
|
private readonly scoringConfig?;
|
|
9
|
-
|
|
10
|
+
private readonly waiverLoader?;
|
|
11
|
+
constructor(checks: SecurityCheck[], ctx: AuditContext, scoringConfig?: ScoringConfig | undefined, waiverLoader?: WaiverLoader | undefined);
|
|
10
12
|
run(onProgress?: (current: number, total: number, checkName: string) => void): Promise<AuditResult>;
|
|
11
13
|
private validateCacheOrdering;
|
|
12
14
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { buildAuditResult } from '../findings/scoring.js';
|
|
2
2
|
import { getComplianceTags } from '../compliance/resolve.js';
|
|
3
3
|
import { ChainEngine } from '../chains/ChainEngine.js';
|
|
4
|
+
import { applyWaivers } from '../waivers/applyWaivers.js';
|
|
4
5
|
const PERMISSION_ERROR_CODES = new Set([
|
|
5
6
|
'INSUFFICIENT_ACCESS_RIGHTS',
|
|
6
7
|
'INVALID_CROSS_REFERENCE_KEY',
|
|
@@ -35,16 +36,20 @@ function buildErrorFinding(check, err) {
|
|
|
35
36
|
? 'Grant the audit user the permissions listed in the tool documentation, then re-run the audit.'
|
|
36
37
|
: 'Review the error message and verify the running user has the required permissions.',
|
|
37
38
|
inconclusive: inconclusive || undefined,
|
|
39
|
+
// A check that threw gathered no evidence, whatever the cause.
|
|
40
|
+
notAssessed: true,
|
|
38
41
|
};
|
|
39
42
|
}
|
|
40
43
|
export class CheckEngine {
|
|
41
44
|
checks;
|
|
42
45
|
ctx;
|
|
43
46
|
scoringConfig;
|
|
44
|
-
|
|
47
|
+
waiverLoader;
|
|
48
|
+
constructor(checks, ctx, scoringConfig, waiverLoader) {
|
|
45
49
|
this.checks = checks;
|
|
46
50
|
this.ctx = ctx;
|
|
47
51
|
this.scoringConfig = scoringConfig;
|
|
52
|
+
this.waiverLoader = waiverLoader;
|
|
48
53
|
this.validateCacheOrdering();
|
|
49
54
|
}
|
|
50
55
|
async run(onProgress) {
|
|
@@ -66,8 +71,11 @@ export class CheckEngine {
|
|
|
66
71
|
findings.push(buildErrorFinding(check, err));
|
|
67
72
|
}
|
|
68
73
|
}
|
|
69
|
-
|
|
70
|
-
|
|
74
|
+
// Waivers apply before correlation but do not remove findings from it: an accepted weakness
|
|
75
|
+
// still forms attack paths with the others.
|
|
76
|
+
const finalFindings = this.waiverLoader ? applyWaivers(findings, this.waiverLoader).findings : findings;
|
|
77
|
+
const attackChains = new ChainEngine().correlate(finalFindings);
|
|
78
|
+
return buildAuditResult(this.ctx, finalFindings, metrics, this.scoringConfig, attackChains);
|
|
71
79
|
}
|
|
72
80
|
validateCacheOrdering() {
|
|
73
81
|
const populated = new Set();
|
|
@@ -54,7 +54,8 @@ export class AgentInventoryCheck {
|
|
|
54
54
|
let versions;
|
|
55
55
|
let agentUsers;
|
|
56
56
|
try {
|
|
57
|
-
|
|
57
|
+
// BotVersion, like BotDefinition, is a data API object: Tooling answers INVALID_TYPE.
|
|
58
|
+
versions = await ctx.soql.queryAll(`SELECT Id, BotDefinitionId, Status, VersionNumber FROM BotVersion WHERE Status = 'Active'`);
|
|
58
59
|
// GenAiPlannerDefinition is queried for completeness of the agent picture (Phase 2
|
|
59
60
|
// action-surface work joins on it); a failure here still counts as an incomplete build.
|
|
60
61
|
await ctx.tooling.query(`SELECT Id, DeveloperName, MasterLabel FROM GenAiPlannerDefinition`);
|
|
@@ -159,13 +160,17 @@ export class AgentInventoryCheck {
|
|
|
159
160
|
// BotDefinition query with a defensive fallback: if Type/BotUserId are not queryable in
|
|
160
161
|
// this org/release (MALFORMED_QUERY on the field), retry with the minimal field set rather
|
|
161
162
|
// than throw. A genuinely missing object still throws and is handled by the caller.
|
|
163
|
+
//
|
|
164
|
+
// BotDefinition is a data API object. The Tooling API answers INVALID_TYPE for it even in
|
|
165
|
+
// orgs with active agents (verified 2026-10-09 on a v67.0 org), which the caller reads as
|
|
166
|
+
// "Agentforce not enabled" — so querying it through Tooling silenced every AI & Agents check.
|
|
162
167
|
async queryBotDefinitions(ctx) {
|
|
163
168
|
try {
|
|
164
|
-
return await ctx.
|
|
169
|
+
return await ctx.soql.queryAll(`SELECT Id, DeveloperName, MasterLabel, Type, BotUserId FROM BotDefinition`);
|
|
165
170
|
}
|
|
166
171
|
catch (e) {
|
|
167
172
|
if (isApiError(e) && /MALFORMED_QUERY|INVALID_FIELD/i.test(e.errorCode)) {
|
|
168
|
-
return ctx.
|
|
173
|
+
return ctx.soql.queryAll(`SELECT Id, DeveloperName, MasterLabel FROM BotDefinition`);
|
|
169
174
|
}
|
|
170
175
|
throw e;
|
|
171
176
|
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { AuditContext } from '@cclabsnz/sf-core';
|
|
2
|
+
import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
|
|
3
|
+
export declare class AgentOutboundActionsCheck implements SecurityCheck {
|
|
4
|
+
readonly id = "agent-outbound-actions";
|
|
5
|
+
readonly name = "Agent Outbound Actions";
|
|
6
|
+
readonly category = "AI & Agents";
|
|
7
|
+
readonly description = "Flags agent actions that send data out of the org (Slack messages, email, external services and MCP tools, including Flow actions whose flow sends email or calls an external service) without requiring user confirmation. An injected prompt can use them to carry data out: PipeLeak (Capsule Security, 2026) used the email action, and SalesBleed posted through Slack.";
|
|
8
|
+
readonly dependsOnCache: readonly ['agentInventory', 'agentAccess'];
|
|
9
|
+
run(ctx: AuditContext): Promise<CheckResult>;
|
|
10
|
+
private outboundFlows;
|
|
11
|
+
private inspectFlow;
|
|
12
|
+
}
|
|
13
|
+
//# sourceMappingURL=AgentOutboundActionsCheck.d.ts.map
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { loadAgentGraph } from '../support/agentGraph.js';
|
|
2
|
+
// Invocation types that hand data to something outside the org.
|
|
3
|
+
const EXTERNAL_TYPES = new Set(['slack', 'externalservice', 'externalconnector', 'mcptool', 'platformmcptool']);
|
|
4
|
+
// Standard invocable actions that send email (Flow's core "Send Email" and email alerts).
|
|
5
|
+
const EMAIL_TARGETS = new Set(['emailsimple', 'emailalert']);
|
|
6
|
+
// Standard Slack actions that post a message somewhere. Names verified from the
|
|
7
|
+
// GenAiPluginFunctionDef.Function picklist (v67.0).
|
|
8
|
+
const SLACK_SEND = /(^|__)(ReplyInThread|SendMessageAsAgent|SendMessageToSlackChannel|SendSlackDirectMessage)(_|$)/i;
|
|
9
|
+
// "SendClaimEmail", "SendVisitSummaryEmail": a name that sends rather than drafts an email.
|
|
10
|
+
const SEND_EMAIL_NAME = /(^|__|_)Send\w*Email/i;
|
|
11
|
+
// Flow action types that send data out. Read from the active flow version's metadata, because
|
|
12
|
+
// an agent's Flow action names the FlowDefinition Id, not what the flow does.
|
|
13
|
+
const FLOW_OUTBOUND = {
|
|
14
|
+
emailsimple: 'email',
|
|
15
|
+
emailalert: 'email',
|
|
16
|
+
externalservice: 'external service',
|
|
17
|
+
};
|
|
18
|
+
// Flows inspected per run. Each needs two Tooling reads; past this the rest are skipped.
|
|
19
|
+
const MAX_FLOWS = 25;
|
|
20
|
+
function outboundKind(fn) {
|
|
21
|
+
const type = (fn.InvocationTargetType ?? '').toLowerCase();
|
|
22
|
+
const target = (fn.InvocationTarget ?? '').toLowerCase();
|
|
23
|
+
const names = [fn.Source, fn.DeveloperName].filter((n) => !!n);
|
|
24
|
+
if (type === 'slack' || names.some((n) => SLACK_SEND.test(n)))
|
|
25
|
+
return 'Slack message';
|
|
26
|
+
if (EMAIL_TARGETS.has(target) || names.some((n) => SEND_EMAIL_NAME.test(n)))
|
|
27
|
+
return 'email';
|
|
28
|
+
if (EXTERNAL_TYPES.has(type))
|
|
29
|
+
return 'external service';
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
export class AgentOutboundActionsCheck {
|
|
33
|
+
id = 'agent-outbound-actions';
|
|
34
|
+
name = 'Agent Outbound Actions';
|
|
35
|
+
category = 'AI & Agents';
|
|
36
|
+
description = 'Flags agent actions that send data out of the org (Slack messages, email, external services and MCP tools, including Flow actions whose flow sends email or calls an external service) without requiring user confirmation. An injected prompt can use them to carry data out: PipeLeak (Capsule Security, 2026) used the email action, and SalesBleed posted through Slack.';
|
|
37
|
+
dependsOnCache = ['agentInventory', 'agentAccess'];
|
|
38
|
+
async run(ctx) {
|
|
39
|
+
const findings = [];
|
|
40
|
+
if (ctx.cache.agentAccess !== 'ok')
|
|
41
|
+
return { findings };
|
|
42
|
+
const activeAgents = (ctx.cache.agentInventory ?? []).filter((a) => a.type === 'agent' && a.isActive);
|
|
43
|
+
if (activeAgents.length === 0)
|
|
44
|
+
return { findings };
|
|
45
|
+
const graph = await loadAgentGraph(ctx, activeAgents);
|
|
46
|
+
if (!graph)
|
|
47
|
+
return { findings };
|
|
48
|
+
// Every action on a live topic, once each.
|
|
49
|
+
const live = new Map();
|
|
50
|
+
for (const topicId of graph.liveTopicIds)
|
|
51
|
+
for (const fn of graph.actionsByTopic.get(topicId) ?? [])
|
|
52
|
+
live.set(fn.Id, fn);
|
|
53
|
+
const setupUrl = `${ctx.orgInfo.instanceUrl}/lightning/setup/EinsteinCopilot/home`;
|
|
54
|
+
const unconfirmed = [];
|
|
55
|
+
const flowActions = [];
|
|
56
|
+
for (const fn of live.values()) {
|
|
57
|
+
if (fn.IsConfirmationRequired === true)
|
|
58
|
+
continue;
|
|
59
|
+
const kind = outboundKind(fn);
|
|
60
|
+
if (kind)
|
|
61
|
+
unconfirmed.push({ label: fn.MasterLabel ?? fn.DeveloperName, kind });
|
|
62
|
+
else if ((fn.InvocationTargetType ?? '').toLowerCase() === 'flow' && fn.InvocationTarget)
|
|
63
|
+
flowActions.push(fn);
|
|
64
|
+
}
|
|
65
|
+
for (const { fn, kind, flowName } of await this.outboundFlows(ctx, flowActions)) {
|
|
66
|
+
unconfirmed.push({ label: fn.MasterLabel ?? fn.DeveloperName, kind, via: flowName });
|
|
67
|
+
}
|
|
68
|
+
if (unconfirmed.length > 0) {
|
|
69
|
+
findings.push({
|
|
70
|
+
id: 'agent-outbound-actions-unconfirmed',
|
|
71
|
+
category: this.category,
|
|
72
|
+
riskLevel: 'HIGH',
|
|
73
|
+
title: `${unconfirmed.length} agent action(s) can send data out of the org without user confirmation`,
|
|
74
|
+
detail: `${unconfirmed.length} action(s) on active agents send a Slack message, an email or a call to an ` +
|
|
75
|
+
`external service, and none of them requires the user to confirm first. If an agent reads text an ` +
|
|
76
|
+
`outsider wrote (a lead, a case, an email), an injected instruction can use these actions to send ` +
|
|
77
|
+
`whatever the agent can read to an address or channel the attacker chooses. PipeLeak used the email ` +
|
|
78
|
+
`action this way; SalesBleed used Slack. Flow actions are judged by what the active flow version does; ` +
|
|
79
|
+
`Apex actions are not inspected. Rendered links and Slack link previews are further ways out that this ` +
|
|
80
|
+
`metadata audit cannot see.`,
|
|
81
|
+
remediation: 'Turn on "Require user confirmation" for each of these actions, or remove them from agents that read ' +
|
|
82
|
+
'untrusted input. Keep agents that send messages separate from agents that can query broadly.',
|
|
83
|
+
affectedItems: unconfirmed.map((u) => ({
|
|
84
|
+
label: u.label,
|
|
85
|
+
url: setupUrl,
|
|
86
|
+
note: `${u.kind}${u.via ? ` (flow ${u.via})` : ''}, no confirmation required`,
|
|
87
|
+
})),
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
// Standard outbound actions a live topic names with no local definition to read the setting from.
|
|
91
|
+
const unverified = [...new Set([...graph.liveTopicIds]
|
|
92
|
+
.flatMap((id) => graph.unresolvedActionsByTopic.get(id) ?? [])
|
|
93
|
+
.filter((n) => outboundKind({ DeveloperName: n, Source: null, InvocationTargetType: null, InvocationTarget: null }) !== null))];
|
|
94
|
+
if (unverified.length > 0) {
|
|
95
|
+
findings.push({
|
|
96
|
+
id: 'agent-outbound-actions-unverified',
|
|
97
|
+
category: this.category,
|
|
98
|
+
riskLevel: 'MEDIUM',
|
|
99
|
+
title: `${unverified.length} standard outbound action(s) in use; confirmation setting not readable`,
|
|
100
|
+
detail: `Topics on active agents use ${unverified.length} standard action(s) that post to Slack or send email ` +
|
|
101
|
+
`(${unverified.join(', ')}). The platform does not expose their confirmation setting through Tooling, ` +
|
|
102
|
+
`so this audit cannot tell whether a user must approve each message. Salesforce changed the default for ` +
|
|
103
|
+
`some Agentforce Slack actions to require confirmation after SalesBleed; agents configured earlier may ` +
|
|
104
|
+
`not have picked that up.`,
|
|
105
|
+
remediation: 'Open each agent that uses these actions in Agentforce Builder and confirm that user confirmation is ' +
|
|
106
|
+
'required before a message is sent. Remove the action where the agent does not need to post.',
|
|
107
|
+
affectedItems: unverified.map((n) => ({ label: n, url: setupUrl, note: 'standard action, confirmation not verified' })),
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
return { findings };
|
|
111
|
+
}
|
|
112
|
+
// For Flow actions, read the active version of each flow and report the first outbound step.
|
|
113
|
+
// An agent's Flow action targets the FlowDefinition by Id (300...) or by API name.
|
|
114
|
+
async outboundFlows(ctx, actions) {
|
|
115
|
+
const out = [];
|
|
116
|
+
const seen = new Map();
|
|
117
|
+
for (const fn of actions) {
|
|
118
|
+
const target = fn.InvocationTarget;
|
|
119
|
+
if (!seen.has(target)) {
|
|
120
|
+
if (seen.size >= MAX_FLOWS)
|
|
121
|
+
break;
|
|
122
|
+
seen.set(target, await this.inspectFlow(ctx, target));
|
|
123
|
+
}
|
|
124
|
+
const hit = seen.get(target);
|
|
125
|
+
if (hit)
|
|
126
|
+
out.push({ fn, ...hit });
|
|
127
|
+
}
|
|
128
|
+
return out;
|
|
129
|
+
}
|
|
130
|
+
async inspectFlow(ctx, target) {
|
|
131
|
+
try {
|
|
132
|
+
const where = /^300[A-Za-z0-9]{12}([A-Za-z0-9]{3})?$/.test(target)
|
|
133
|
+
? `Id = '${target}'`
|
|
134
|
+
: `DeveloperName = '${target.split('__').pop().replace(/'/g, '')}'`;
|
|
135
|
+
const [def] = await ctx.tooling.query(`SELECT Id, DeveloperName, ActiveVersionId FROM FlowDefinition WHERE ${where}`);
|
|
136
|
+
if (!def?.ActiveVersionId)
|
|
137
|
+
return null;
|
|
138
|
+
// Tooling returns Metadata for one Flow row per query.
|
|
139
|
+
const [version] = await ctx.tooling.query(`SELECT Id, Metadata FROM Flow WHERE Id = '${def.ActiveVersionId}'`);
|
|
140
|
+
for (const call of version?.Metadata?.actionCalls ?? []) {
|
|
141
|
+
const type = (call.actionType ?? '').toLowerCase();
|
|
142
|
+
const name = (call.actionName ?? '').toLowerCase();
|
|
143
|
+
const kind = FLOW_OUTBOUND[type] ?? (type.includes('slack') || name.includes('slack') ? 'Slack message' : undefined);
|
|
144
|
+
if (kind)
|
|
145
|
+
return { kind, flowName: def.DeveloperName };
|
|
146
|
+
}
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
// Flow metadata unreadable: make no claim about this action.
|
|
151
|
+
return null;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
//# sourceMappingURL=AgentOutboundActionsCheck.js.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { AuditContext } from '@cclabsnz/sf-core';
|
|
2
|
+
import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
|
|
3
|
+
export declare class AgentQueryReachCheck implements SecurityCheck {
|
|
4
|
+
readonly id = "agent-query-reach";
|
|
5
|
+
readonly name = "Agent Query Reach";
|
|
6
|
+
readonly category = "AI & Agents";
|
|
7
|
+
readonly description = "Flags agents that carry the standard General CRM topic or a Query Records action, which lets an injected prompt query any object the run-as user can read. This open-ended query is how SalesBleed (Zenity Labs, 2026) read Account data from a poisoned Web-to-Lead record.";
|
|
8
|
+
readonly dependsOnCache: readonly ['agentInventory', 'agentAccess'];
|
|
9
|
+
run(ctx: AuditContext): Promise<CheckResult>;
|
|
10
|
+
}
|
|
11
|
+
//# sourceMappingURL=AgentQueryReachCheck.d.ts.map
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { loadAgentGraph } from '../support/agentGraph.js';
|
|
2
|
+
// Standard names are namespaced (EmployeeCopilot__GeneralCRM); local copies carry them in Source
|
|
3
|
+
// or as a DeveloperName prefix with an id suffix (GeneralCRM_16jgK000002FoUn). Match by suffix
|
|
4
|
+
// so the namespace and local suffixes are not load-bearing.
|
|
5
|
+
const GENERAL_CRM = /(^|__)GeneralCRM(_|$)/i;
|
|
6
|
+
const QUERY_RECORDS = /(^|__)QueryRecords(WithAggregate)?(_|$)/i;
|
|
7
|
+
const matches = (re, ...names) => names.some((n) => !!n && re.test(n));
|
|
8
|
+
const isQueryAction = (fn) => matches(QUERY_RECORDS, fn.Source, fn.DeveloperName);
|
|
9
|
+
const topicLabel = (t) => t.MasterLabel ?? t.DeveloperName;
|
|
10
|
+
export class AgentQueryReachCheck {
|
|
11
|
+
id = 'agent-query-reach';
|
|
12
|
+
name = 'Agent Query Reach';
|
|
13
|
+
category = 'AI & Agents';
|
|
14
|
+
description = 'Flags agents that carry the standard General CRM topic or a Query Records action, which lets an injected prompt query any object the run-as user can read. This open-ended query is how SalesBleed (Zenity Labs, 2026) read Account data from a poisoned Web-to-Lead record.';
|
|
15
|
+
dependsOnCache = ['agentInventory', 'agentAccess'];
|
|
16
|
+
async run(ctx) {
|
|
17
|
+
const findings = [];
|
|
18
|
+
if (ctx.cache.agentAccess !== 'ok')
|
|
19
|
+
return { findings };
|
|
20
|
+
const activeAgents = (ctx.cache.agentInventory ?? []).filter((a) => a.type === 'agent' && a.isActive);
|
|
21
|
+
if (activeAgents.length === 0)
|
|
22
|
+
return { findings };
|
|
23
|
+
const graph = await loadAgentGraph(ctx, activeAgents);
|
|
24
|
+
if (!graph)
|
|
25
|
+
return { findings };
|
|
26
|
+
const setupUrl = `${ctx.orgInfo.instanceUrl}/lightning/setup/EinsteinCopilot/home`;
|
|
27
|
+
for (const planner of graph.planners) {
|
|
28
|
+
const reasons = new Set();
|
|
29
|
+
for (const topic of graph.topicsByPlanner.get(planner.Id) ?? []) {
|
|
30
|
+
if (matches(GENERAL_CRM, topic.Source, topic.DeveloperName))
|
|
31
|
+
reasons.add('General CRM topic');
|
|
32
|
+
const actions = graph.actionsByTopic.get(topic.Id) ?? [];
|
|
33
|
+
const unresolved = graph.unresolvedActionsByTopic.get(topic.Id) ?? [];
|
|
34
|
+
if (actions.some(isQueryAction) || unresolved.some((n) => QUERY_RECORDS.test(n))) {
|
|
35
|
+
reasons.add(topic.Id.startsWith('planner:') ? 'Query Records action' : `Query Records action (topic ${topicLabel(topic)})`);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
if (reasons.size === 0)
|
|
39
|
+
continue;
|
|
40
|
+
const label = planner.MasterLabel ?? planner.DeveloperName;
|
|
41
|
+
const why = [...reasons].join(', ');
|
|
42
|
+
findings.push({
|
|
43
|
+
id: `agent-query-reach-${planner.DeveloperName}`,
|
|
44
|
+
category: this.category,
|
|
45
|
+
riskLevel: 'HIGH',
|
|
46
|
+
title: `Agent "${label}" can run open-ended record queries`,
|
|
47
|
+
detail: `The agent "${label}" (${planner.DeveloperName}) has: ${why}. The standard General CRM topic and its ` +
|
|
48
|
+
`Query Records action let the model decide at run time which object to query, so an instruction ` +
|
|
49
|
+
`hidden in any record the agent reads (a Web-to-Lead or Web-to-Case submission, an inbound email, a ` +
|
|
50
|
+
`chat transcript) can make it query any object its run-as user can see. This is how SalesBleed read ` +
|
|
51
|
+
`Account data from a poisoned lead. Whether that data can then leave depends on the agent's output ` +
|
|
52
|
+
`channels; see agent-outbound-actions.` +
|
|
53
|
+
(graph.activeOnly ? '' : ' (Active versions could not be told apart, so every agent version was checked.)'),
|
|
54
|
+
remediation: 'Remove the General CRM topic or the Query Records action from agents that do not need open-ended ' +
|
|
55
|
+
'querying, and replace it with actions that read only the records the job needs. Where it must stay, ' +
|
|
56
|
+
'keep the agent away from untrusted input and trim its run-as user\'s object and field access.',
|
|
57
|
+
affectedItems: [{ label: `${label} (${planner.DeveloperName})`, url: setupUrl, note: why }],
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
// Query Records on topics no agent references. Only meaningful when every planner was in
|
|
61
|
+
// scope: once narrowed to active versions, inactive versions' topics are expected here.
|
|
62
|
+
if (findings.length === 0 && !graph.activeOnly) {
|
|
63
|
+
const orphans = [...graph.actionsByTopic.entries()]
|
|
64
|
+
.filter(([topicId, fns]) => !graph.liveTopicIds.has(topicId) && fns.some(isQueryAction))
|
|
65
|
+
.map(([topicId]) => topicId);
|
|
66
|
+
for (const [topicId, names] of graph.unresolvedActionsByTopic) {
|
|
67
|
+
if (!graph.liveTopicIds.has(topicId) && names.some((n) => QUERY_RECORDS.test(n)) && !orphans.includes(topicId))
|
|
68
|
+
orphans.push(topicId);
|
|
69
|
+
}
|
|
70
|
+
if (orphans.length > 0) {
|
|
71
|
+
findings.push({
|
|
72
|
+
id: 'agent-query-reach-unmapped',
|
|
73
|
+
category: this.category,
|
|
74
|
+
riskLevel: 'MEDIUM',
|
|
75
|
+
title: `Query Records is configured on ${orphans.length} topic(s) not tied to a specific agent`,
|
|
76
|
+
detail: `The open-ended Query Records action is attached to ${orphans.length} topic(s), but the platform did ` +
|
|
77
|
+
`not expose a link from those topics to an agent. ${activeAgents.length} active agent(s) exist, so ` +
|
|
78
|
+
`confirm in Agentforce Builder whether any of them uses these topics.`,
|
|
79
|
+
remediation: 'Open each active agent in Agentforce Builder and check its topics for Query Records. Remove it where ' +
|
|
80
|
+
'the agent does not need open-ended querying.',
|
|
81
|
+
affectedItems: orphans.map((id) => ({ label: id, url: setupUrl, note: 'topic with Query Records' })),
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return { findings };
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
//# sourceMappingURL=AgentQueryReachCheck.js.map
|
|
@@ -1,8 +1,15 @@
|
|
|
1
|
+
import { testApexPattern } from '@cclabsnz/sf-core';
|
|
2
|
+
import { apexCode, codeWithoutStrings, DML_AS_USER, usesSystemMode } from '../support/apexAccess.js';
|
|
1
3
|
// Patterns that indicate DML or inline SOQL is being performed
|
|
2
|
-
const HAS_DML = /\b(?:insert|update|delete|upsert|merge)\s+\w+|Database\.(?:insert|update|delete|upsert|merge)\s*\(/i;
|
|
3
|
-
|
|
4
|
+
const HAS_DML = /\b(?:insert|update|delete|upsert|undelete|merge)\s+\w+|Database\.(?:insert|update|delete|upsert|undelete|merge)\w*\s*\(/i;
|
|
5
|
+
// SOQL and SOSL, inline or dynamic.
|
|
6
|
+
const HAS_SOQL = /\[\s*(?:SELECT|FIND)\b|Database\.(?:query|queryWithBinds|countQuery|countQueryWithBinds|getQueryLocator|getQueryLocatorWithBinds|getCursor|getCursorWithBinds)\s*\(|\bSearch\.(?:query|find)\s*\(/i;
|
|
4
7
|
// Patterns that indicate FLS/CRUD is being checked or enforced
|
|
5
|
-
|
|
8
|
+
// USER_MODE enforces CRUD/FLS (and sharing) on the query or DML it is attached to.
|
|
9
|
+
const HAS_FLS = /(?:\.isAccessible\(\)|\.isCreateable\(\)|\.isUpdateable\(\)|\.isDeletable\(\)|Security\.stripInaccessible|SObjectAccessDecision|Schema\.describeSObjects|Schema\.sObjectType\.\w+\.fields|\bWITH\s+USER_MODE\b|\bAccessLevel\s*\.\s*USER_MODE\b)/i;
|
|
10
|
+
// SYSTEM_MODE (WITH SYSTEM_MODE, AccessLevel.SYSTEM_MODE, `insert as system`) switches CRUD/FLS
|
|
11
|
+
// off for that operation; sharing still follows the class keyword. It is never enforcement,
|
|
12
|
+
// whatever else the class does, and batch or scheduled classes are no exception (spec RULE-002).
|
|
6
13
|
// Classes that are exempt from CRUD/FLS enforcement by design:
|
|
7
14
|
// batch, scheduled, and trigger handlers run in a system context
|
|
8
15
|
const IS_BATCH_OR_SCHEDULED = /implements\s+(?:Database\.Batchable|Schedulable|Database\.StatefulBatch|Database\.AllowsCallouts)/i;
|
|
@@ -31,20 +38,33 @@ export class ApexCrudFLSCheck {
|
|
|
31
38
|
}
|
|
32
39
|
const withoutSharingNoFls = [];
|
|
33
40
|
const withDmlNoFls = [];
|
|
41
|
+
const systemMode = [];
|
|
34
42
|
// apexBodies is pre-filtered by HardcodedCredentialsCheck, which excludes @IsTest classes
|
|
35
43
|
// before populating the cache. There is deliberately no second guard here: a cache miss
|
|
36
44
|
// yields an empty array, not unfiltered bodies, so there is nothing for one to catch.
|
|
37
|
-
for (const { name, body } of apexBodies) {
|
|
38
|
-
if (!
|
|
45
|
+
for (const { name, body: raw } of apexBodies) {
|
|
46
|
+
if (!raw)
|
|
39
47
|
continue;
|
|
40
|
-
|
|
41
|
-
const
|
|
48
|
+
// Patterns are matched against code only: "WITH USER_MODE" in a comment enforces nothing.
|
|
49
|
+
const body = apexCode(raw);
|
|
50
|
+
// SYSTEM_MODE only ever qualifies a query or DML, so it is reported before, and regardless
|
|
51
|
+
// of, the pattern gate below: a form that gate does not know must not slip through (RULE-002).
|
|
52
|
+
if (usesSystemMode(raw)) {
|
|
53
|
+
systemMode.push({ name, withoutSharing: testApexPattern(body, WITHOUT_SHARING) });
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
const hasDml = testApexPattern(body, HAS_DML);
|
|
57
|
+
const hasSoql = testApexPattern(body, HAS_SOQL);
|
|
42
58
|
if (!hasDml && !hasSoql)
|
|
43
59
|
continue;
|
|
44
|
-
|
|
60
|
+
if (testApexPattern(body, IS_BATCH_OR_SCHEDULED))
|
|
61
|
+
continue;
|
|
62
|
+
// Enforcement must be code, not text: 'WITH USER_MODE' inside a debug string enforces nothing.
|
|
63
|
+
const enforcementCode = codeWithoutStrings(raw);
|
|
64
|
+
const hasFls = testApexPattern(enforcementCode, HAS_FLS) || testApexPattern(enforcementCode, DML_AS_USER);
|
|
45
65
|
if (hasFls)
|
|
46
66
|
continue;
|
|
47
|
-
if (
|
|
67
|
+
if (testApexPattern(body, WITHOUT_SHARING)) {
|
|
48
68
|
withoutSharingNoFls.push(name);
|
|
49
69
|
}
|
|
50
70
|
else {
|
|
@@ -81,7 +101,22 @@ export class ApexCrudFLSCheck {
|
|
|
81
101
|
})),
|
|
82
102
|
});
|
|
83
103
|
}
|
|
84
|
-
if (
|
|
104
|
+
if (systemMode.length > 0) {
|
|
105
|
+
findings.push({
|
|
106
|
+
id: 'apex-crud-fls-system-mode',
|
|
107
|
+
category: this.category,
|
|
108
|
+
riskLevel: 'MEDIUM',
|
|
109
|
+
title: `${systemMode.length} Apex class(es) switch off CRUD/FLS with SYSTEM_MODE`,
|
|
110
|
+
detail: 'WITH SYSTEM_MODE and AccessLevel.SYSTEM_MODE run a query or DML without checking the user\'s object and field permissions. Record sharing still follows the class keyword, so this exposes fields and objects the user cannot otherwise see on records they can reach; in a "without sharing" class it exposes every record too.',
|
|
111
|
+
remediation: 'Use WITH USER_MODE / AccessLevel.USER_MODE wherever the operation serves a user. Where SYSTEM_MODE is genuinely needed, keep it to the narrowest query and strip fields with Security.stripInaccessible() before returning results.',
|
|
112
|
+
affectedItems: systemMode.slice(0, 30).map(({ name, withoutSharing }) => ({
|
|
113
|
+
label: name,
|
|
114
|
+
url: apexClassesUrl,
|
|
115
|
+
note: withoutSharing ? 'SYSTEM_MODE in a "without sharing" class: no CRUD/FLS and no sharing' : 'SYSTEM_MODE: CRUD/FLS not enforced',
|
|
116
|
+
})),
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
if (withoutSharingNoFls.length === 0 && withDmlNoFls.length === 0 && systemMode.length === 0) {
|
|
85
120
|
findings.push({
|
|
86
121
|
id: 'apex-crud-fls-ok',
|
|
87
122
|
category: this.category,
|