@cclabsnz/sf-audit 1.16.0 → 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 +118 -1
- package/README.md +94 -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 +95 -7
- package/lib/checks/CheckEngine.d.ts +3 -1
- package/lib/checks/CheckEngine.js +11 -3
- 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 +30 -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 +28 -7
- package/lib/findings/AuditResult.d.ts +8 -0
- package/lib/findings/CheckMeta.js +15 -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,98 @@
|
|
|
1
|
+
export class DelegatedAuthenticationExposureCheck {
|
|
2
|
+
id = 'delegated-authentication-exposure';
|
|
3
|
+
name = 'Delegated Authentication Exposure';
|
|
4
|
+
category = 'Identity & Access';
|
|
5
|
+
description = 'Flags Delegated Authentication enabled over non-mTLS endpoints or assigned to System Administrator profiles.';
|
|
6
|
+
async run(ctx) {
|
|
7
|
+
const findings = [];
|
|
8
|
+
const baseUrl = ctx.orgInfo.instanceUrl;
|
|
9
|
+
const ssoUrl = `${baseUrl}/lightning/setup/SingleSignOn/home`;
|
|
10
|
+
// Enabled, disabled, or unknown. Only a boolean actually returned by the settings read
|
|
11
|
+
// decides; a failed read or an absent Metadata client leaves it unknown, never "disabled".
|
|
12
|
+
let delegatedAuth;
|
|
13
|
+
let gatewayUrl = '';
|
|
14
|
+
if (ctx.metadata) {
|
|
15
|
+
try {
|
|
16
|
+
const sec = await ctx.metadata.read('SecuritySettings', 'Security');
|
|
17
|
+
const sso = sec?.singleSignOnSettings;
|
|
18
|
+
if (typeof sso?.isDelegatedAuthEnabled === 'boolean') {
|
|
19
|
+
delegatedAuth = sso.isDelegatedAuthEnabled;
|
|
20
|
+
gatewayUrl = sso.delegatedGatewayUrl ?? '';
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
delegatedAuth = undefined;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
const isDelegatedAuthEnabled = delegatedAuth === true;
|
|
28
|
+
const profiles = await ctx.soql.queryAll('SELECT Id, Name, PermissionsIsSingleSignOnEnabled FROM Profile WHERE PermissionsIsSingleSignOnEnabled = true');
|
|
29
|
+
const adminProfilesWithDelegatedAuth = profiles.filter((p) => p.Name.toLowerCase().includes('admin') || p.Name === 'System Administrator');
|
|
30
|
+
if (isDelegatedAuthEnabled) {
|
|
31
|
+
// Check 1: Insecure Gateway URL (non-https or cleartext)
|
|
32
|
+
const isInsecure = !gatewayUrl ||
|
|
33
|
+
gatewayUrl.startsWith('http://') ||
|
|
34
|
+
(!gatewayUrl.startsWith('https://') && gatewayUrl.length > 0);
|
|
35
|
+
if (isInsecure) {
|
|
36
|
+
findings.push({
|
|
37
|
+
id: 'delegated-authentication-insecure-gateway',
|
|
38
|
+
category: this.category,
|
|
39
|
+
riskLevel: 'CRITICAL',
|
|
40
|
+
title: 'Delegated Authentication gateway is unencrypted or missing mutual TLS',
|
|
41
|
+
detail: `Delegated Authentication is enabled with gateway URL "${gatewayUrl || 'empty'}". Unlike SAML or OIDC, Delegated Authentication relies on a simple SOAP boolean response without cryptographic assertion signatures. Transmitting credentials over unencrypted or unauthenticated endpoints allows credential harvesting and spoofed responses.`,
|
|
42
|
+
remediation: 'Configure a secure HTTPS endpoint with mutual TLS (mTLS) client certificate verification for the Delegated Authentication gateway, or migrate to SAML 2.0 / OpenID Connect.',
|
|
43
|
+
affectedItems: [
|
|
44
|
+
{
|
|
45
|
+
label: 'Delegated Gateway Endpoint',
|
|
46
|
+
url: ssoUrl,
|
|
47
|
+
note: `Gateway URL: ${gatewayUrl || 'None configured'}`,
|
|
48
|
+
},
|
|
49
|
+
],
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
// Check 2: Assigned to System Administrators
|
|
53
|
+
if (adminProfilesWithDelegatedAuth.length > 0) {
|
|
54
|
+
findings.push({
|
|
55
|
+
id: 'delegated-authentication-admin-assigned',
|
|
56
|
+
category: this.category,
|
|
57
|
+
riskLevel: 'CRITICAL',
|
|
58
|
+
title: `Delegated Authentication is assigned to ${adminProfilesWithDelegatedAuth.length} Administrator profile(s)`,
|
|
59
|
+
detail: 'The "Is Single Sign-On Enabled" permission routes user authentication through the external delegated gateway. When assigned to System Administrators, compromising or spoofing the delegated gateway grants instantaneous full org takeover as an admin.',
|
|
60
|
+
remediation: 'Remove "Is Single Sign-On Enabled" from System Administrator and privileged profiles. Reserve Delegated Authentication strictly for standard users, or enforce SAML/OIDC.',
|
|
61
|
+
affectedItems: adminProfilesWithDelegatedAuth.map((p) => ({
|
|
62
|
+
label: p.Name,
|
|
63
|
+
url: `${baseUrl}/lightning/setup/EnhancedProfiles/page?address=%2F${p.Id}`,
|
|
64
|
+
note: 'Admin profile routes authentication through delegated gateway',
|
|
65
|
+
})),
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
if (delegatedAuth === undefined) {
|
|
70
|
+
findings.push({
|
|
71
|
+
id: 'delegated-authentication-advisory',
|
|
72
|
+
category: this.category,
|
|
73
|
+
riskLevel: 'INFO',
|
|
74
|
+
title: 'Verify Delegated Authentication settings manually',
|
|
75
|
+
detail: `This run could not read SecuritySettings, so whether Delegated Authentication is enabled is unknown. ${adminProfilesWithDelegatedAuth.length} administrator profile(s) hold "Is Single Sign-On Enabled", which routes their sign-in through the delegated gateway if it is on.`,
|
|
76
|
+
remediation: 'In Setup → Single Sign-On Settings, check whether Delegated Authentication is enabled. If it is, the gateway must be HTTPS with mutual TLS, and administrator profiles should not hold "Is Single Sign-On Enabled".',
|
|
77
|
+
affectedItems: [{ label: 'Single Sign-On Settings', url: ssoUrl }],
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
else if (findings.length === 0) {
|
|
81
|
+
findings.push({
|
|
82
|
+
id: 'delegated-authentication-exposure-ok',
|
|
83
|
+
category: this.category,
|
|
84
|
+
riskLevel: 'LOW',
|
|
85
|
+
passed: true,
|
|
86
|
+
title: isDelegatedAuthEnabled
|
|
87
|
+
? 'Delegated Authentication uses an HTTPS gateway and is not assigned to administrators'
|
|
88
|
+
: 'Delegated Authentication is disabled',
|
|
89
|
+
detail: isDelegatedAuthEnabled
|
|
90
|
+
? 'SecuritySettings shows Delegated Authentication enabled with an HTTPS gateway, and no administrator profile holds "Is Single Sign-On Enabled".'
|
|
91
|
+
: 'SecuritySettings confirms Delegated Authentication is disabled, so no sign-in is routed through an external gateway.',
|
|
92
|
+
remediation: 'Continue using SAML 2.0 or OpenID Connect with signed assertions for SSO.',
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
return { findings };
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
//# sourceMappingURL=DelegatedAuthenticationExposureCheck.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 ExternalAccountHierarchyExposureCheck implements SecurityCheck {
|
|
4
|
+
readonly id = "external-account-hierarchy-exposure";
|
|
5
|
+
readonly name = "External Account Hierarchy & Partner Super User Exposure";
|
|
6
|
+
readonly category = "External-Facing Access";
|
|
7
|
+
readonly description = "Flags Partner Super User access and External Account Hierarchies that bypass external OWD and widen portal visibility.";
|
|
8
|
+
run(ctx: AuditContext): Promise<CheckResult>;
|
|
9
|
+
}
|
|
10
|
+
//# sourceMappingURL=ExternalAccountHierarchyExposureCheck.d.ts.map
|
|
@@ -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
|
}
|