@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
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { queryIfPresent } from '../support/missingObject.js';
|
|
2
|
+
function isMissingPrmField(err) {
|
|
3
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
4
|
+
return /No such column 'IsPrmSuperUser'/i.test(msg);
|
|
5
|
+
}
|
|
6
|
+
export class ExternalAccountHierarchyExposureCheck {
|
|
7
|
+
id = 'external-account-hierarchy-exposure';
|
|
8
|
+
name = 'External Account Hierarchy & Partner Super User Exposure';
|
|
9
|
+
category = 'External-Facing Access';
|
|
10
|
+
description = 'Flags Partner Super User access and External Account Hierarchies that bypass external OWD and widen portal visibility.';
|
|
11
|
+
async run(ctx) {
|
|
12
|
+
const findings = [];
|
|
13
|
+
const baseUrl = ctx.orgInfo.instanceUrl;
|
|
14
|
+
const usersUrl = `${baseUrl}/lightning/setup/ManageUsers/home`;
|
|
15
|
+
// 1. Active users with Partner Super User access. User.IsPrmSuperUser only exists in orgs
|
|
16
|
+
// with a partner (PRM) licence; there its absence means no super users. Any other error
|
|
17
|
+
// propagates so the check reports inconclusive rather than clean.
|
|
18
|
+
let superUsers;
|
|
19
|
+
try {
|
|
20
|
+
superUsers = await ctx.soql.queryAll('SELECT Id, Username, IsActive, IsPrmSuperUser FROM User WHERE IsPrmSuperUser = true AND IsActive = true');
|
|
21
|
+
}
|
|
22
|
+
catch (err) {
|
|
23
|
+
if (!isMissingPrmField(err))
|
|
24
|
+
throw err;
|
|
25
|
+
superUsers = [];
|
|
26
|
+
}
|
|
27
|
+
if (superUsers.length > 0) {
|
|
28
|
+
findings.push({
|
|
29
|
+
id: 'external-account-hierarchy-super-users',
|
|
30
|
+
category: this.category,
|
|
31
|
+
riskLevel: 'HIGH',
|
|
32
|
+
title: `${superUsers.length} active portal user(s) granted Partner Super User Access (IsPrmSuperUser)`,
|
|
33
|
+
detail: 'Enabling Partner Super User Access grants external portal users visibility across all cases, opportunities, contacts, and custom objects owned by other partner users in their partner account hierarchy. This broadens data access beyond standard sharing rules and circumvents Private External Org-Wide Defaults.',
|
|
34
|
+
remediation: 'Review all users with Partner Super User Access in Setup → Users, and disable IsPrmSuperUser unless justified by strict business need.',
|
|
35
|
+
affectedItems: superUsers.map((u) => ({
|
|
36
|
+
label: u.Username,
|
|
37
|
+
url: `${baseUrl}/lightning/setup/ManageUsers/page?address=%2F${u.Id}`,
|
|
38
|
+
note: 'IsPrmSuperUser = true: cross-user record visibility in portal',
|
|
39
|
+
})),
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
// 2. Query ExternalAccountHierarchy records
|
|
43
|
+
const hierarchies = await queryIfPresent(() => ctx.soql.queryAll('SELECT Id, MasterLabel FROM ExternalAccountHierarchy'));
|
|
44
|
+
if (hierarchies.length > 0) {
|
|
45
|
+
findings.push({
|
|
46
|
+
id: 'external-account-hierarchy-active',
|
|
47
|
+
category: this.category,
|
|
48
|
+
riskLevel: 'HIGH',
|
|
49
|
+
title: `${hierarchies.length} active External Account Hierarchy relationship(s) configured`,
|
|
50
|
+
detail: 'External Account Hierarchies link separate partner and customer portal accounts into parent-child relationships, granting parent portal users upward and horizontal record visibility across child accounts without standard sharing rules.',
|
|
51
|
+
remediation: 'Audit all active External Account Hierarchy relationships in Setup → External Account Hierarchies to verify cross-account data exposure conforms to least-privilege sharing models.',
|
|
52
|
+
affectedItems: hierarchies.map((h) => ({
|
|
53
|
+
label: h.MasterLabel || h.Id,
|
|
54
|
+
url: usersUrl,
|
|
55
|
+
note: 'External Account Hierarchy active',
|
|
56
|
+
})),
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
if (superUsers.length === 0 && hierarchies.length === 0) {
|
|
60
|
+
findings.push({
|
|
61
|
+
id: 'external-account-hierarchy-ok',
|
|
62
|
+
category: this.category,
|
|
63
|
+
riskLevel: 'LOW',
|
|
64
|
+
passed: true,
|
|
65
|
+
title: 'No Partner Super Users or External Account Hierarchies widening portal visibility',
|
|
66
|
+
detail: 'External portal users are constrained to their own account boundaries without hierarchical over-sharing.',
|
|
67
|
+
remediation: 'Maintain standard Private external OWD and avoid unreviewed Super User grants.',
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
return { findings };
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
//# sourceMappingURL=ExternalAccountHierarchyExposureCheck.js.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { AuditContext } from '@cclabsnz/sf-core';
|
|
2
|
+
import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
|
|
3
|
+
export declare class FlowHttpCalloutCredentialBypassCheck implements SecurityCheck {
|
|
4
|
+
readonly id = "flow-http-callout-credential-bypass";
|
|
5
|
+
readonly name = "Flow HTTP Callout Credential Bypass";
|
|
6
|
+
readonly category = "Integration Security";
|
|
7
|
+
readonly description = "Detects declarative Flow HTTP callouts storing credentials in formulas or bypassing modern Named Credentials.";
|
|
8
|
+
run(ctx: AuditContext): Promise<CheckResult>;
|
|
9
|
+
}
|
|
10
|
+
//# sourceMappingURL=FlowHttpCalloutCredentialBypassCheck.d.ts.map
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { FlowRepository } from '@cclabsnz/sf-core';
|
|
2
|
+
import { queryIfPresent } from '../support/missingObject.js';
|
|
3
|
+
/** Flow.Metadata is one row per Tooling query, so reads run concurrently but bounded. */
|
|
4
|
+
const METADATA_CONCURRENCY = 8;
|
|
5
|
+
// Patterns for hardcoded credentials / tokens in Flow formulas, headers, or parameters
|
|
6
|
+
const SECRET_PATTERNS = [
|
|
7
|
+
/Bearer\s+[A-Za-z0-9_.-]{12,}/i,
|
|
8
|
+
/Basic\s+[A-Za-z0-9+/=]{16,}/i,
|
|
9
|
+
/(?:api[_-]?key|client[_-]?secret|auth[_-]?token|webhook[_-]?secret)\s*[:=]\s*['"][^'"]{8,}['"]/i,
|
|
10
|
+
/https?:\/\/[^:]+:[^@]+@/i,
|
|
11
|
+
];
|
|
12
|
+
export class FlowHttpCalloutCredentialBypassCheck {
|
|
13
|
+
id = 'flow-http-callout-credential-bypass';
|
|
14
|
+
name = 'Flow HTTP Callout Credential Bypass';
|
|
15
|
+
category = 'Integration Security';
|
|
16
|
+
description = 'Detects declarative Flow HTTP callouts storing credentials in formulas or bypassing modern Named Credentials.';
|
|
17
|
+
async run(ctx) {
|
|
18
|
+
const findings = [];
|
|
19
|
+
const baseUrl = ctx.orgInfo.instanceUrl;
|
|
20
|
+
const externalServices = await queryIfPresent(() => ctx.tooling.query('SELECT Id, DeveloperName, MasterLabel, NamedCredentialId FROM ExternalServiceRegistration'));
|
|
21
|
+
const uncredentialedServices = externalServices.filter((s) => !s.NamedCredentialId || s.NamedCredentialId.trim() === '');
|
|
22
|
+
// Credentials live in the flow definition (formulas, constants, text templates, action
|
|
23
|
+
// inputs), which only Flow.Metadata carries. Every string in it is scanned.
|
|
24
|
+
const repo = new FlowRepository(ctx.soql, ctx.tooling);
|
|
25
|
+
const { versions } = FlowRepository.selectVersions(await repo.listDefinitions());
|
|
26
|
+
const hardcodedSecretFlows = [];
|
|
27
|
+
let unread = 0;
|
|
28
|
+
await mapWithConcurrency(versions, METADATA_CONCURRENCY, async (v) => {
|
|
29
|
+
let metadata;
|
|
30
|
+
try {
|
|
31
|
+
metadata = await repo.fetchMetadata(v.id);
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
unread++;
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
if (stringsIn(metadata).some((str) => SECRET_PATTERNS.some((p) => p.test(str)))) {
|
|
38
|
+
hardcodedSecretFlows.push(v);
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
hardcodedSecretFlows.sort((x, y) => x.apiName.localeCompare(y.apiName));
|
|
42
|
+
if (hardcodedSecretFlows.length > 0) {
|
|
43
|
+
findings.push({
|
|
44
|
+
id: 'flow-http-callout-hardcoded-secret',
|
|
45
|
+
category: this.category,
|
|
46
|
+
riskLevel: 'HIGH',
|
|
47
|
+
title: `${hardcodedSecretFlows.length} Flow(s) contain hardcoded credentials or API keys in callout logic`,
|
|
48
|
+
detail: 'Flow HTTP Callout actions or formulas contain embedded bearer tokens, API keys, or basic authentication credentials. Storing credentials directly in declarative Flows bypasses Apex static analysis and exposes secrets to anyone who can view or export Flow definitions.',
|
|
49
|
+
remediation: 'Replace all hardcoded secrets in Flow formulas and HTTP Callout headers with modern Named Credentials and External Credentials with encrypted auth headers.',
|
|
50
|
+
affectedItems: hardcodedSecretFlows.map((fl) => ({
|
|
51
|
+
label: fl.apiName,
|
|
52
|
+
url: `${baseUrl}/builder_platform_interaction/flowBuilder.app?flowId=${fl.id}`,
|
|
53
|
+
note: 'Contains embedded credential or API token',
|
|
54
|
+
})),
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
if (uncredentialedServices.length > 0) {
|
|
58
|
+
findings.push({
|
|
59
|
+
id: 'flow-http-callout-uncredentialed-endpoint',
|
|
60
|
+
category: this.category,
|
|
61
|
+
riskLevel: 'HIGH',
|
|
62
|
+
title: `${uncredentialedServices.length} External Service(s) configured without a Named Credential`,
|
|
63
|
+
detail: 'ExternalServiceRegistration records missing a designated Named Credential connect to remote endpoints without managed authentication and network controls, increasing exposure to rogue API endpoints and SSRF.',
|
|
64
|
+
remediation: 'Assign an approved Named Credential to every External Service Registration.',
|
|
65
|
+
affectedItems: uncredentialedServices.map((s) => ({
|
|
66
|
+
label: s.MasterLabel || s.DeveloperName,
|
|
67
|
+
url: `${baseUrl}/lightning/setup/ExternalServices/home`,
|
|
68
|
+
note: 'External Service lacks a Named Credential binding',
|
|
69
|
+
})),
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
if (unread > 0 && hardcodedSecretFlows.length === 0) {
|
|
73
|
+
findings.push({
|
|
74
|
+
id: 'flow-http-callout-inconclusive',
|
|
75
|
+
category: this.category,
|
|
76
|
+
riskLevel: 'INFO',
|
|
77
|
+
inconclusive: true,
|
|
78
|
+
title: `${unread} of ${versions.length} active Flow definition(s) could not be read`,
|
|
79
|
+
detail: 'Flow metadata could not be retrieved for some active flows, so they were not scanned for embedded credentials. The flows that were read contained none.',
|
|
80
|
+
remediation: 'Grant the audit user View Setup and Configuration and access to Flow metadata, then re-run.',
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
else if (hardcodedSecretFlows.length === 0 && uncredentialedServices.length === 0) {
|
|
84
|
+
findings.push({
|
|
85
|
+
id: 'flow-http-callout-ok',
|
|
86
|
+
category: this.category,
|
|
87
|
+
riskLevel: 'LOW',
|
|
88
|
+
passed: true,
|
|
89
|
+
title: 'Declarative Flow HTTP Callouts use proper Named Credentials without embedded secrets',
|
|
90
|
+
detail: 'External services and declarative flows were inspected; no hardcoded API keys or uncredentialed external service endpoints detected.',
|
|
91
|
+
remediation: 'Continue utilizing Named Credentials and External Credentials for all declarative HTTP integrations.',
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
return { findings };
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
/** Every string value anywhere in a parsed metadata tree. */
|
|
98
|
+
function stringsIn(node) {
|
|
99
|
+
if (typeof node === 'string')
|
|
100
|
+
return [node];
|
|
101
|
+
if (Array.isArray(node))
|
|
102
|
+
return node.flatMap(stringsIn);
|
|
103
|
+
if (node && typeof node === 'object')
|
|
104
|
+
return Object.values(node).flatMap(stringsIn);
|
|
105
|
+
return [];
|
|
106
|
+
}
|
|
107
|
+
async function mapWithConcurrency(items, limit, fn) {
|
|
108
|
+
let next = 0;
|
|
109
|
+
const worker = async () => {
|
|
110
|
+
while (next < items.length)
|
|
111
|
+
await fn(items[next++]);
|
|
112
|
+
};
|
|
113
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
|
114
|
+
}
|
|
115
|
+
//# sourceMappingURL=FlowHttpCalloutCredentialBypassCheck.js.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { AuditContext } from '@cclabsnz/sf-core';
|
|
2
|
+
import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
|
|
3
|
+
export declare class GenAiPromptTemplateGroundingCheck implements SecurityCheck {
|
|
4
|
+
readonly id = "genai-prompt-template-grounding";
|
|
5
|
+
readonly name = "GenAI Prompt Template Grounding & Context";
|
|
6
|
+
readonly category = "AI & Agents";
|
|
7
|
+
readonly description = "Inspects active GenAI Prompt Templates for grounding on System-Mode Flows or without-sharing Apex, and untrusted CRM input interpolation.";
|
|
8
|
+
run(ctx: AuditContext): Promise<CheckResult>;
|
|
9
|
+
}
|
|
10
|
+
//# sourceMappingURL=GenAiPromptTemplateGroundingCheck.d.ts.map
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
import { FlowRepository } from '@cclabsnz/sf-core';
|
|
2
|
+
import { isMissingObjectError } from '../support/missingObject.js';
|
|
3
|
+
// A template names its grounding sources explicitly: as a data provider definition
|
|
4
|
+
// (flow://Name, apex://Name) or as a merge field ({!$Flow:Name.Prompt}, {!$Apex:Name.Prompt}).
|
|
5
|
+
// Matching on those, rather than on a flow or class name appearing anywhere, keeps a template
|
|
6
|
+
// that merely mentions a common word from being tied to an unrelated flow.
|
|
7
|
+
const FLOW_REF = /(?:flow:\/\/|\$Flow:)([A-Za-z][A-Za-z0-9_]*)/gi;
|
|
8
|
+
const APEX_REF = /(?:apex:\/\/|\$Apex:)([A-Za-z][A-Za-z0-9_]*)/gi;
|
|
9
|
+
// Untrusted external text inputs that may carry prompt injections into prompt templates
|
|
10
|
+
const UNTRUSTED_FIELD_PATTERNS = [
|
|
11
|
+
/Lead\.Description/i,
|
|
12
|
+
/Case\.SuppliedName/i,
|
|
13
|
+
/Case\.Description/i,
|
|
14
|
+
/EmailMessage\.TextBody/i,
|
|
15
|
+
/EmailMessage\.HtmlBody/i,
|
|
16
|
+
];
|
|
17
|
+
// Privileged CRM fields that should not be colocated with untrusted external inputs in an unescaped prompt
|
|
18
|
+
const PRIVILEGED_DATA_PATTERNS = [
|
|
19
|
+
/Account\./i,
|
|
20
|
+
/Contact\./i,
|
|
21
|
+
/Opportunity\./i,
|
|
22
|
+
/User\./i,
|
|
23
|
+
];
|
|
24
|
+
export class GenAiPromptTemplateGroundingCheck {
|
|
25
|
+
id = 'genai-prompt-template-grounding';
|
|
26
|
+
name = 'GenAI Prompt Template Grounding & Context';
|
|
27
|
+
category = 'AI & Agents';
|
|
28
|
+
description = 'Inspects active GenAI Prompt Templates for grounding on System-Mode Flows or without-sharing Apex, and untrusted CRM input interpolation.';
|
|
29
|
+
async run(ctx) {
|
|
30
|
+
const findings = [];
|
|
31
|
+
const baseUrl = ctx.orgInfo.instanceUrl;
|
|
32
|
+
let templates;
|
|
33
|
+
try {
|
|
34
|
+
templates = await ctx.tooling.query('SELECT Id, DeveloperName, MasterLabel FROM GenAiPromptTemplate');
|
|
35
|
+
}
|
|
36
|
+
catch (err) {
|
|
37
|
+
if (!isMissingObjectError(err))
|
|
38
|
+
throw err;
|
|
39
|
+
findings.push({
|
|
40
|
+
id: 'genai-prompt-template-grounding-not-enabled',
|
|
41
|
+
category: this.category,
|
|
42
|
+
riskLevel: 'LOW',
|
|
43
|
+
passed: true,
|
|
44
|
+
title: 'GenAI Prompt Templates are not enabled or configured in this org',
|
|
45
|
+
detail: 'GenAiPromptTemplate object is not available; Prompt Builder / GenAI is not enabled.',
|
|
46
|
+
remediation: 'No action required if Generative AI Prompt Builder is not deployed.',
|
|
47
|
+
});
|
|
48
|
+
return { findings };
|
|
49
|
+
}
|
|
50
|
+
if (templates.length === 0) {
|
|
51
|
+
findings.push({
|
|
52
|
+
id: 'genai-prompt-template-grounding-ok',
|
|
53
|
+
category: this.category,
|
|
54
|
+
riskLevel: 'LOW',
|
|
55
|
+
passed: true,
|
|
56
|
+
title: 'No active GenAI Prompt Templates found in the org',
|
|
57
|
+
detail: 'Zero GenAiPromptTemplate records were returned.',
|
|
58
|
+
remediation: 'Review grounding sources whenever new Prompt Templates are created.',
|
|
59
|
+
});
|
|
60
|
+
return { findings };
|
|
61
|
+
}
|
|
62
|
+
// The template body, its inputs and its data providers exist only in the Metadata API
|
|
63
|
+
// definition. Without it nothing below can be judged, so the run says so.
|
|
64
|
+
const contentByTemplate = new Map();
|
|
65
|
+
let unread = 0;
|
|
66
|
+
for (const t of templates) {
|
|
67
|
+
let meta = null;
|
|
68
|
+
if (ctx.metadata) {
|
|
69
|
+
try {
|
|
70
|
+
meta = await ctx.metadata.read('GenAiPromptTemplate', t.DeveloperName);
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
meta = null;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (meta)
|
|
77
|
+
contentByTemplate.set(t, stringsIn(meta).join('\n'));
|
|
78
|
+
else
|
|
79
|
+
unread++;
|
|
80
|
+
}
|
|
81
|
+
const flowRefs = new Map();
|
|
82
|
+
const apexRefs = new Map();
|
|
83
|
+
for (const [t, content] of contentByTemplate) {
|
|
84
|
+
flowRefs.set(t, refs(content, FLOW_REF));
|
|
85
|
+
apexRefs.set(t, refs(content, APEX_REF));
|
|
86
|
+
}
|
|
87
|
+
// Run mode of each referenced active flow, keyed by API name (lower-cased).
|
|
88
|
+
const flowRunMode = new Map();
|
|
89
|
+
if ([...flowRefs.values()].some((r) => r.length > 0)) {
|
|
90
|
+
const repo = new FlowRepository(ctx.soql, ctx.tooling);
|
|
91
|
+
const [definitions, active] = await Promise.all([repo.listDefinitions(), repo.listActiveVersions()]);
|
|
92
|
+
const modeByVersion = new Map(active.map((v) => [v.id, v.runInMode]));
|
|
93
|
+
for (const d of definitions) {
|
|
94
|
+
if (d.activeVersionId && modeByVersion.has(d.activeVersionId)) {
|
|
95
|
+
flowRunMode.set(d.apiName.toLowerCase(), modeByVersion.get(d.activeVersionId) ?? null);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
const referencedClasses = [...new Set([...apexRefs.values()].flat())];
|
|
100
|
+
const withoutSharingClasses = new Set();
|
|
101
|
+
if (referencedClasses.length > 0) {
|
|
102
|
+
const names = referencedClasses.map((n) => `'${n}'`).join(', ');
|
|
103
|
+
const classes = await ctx.tooling.query(`SELECT Id, Name, Body FROM ApexClass WHERE Name IN (${names})`);
|
|
104
|
+
for (const cls of classes) {
|
|
105
|
+
if (declaredWithoutSharing(cls.Name, cls.Body ?? ''))
|
|
106
|
+
withoutSharingClasses.add(cls.Name.toLowerCase());
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
const systemModeFlowTemplates = [];
|
|
110
|
+
const withoutSharingApexTemplates = [];
|
|
111
|
+
const untrustedInputTemplates = [];
|
|
112
|
+
for (const [t, content] of contentByTemplate) {
|
|
113
|
+
// Only SystemModeWithoutSharing ignores the running user's record access. DefaultMode and
|
|
114
|
+
// SystemModeWithSharing both still apply sharing.
|
|
115
|
+
if ((flowRefs.get(t) ?? []).some((f) => flowRunMode.get(f) === 'SystemModeWithoutSharing')) {
|
|
116
|
+
systemModeFlowTemplates.push(t);
|
|
117
|
+
}
|
|
118
|
+
if ((apexRefs.get(t) ?? []).some((c) => withoutSharingClasses.has(c))) {
|
|
119
|
+
withoutSharingApexTemplates.push(t);
|
|
120
|
+
}
|
|
121
|
+
const hasUntrusted = UNTRUSTED_FIELD_PATTERNS.some((p) => p.test(content));
|
|
122
|
+
const hasPrivileged = PRIVILEGED_DATA_PATTERNS.some((p) => p.test(content));
|
|
123
|
+
if (hasUntrusted && hasPrivileged) {
|
|
124
|
+
untrustedInputTemplates.push(t);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
if (systemModeFlowTemplates.length > 0) {
|
|
128
|
+
findings.push({
|
|
129
|
+
id: 'genai-prompt-template-grounding-flow',
|
|
130
|
+
category: this.category,
|
|
131
|
+
riskLevel: 'HIGH',
|
|
132
|
+
title: `${systemModeFlowTemplates.length} Prompt Template(s) grounded on System-Mode Flow`,
|
|
133
|
+
detail: 'Prompt templates grounded on Flows executing in system context bypass the invoking user\'s record-level sharing, exposing records they cannot view directly.',
|
|
134
|
+
remediation: 'Set grounding Flows to run in user context ("Run in User Context" or SystemModeWithSharing) to enforce caller record visibility.',
|
|
135
|
+
affectedItems: systemModeFlowTemplates.map((t) => ({
|
|
136
|
+
label: t.MasterLabel || t.DeveloperName,
|
|
137
|
+
url: `${baseUrl}/lightning/setup/PromptTemplate/home`,
|
|
138
|
+
note: 'Template grounded on system-mode Flow',
|
|
139
|
+
})),
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
if (withoutSharingApexTemplates.length > 0) {
|
|
143
|
+
findings.push({
|
|
144
|
+
id: 'genai-prompt-template-grounding-apex',
|
|
145
|
+
category: this.category,
|
|
146
|
+
riskLevel: 'HIGH',
|
|
147
|
+
title: `${withoutSharingApexTemplates.length} Prompt Template(s) grounded on Apex running without sharing`,
|
|
148
|
+
detail: 'Invocable Apex grounding methods declared "without sharing" return unconstrained records, allowing prompt generation to extract CRM records outside the caller\'s access permissions.',
|
|
149
|
+
remediation: 'Declare grounding Apex classes with "inherited sharing" or "with sharing" to ensure record-level security is enforced during prompt resolution.',
|
|
150
|
+
affectedItems: withoutSharingApexTemplates.map((t) => ({
|
|
151
|
+
label: t.MasterLabel || t.DeveloperName,
|
|
152
|
+
url: `${baseUrl}/lightning/setup/PromptTemplate/home`,
|
|
153
|
+
note: 'Grounding Apex class runs without sharing',
|
|
154
|
+
})),
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
if (untrustedInputTemplates.length > 0) {
|
|
158
|
+
findings.push({
|
|
159
|
+
id: 'genai-prompt-template-grounding-untrusted',
|
|
160
|
+
category: this.category,
|
|
161
|
+
riskLevel: 'HIGH',
|
|
162
|
+
title: `${untrustedInputTemplates.length} Prompt Template(s) interpolate untrusted fields with privileged CRM data`,
|
|
163
|
+
detail: 'Templates interpolating external text fields (e.g. Lead.Description, Case.SuppliedName) alongside sensitive CRM objects allow attackers to inject prompts that extract or manipulate adjacent data.',
|
|
164
|
+
remediation: 'Separate prompt templates processing untrusted external text from those retrieving privileged internal records, and apply input sanitization guardrails.',
|
|
165
|
+
affectedItems: untrustedInputTemplates.map((t) => ({
|
|
166
|
+
label: t.MasterLabel || t.DeveloperName,
|
|
167
|
+
url: `${baseUrl}/lightning/setup/PromptTemplate/home`,
|
|
168
|
+
note: 'Untrusted input combined with privileged context',
|
|
169
|
+
})),
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
const anyFinding = systemModeFlowTemplates.length > 0 || withoutSharingApexTemplates.length > 0 || untrustedInputTemplates.length > 0;
|
|
173
|
+
if (unread > 0) {
|
|
174
|
+
findings.push({
|
|
175
|
+
id: 'genai-prompt-template-grounding-inconclusive',
|
|
176
|
+
category: this.category,
|
|
177
|
+
riskLevel: 'INFO',
|
|
178
|
+
inconclusive: true,
|
|
179
|
+
title: `${unread} of ${templates.length} Prompt Template definition(s) could not be read`,
|
|
180
|
+
detail: 'A prompt template\'s body, inputs and grounding sources are only in its Metadata API definition. Templates that could not be read were not evaluated for system-mode grounding or untrusted input.',
|
|
181
|
+
remediation: 'Run the audit with a user that can read Prompt Builder metadata (Customize Application or View Setup and Configuration), then re-run.',
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
else if (!anyFinding) {
|
|
185
|
+
findings.push({
|
|
186
|
+
id: 'genai-prompt-template-grounding-ok',
|
|
187
|
+
category: this.category,
|
|
188
|
+
riskLevel: 'LOW',
|
|
189
|
+
passed: true,
|
|
190
|
+
title: 'All evaluated Prompt Templates use safe grounding sources',
|
|
191
|
+
detail: `${templates.length} Prompt Template(s) inspected with no unconstrained system-mode or without-sharing grounding detected.`,
|
|
192
|
+
remediation: 'Continue enforcing user-context execution for all prompt template grounding sources.',
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
return { findings };
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
function refs(content, pattern) {
|
|
199
|
+
return [...new Set([...content.matchAll(pattern)].map((m) => m[1].toLowerCase()))];
|
|
200
|
+
}
|
|
201
|
+
/** Every string value anywhere in a parsed metadata tree. */
|
|
202
|
+
function stringsIn(node) {
|
|
203
|
+
if (typeof node === 'string')
|
|
204
|
+
return [node];
|
|
205
|
+
if (Array.isArray(node))
|
|
206
|
+
return node.flatMap(stringsIn);
|
|
207
|
+
if (node && typeof node === 'object')
|
|
208
|
+
return Object.values(node).flatMap(stringsIn);
|
|
209
|
+
return [];
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Whether the declaration of `className` in `body` carries `without sharing`. Literal patterns
|
|
213
|
+
* only, in one linear pass: the name comes from the org, so it never becomes part of a regex.
|
|
214
|
+
*/
|
|
215
|
+
function declaredWithoutSharing(className, body) {
|
|
216
|
+
const target = className.toLowerCase();
|
|
217
|
+
const declaration = /\bclass\s+(\w+)/gi;
|
|
218
|
+
for (let m = declaration.exec(body); m !== null; m = declaration.exec(body)) {
|
|
219
|
+
if (m[1].toLowerCase() !== target)
|
|
220
|
+
continue;
|
|
221
|
+
// The modifiers sit between the previous statement or block boundary and `class`.
|
|
222
|
+
const start = Math.max(body.lastIndexOf(';', m.index), body.lastIndexOf('{', m.index), body.lastIndexOf('}', m.index)) + 1;
|
|
223
|
+
return /\bwithout\s+sharing\b/i.test(body.slice(start, m.index));
|
|
224
|
+
}
|
|
225
|
+
return false;
|
|
226
|
+
}
|
|
227
|
+
//# sourceMappingURL=GenAiPromptTemplateGroundingCheck.js.map
|
|
@@ -4,7 +4,7 @@ export declare class GuestExecutableApexCheck implements SecurityCheck {
|
|
|
4
4
|
readonly id = "guest-executable-apex";
|
|
5
5
|
readonly name = "Guest-Executable Apex";
|
|
6
6
|
readonly category = "Access Control";
|
|
7
|
-
readonly description = "Finds Apex classes that unauthenticated guest profiles can execute, flagging those that run without sharing
|
|
7
|
+
readonly description = "Finds Apex classes that unauthenticated guest profiles can execute, flagging those that run without sharing, call a without-sharing helper, or switch off CRUD/FLS with SYSTEM_MODE";
|
|
8
8
|
readonly dependsOnCache: readonly ['apexBodies'];
|
|
9
9
|
run(ctx: AuditContext): Promise<CheckResult>;
|
|
10
10
|
}
|
|
@@ -1,11 +1,27 @@
|
|
|
1
1
|
import { ApexRepository } from '@cclabsnz/sf-core';
|
|
2
|
-
|
|
3
|
-
|
|
2
|
+
import { declaresWithoutSharing, effectiveSharing, parentClass, usesSystemMode } from '../support/apexAccess.js';
|
|
3
|
+
/**
|
|
4
|
+
* The org-local classes a class calls, as its compiled SymbolTable records them. A reference with a
|
|
5
|
+
* namespace is to packaged code, which the audit does not read, so it never resolves to a local
|
|
6
|
+
* class that happens to share its name.
|
|
7
|
+
*/
|
|
8
|
+
function referencedClasses(symbolTable) {
|
|
9
|
+
const refs = symbolTable
|
|
10
|
+
?.externalReferences;
|
|
11
|
+
if (!Array.isArray(refs))
|
|
12
|
+
return [];
|
|
13
|
+
return refs
|
|
14
|
+
.filter((r) => !(typeof r?.namespace === 'string' && r.namespace !== ''))
|
|
15
|
+
.map((r) => r?.name)
|
|
16
|
+
.filter((n) => typeof n === 'string' && n !== '')
|
|
17
|
+
// An inner class is referenced as Outer.Inner; its code lives in the outer class's body.
|
|
18
|
+
.map((n) => n.split('.')[0]);
|
|
19
|
+
}
|
|
4
20
|
export class GuestExecutableApexCheck {
|
|
5
21
|
id = 'guest-executable-apex';
|
|
6
22
|
name = 'Guest-Executable Apex';
|
|
7
23
|
category = 'Access Control';
|
|
8
|
-
description = 'Finds Apex classes that unauthenticated guest profiles can execute, flagging those that run without sharing
|
|
24
|
+
description = 'Finds Apex classes that unauthenticated guest profiles can execute, flagging those that run without sharing, call a without-sharing helper, or switch off CRUD/FLS with SYSTEM_MODE';
|
|
9
25
|
// Use cached Apex bodies (from HardcodedCredentialsCheck) when available to classify sharing.
|
|
10
26
|
dependsOnCache = ['apexBodies'];
|
|
11
27
|
async run(ctx) {
|
|
@@ -45,18 +61,75 @@ export class GuestExecutableApexCheck {
|
|
|
45
61
|
// fails the whole query with "invalid ID field", losing every good row with it.
|
|
46
62
|
const nameById = await new ApexRepository(ctx.tooling).namesByIds(classIds);
|
|
47
63
|
const bodies = ctx.cache.apexBodies ?? [];
|
|
48
|
-
|
|
64
|
+
// Apex names are case-insensitive, and a SymbolTable may spell one differently from its declaration.
|
|
65
|
+
const byName = new Map(bodies.map((b) => [b.name.toLowerCase(), b]));
|
|
66
|
+
/**
|
|
67
|
+
* Everything reachable from `start` through SymbolTable references: whichever class is declared
|
|
68
|
+
* without sharing, at any depth, runs its own code without sharing (spec RULE-004), and SYSTEM_MODE
|
|
69
|
+
* anywhere on the path lifts CRUD/FLS for the guest (RULE-003).
|
|
70
|
+
*/
|
|
71
|
+
const bodyOf = (n) => byName.get(n.toLowerCase())?.body;
|
|
72
|
+
// A class reaches what its SymbolTable references, and the class it extends: inherited methods
|
|
73
|
+
// run with the parent's own sharing.
|
|
74
|
+
const neighbours = (n) => {
|
|
75
|
+
const entry = byName.get(n.toLowerCase());
|
|
76
|
+
const parent = entry?.body ? parentClass(n, entry.body) : undefined;
|
|
77
|
+
return [...referencedClasses(entry?.symbolTable), ...(parent ? [parent] : [])];
|
|
78
|
+
};
|
|
79
|
+
const reach = (start) => {
|
|
80
|
+
const seen = new Set([start.toLowerCase()]);
|
|
81
|
+
const queue = neighbours(start);
|
|
82
|
+
let systemModeAt;
|
|
83
|
+
while (queue.length > 0) {
|
|
84
|
+
const ref = queue.shift();
|
|
85
|
+
if (seen.has(ref.toLowerCase()))
|
|
86
|
+
continue;
|
|
87
|
+
seen.add(ref.toLowerCase());
|
|
88
|
+
const helper = byName.get(ref.toLowerCase());
|
|
89
|
+
if (!helper?.body)
|
|
90
|
+
continue;
|
|
91
|
+
if (declaresWithoutSharing(helper.body))
|
|
92
|
+
return { withoutSharing: helper.name };
|
|
93
|
+
if (!systemModeAt && usesSystemMode(helper.body))
|
|
94
|
+
systemModeAt = helper.name;
|
|
95
|
+
queue.push(...neighbours(helper.name));
|
|
96
|
+
}
|
|
97
|
+
return { systemMode: systemModeAt };
|
|
98
|
+
};
|
|
99
|
+
// spec/apex-access-mode.md. A guest call is an entry point: no keyword means without sharing,
|
|
100
|
+
// and inherited sharing means with sharing. SYSTEM_MODE bypasses CRUD/FLS only (RULE-003); a
|
|
101
|
+
// helper declared without sharing bypasses sharing for whatever it does (RULE-004).
|
|
49
102
|
const unprotected = [];
|
|
103
|
+
const systemMode = [];
|
|
50
104
|
const exposed = [];
|
|
51
105
|
for (const id of classIds) {
|
|
52
106
|
const name = nameById.get(id) ?? id;
|
|
53
|
-
const
|
|
54
|
-
|
|
55
|
-
|
|
107
|
+
const entry = byName.get(name.toLowerCase());
|
|
108
|
+
const body = entry?.body;
|
|
109
|
+
// A class with no keyword takes the sharing of the class it extends (spec MN-001).
|
|
110
|
+
const keyword = body ? effectiveSharing(name, body, bodyOf) : null;
|
|
111
|
+
if (keyword === 'without' || (keyword !== null && body && declaresWithoutSharing(body))) {
|
|
112
|
+
unprotected.push({
|
|
113
|
+
name,
|
|
114
|
+
note: keyword === 'without' ? 'Declared "without sharing": fix immediately' : 'Contains an inner class declared "without sharing"',
|
|
115
|
+
});
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
if (keyword === 'none') {
|
|
119
|
+
unprotected.push({ name, note: 'No sharing declaration: runs without sharing when a guest calls it' });
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
if (keyword === null || !body) {
|
|
123
|
+
// No readable body (managed or hidden): its sharing cannot be judged.
|
|
124
|
+
exposed.push(name);
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
const path = reach(name);
|
|
128
|
+
if (path.withoutSharing) {
|
|
129
|
+
unprotected.push({ name, note: `Reaches "${path.withoutSharing}", which is declared "without sharing"` });
|
|
56
130
|
}
|
|
57
|
-
else if (body
|
|
58
|
-
|
|
59
|
-
unprotected.push(name);
|
|
131
|
+
else if (usesSystemMode(body) || path.systemMode) {
|
|
132
|
+
systemMode.push({ name, via: usesSystemMode(body) ? undefined : path.systemMode });
|
|
60
133
|
}
|
|
61
134
|
else {
|
|
62
135
|
exposed.push(name);
|
|
@@ -68,12 +141,30 @@ export class GuestExecutableApexCheck {
|
|
|
68
141
|
id: 'guest-executable-apex-unprotected',
|
|
69
142
|
category: this.category,
|
|
70
143
|
riskLevel: 'CRITICAL',
|
|
71
|
-
title: `${unprotected.length} guest-executable Apex class(es) run without
|
|
72
|
-
detail: 'These Apex classes can be invoked by unauthenticated guest users AND do not enforce record-level sharing
|
|
144
|
+
title: `${unprotected.length} guest-executable Apex class(es) run without sharing, directly or through a helper`,
|
|
145
|
+
detail: 'These Apex classes can be invoked by unauthenticated guest users AND do not enforce record-level sharing, ' +
|
|
146
|
+
'either themselves or in a helper class they call that is declared "without sharing". ' +
|
|
73
147
|
'This is the classic Salesforce guest-user exploit chain: an attacker calls the class and reads or writes ' +
|
|
74
148
|
'business data in bulk with no login. Object-level guest permissions do not mitigate this: the class runs in system context.',
|
|
75
|
-
remediation: 'Add "with sharing" to every guest-reachable Apex class, enforce CRUD/FLS, and remove guest execution access from any class that does not strictly need it.',
|
|
76
|
-
affectedItems: unprotected.map((
|
|
149
|
+
remediation: 'Add "with sharing" to every guest-reachable Apex class and to every helper it calls, enforce CRUD/FLS, and remove guest execution access from any class that does not strictly need it.',
|
|
150
|
+
affectedItems: unprotected.map((u) => ({ label: u.name, url: apexUrl, note: u.note })),
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
if (systemMode.length > 0) {
|
|
154
|
+
findings.push({
|
|
155
|
+
id: 'guest-executable-apex-system-mode',
|
|
156
|
+
category: this.category,
|
|
157
|
+
riskLevel: 'HIGH',
|
|
158
|
+
title: `${systemMode.length} guest-executable Apex class(es) switch off CRUD/FLS with SYSTEM_MODE`,
|
|
159
|
+
detail: 'Guest users can execute these classes, which enforce sharing but run queries or DML with WITH SYSTEM_MODE or ' +
|
|
160
|
+
'AccessLevel.SYSTEM_MODE. Sharing still limits which records a guest reaches, but not which objects and fields: ' +
|
|
161
|
+
'a guest can read or change fields the guest profile is denied on any record shared with guests.',
|
|
162
|
+
remediation: 'Replace SYSTEM_MODE with USER_MODE in guest-reachable code, or strip fields with Security.stripInaccessible() before returning results. Remove guest access where unnecessary.',
|
|
163
|
+
affectedItems: systemMode.map(({ name, via }) => ({
|
|
164
|
+
label: name,
|
|
165
|
+
url: apexUrl,
|
|
166
|
+
note: via ? `Calls "${via}", which uses SYSTEM_MODE: guest CRUD/FLS not enforced` : 'SYSTEM_MODE: guest CRUD/FLS not enforced',
|
|
167
|
+
})),
|
|
77
168
|
});
|
|
78
169
|
}
|
|
79
170
|
if (exposed.length > 0) {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { apexCode } from '../support/apexAccess.js';
|
|
1
2
|
import { ApexRepository } from '@cclabsnz/sf-core';
|
|
2
3
|
const HIGH_RISK_PATTERNS = [
|
|
3
4
|
/Bearer\s+[A-Za-z0-9\-_.~+/]{20,}=*/gi, // Bearer tokens (min length to avoid test stubs)
|
|
@@ -38,10 +39,14 @@ export class HardcodedCredentialsCheck {
|
|
|
38
39
|
Body: c.body ?? '',
|
|
39
40
|
LengthWithoutComments: (c.body ?? '').length,
|
|
40
41
|
NamespacePrefix: c.namespace,
|
|
42
|
+
SymbolTable: c.symbolTable,
|
|
41
43
|
}));
|
|
42
44
|
// Cache apex bodies for downstream checks — exclude test classes and filter null bodies
|
|
43
|
-
|
|
44
|
-
|
|
45
|
+
// @IsTest is read from code only: a production helper mentioning it in a comment must still
|
|
46
|
+
// reach the cache, or the checks that follow calls into it never see its sharing (spec MN-002).
|
|
47
|
+
const nonTestRecords = records.filter((r) => !IS_TEST_CLASS.test(apexCode(r.Body ?? '')));
|
|
48
|
+
// The SymbolTable travels with the body so GuestExecutableApexCheck can follow calls into helpers.
|
|
49
|
+
ctx.cache.apexBodies = nonTestRecords.map((r) => ({ name: r.Name, body: r.Body ?? '', symbolTable: r.SymbolTable }));
|
|
45
50
|
const namedCredentialEndpoints = (ctx.cache.namedCredentialEndpoints ?? []).filter(Boolean);
|
|
46
51
|
const remoteSiteUrls = (ctx.cache.remoteSiteUrls ?? []).filter(Boolean);
|
|
47
52
|
const classesWithCredentials = [];
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { AuditContext } from '@cclabsnz/sf-core';
|
|
2
|
+
import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
|
|
3
|
+
export declare class InboundEmailHandlerExposureCheck implements SecurityCheck {
|
|
4
|
+
readonly id = "inbound-email-handler-exposure";
|
|
5
|
+
readonly name = "Inbound Email Handler Unauthenticated Execution";
|
|
6
|
+
readonly category = "External Connectivity";
|
|
7
|
+
readonly description = "Detects active inbound email services open to all senders without SPF/DKIM verification executing Apex under privileged users.";
|
|
8
|
+
run(ctx: AuditContext): Promise<CheckResult>;
|
|
9
|
+
}
|
|
10
|
+
//# sourceMappingURL=InboundEmailHandlerExposureCheck.d.ts.map
|