@cclabsnz/sf-audit 1.16.0 → 1.18.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 +172 -1
- package/PERMISSIONS.md +139 -0
- package/README.md +98 -26
- package/config/scoring.sample.json +104 -5
- package/docs/permissionset/SF_Audit_ReadOnly.permissionset-meta.xml +54 -0
- 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/ChainEngine.js +11 -1
- package/lib/chains/namedChains.js +130 -24
- package/lib/checks/CheckEngine.d.ts +3 -1
- package/lib/checks/CheckEngine.js +65 -26
- package/lib/checks/impl/AgentUserPrivilegeCheck.js +5 -4
- package/lib/checks/impl/AnonymousApexAuditCheck.js +41 -8
- package/lib/checks/impl/ApexCrudFLSCheck.js +45 -10
- package/lib/checks/impl/ApexSharingCheck.js +19 -26
- package/lib/checks/impl/ApiClientPermissionCheck.js +21 -5
- package/lib/checks/impl/AuditTrailCheck.js +23 -8
- package/lib/checks/impl/AuthProviderRegistrationHandlerCheck.d.ts +10 -0
- package/lib/checks/impl/AuthProviderRegistrationHandlerCheck.js +131 -0
- package/lib/checks/impl/CertificateExpiryCheck.js +2 -1
- package/lib/checks/impl/ConnectedAppScopeCheck.js +61 -5
- package/lib/checks/impl/ConnectedAppsCheck.js +60 -5
- package/lib/checks/impl/ContentLinksCheck.js +33 -9
- package/lib/checks/impl/CorsAllowlistCheck.js +3 -2
- package/lib/checks/impl/DataClassificationCheck.js +15 -13
- package/lib/checks/impl/DataCloudDataSpaceIsolationCheck.d.ts +10 -0
- package/lib/checks/impl/DataCloudDataSpaceIsolationCheck.js +116 -0
- package/lib/checks/impl/DebugLogAccessCheck.js +4 -4
- package/lib/checks/impl/DelegatedAdministrationGroupsCheck.d.ts +10 -0
- package/lib/checks/impl/DelegatedAdministrationGroupsCheck.js +76 -0
- package/lib/checks/impl/DelegatedAuthenticationExposureCheck.d.ts +10 -0
- package/lib/checks/impl/DelegatedAuthenticationExposureCheck.js +105 -0
- package/lib/checks/impl/DeploymentIdentityCheck.js +32 -5
- package/lib/checks/impl/EmailSecurityCheck.d.ts +1 -1
- package/lib/checks/impl/EmailSecurityCheck.js +14 -34
- package/lib/checks/impl/EncryptionCoverageCheck.js +21 -15
- package/lib/checks/impl/EnhancedDomainsCheck.js +17 -2
- package/lib/checks/impl/EscalationPermsCheck.d.ts +2 -0
- package/lib/checks/impl/EscalationPermsCheck.js +88 -21
- package/lib/checks/impl/ExperienceCloudSiteCheck.js +56 -5
- package/lib/checks/impl/ExternalAccountHierarchyExposureCheck.d.ts +10 -0
- package/lib/checks/impl/ExternalAccountHierarchyExposureCheck.js +65 -0
- package/lib/checks/impl/ExternalCredentialsCheck.js +6 -3
- package/lib/checks/impl/FailedLoginCheck.js +36 -9
- package/lib/checks/impl/FieldHistoryTrackingCheck.js +14 -11
- 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/GuestRecordAccessPolicyCheck.js +52 -11
- package/lib/checks/impl/HardcodedCredentialsCheck.js +7 -2
- package/lib/checks/impl/HealthCheckCheck.js +1 -0
- package/lib/checks/impl/HighAssuranceSessionCheck.js +16 -11
- package/lib/checks/impl/InactiveUsersCheck.js +1 -1
- package/lib/checks/impl/InboundEmailHandlerExposureCheck.d.ts +10 -0
- package/lib/checks/impl/InboundEmailHandlerExposureCheck.js +136 -0
- package/lib/checks/impl/IntegrationLeastPrivilegeCheck.js +7 -6
- package/lib/checks/impl/InternalUserMfaCheck.js +26 -8
- package/lib/checks/impl/IpRestrictionsCheck.js +35 -16
- package/lib/checks/impl/LoginAccessPolicyCheck.js +5 -4
- package/lib/checks/impl/LoginAnomalyCheck.js +10 -7
- package/lib/checks/impl/LoginSessionCheck.js +2 -0
- package/lib/checks/impl/MfaEnforcementCheck.js +23 -6
- package/lib/checks/impl/MfaMethodStrengthCheck.js +18 -3
- package/lib/checks/impl/MfaRegistrationCheck.js +4 -3
- package/lib/checks/impl/MyDomainLoginPolicyCheck.js +23 -10
- 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/OutboundMessagesCheck.js +48 -6
- 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 +88 -0
- package/lib/checks/impl/PrivilegedAccessCheck.js +12 -5
- package/lib/checks/impl/ReleaseUpdatesCheck.js +18 -3
- package/lib/checks/impl/RemoteSitesCheck.js +4 -4
- package/lib/checks/impl/RestrictionRulesIntegrityCheck.d.ts +10 -0
- package/lib/checks/impl/RestrictionRulesIntegrityCheck.js +105 -0
- package/lib/checks/impl/SeparationOfDutiesCheck.js +14 -3
- package/lib/checks/impl/ShieldTenantSecretLifecycleCheck.d.ts +10 -0
- package/lib/checks/impl/ShieldTenantSecretLifecycleCheck.js +90 -0
- package/lib/checks/impl/SoapLoginApiAuthCheck.js +20 -8
- package/lib/checks/impl/SsoEnforcementCheck.js +16 -5
- package/lib/checks/impl/TransactionSecurityPolicyCheck.js +5 -5
- package/lib/checks/impl/TrustedIPRangesCheck.js +18 -9
- package/lib/checks/impl/UsersAndAdminsCheck.js +24 -4
- package/lib/checks/permCatalog.js +1 -1
- 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 +37 -0
- package/lib/checks/support/schema.d.ts +17 -0
- package/lib/checks/support/schema.js +41 -0
- package/lib/commands/audit/apps.d.ts +1 -0
- package/lib/commands/audit/apps.js +86 -30
- package/lib/commands/audit/diff.js +2 -2
- package/lib/commands/audit/events/pull.js +3 -1
- package/lib/commands/audit/history.js +2 -2
- package/lib/commands/audit/incident/collect.js +3 -1
- package/lib/commands/audit/incident/report.js +2 -2
- package/lib/commands/audit/security.d.ts +3 -0
- package/lib/commands/audit/security.js +65 -10
- package/lib/commands/audit/timeline.js +2 -2
- package/lib/compliance/mapping.js +28 -7
- package/lib/findings/AuditResult.d.ts +10 -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 +34 -0
- package/lib/findings/coverage.js +42 -0
- package/lib/findings/exitCode.js +1 -1
- package/lib/findings/loadScoringConfig.js +51 -8
- package/lib/findings/scoring.js +61 -10
- 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/preflight/permissionMap.d.ts +2 -20
- package/lib/preflight/permissionMap.js +2 -43
- package/lib/preflight/permissions.d.ts +25 -0
- package/lib/preflight/permissions.js +50 -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 +23 -6
- package/lib/renderers/MarkdownRenderer.js +11 -1
- 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.d.ts +5 -1
- package/lib/report/RemediationRoadmap.js +6 -2
- 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 +6 -4
|
@@ -1,3 +1,9 @@
|
|
|
1
|
+
// LoginHistory has no IsSuccess field, and Status cannot be filtered (not in WHERE, not in
|
|
2
|
+
// HAVING). It can be grouped, so failures are counted by grouping on Status and dropping the
|
|
3
|
+
// 'Success' group in code.
|
|
4
|
+
const SUCCESS = 'Success';
|
|
5
|
+
// An aggregate query returns at most 2,000 groups and cannot be paged.
|
|
6
|
+
const MAX_GROUPS = 2000;
|
|
1
7
|
// Thresholds for brute-force / credential stuffing detection (7-day window)
|
|
2
8
|
const BRUTE_FORCE_PER_USER = 20; // >20 failures for one user = targeted attack
|
|
3
9
|
const BULK_THRESHOLD_PER_USER = 50; // >50 = highly likely automated attack
|
|
@@ -14,17 +20,18 @@ export class FailedLoginCheck {
|
|
|
14
20
|
// Query 1: total failed logins in last 7 days
|
|
15
21
|
let totalFailures = 0;
|
|
16
22
|
try {
|
|
17
|
-
const
|
|
18
|
-
totalFailures =
|
|
23
|
+
const byStatus = await ctx.soql.query(`SELECT Status, COUNT(Id) FROM LoginHistory WHERE LoginTime > LAST_N_DAYS:7 GROUP BY Status`);
|
|
24
|
+
totalFailures = byStatus.records.filter((r) => r.Status !== SUCCESS).reduce((n, r) => n + r.expr0, 0);
|
|
19
25
|
}
|
|
20
|
-
catch {
|
|
26
|
+
catch (err) {
|
|
21
27
|
findings.push({
|
|
22
28
|
id: 'failed-login-inaccessible',
|
|
23
29
|
category: this.category,
|
|
24
30
|
riskLevel: 'INFO',
|
|
25
31
|
inconclusive: true,
|
|
26
32
|
title: 'LoginHistory could not be queried: failed login analysis skipped',
|
|
27
|
-
detail:
|
|
33
|
+
detail: `The LoginHistory query failed: ${err instanceof Error ? err.message : String(err)}. ` +
|
|
34
|
+
'If the org denied access, the audit user may lack "View All Users".',
|
|
28
35
|
remediation: 'Grant "View All Users" to the audit user. For event-level access, enable Event Monitoring.',
|
|
29
36
|
});
|
|
30
37
|
return { findings };
|
|
@@ -45,13 +52,33 @@ export class FailedLoginCheck {
|
|
|
45
52
|
let perUserCounts = [];
|
|
46
53
|
let perUserUnavailable = false;
|
|
47
54
|
try {
|
|
48
|
-
const aggResult = await ctx.soql.query(`SELECT
|
|
55
|
+
const aggResult = await ctx.soql.query(`SELECT UserId, Status, COUNT(Id)
|
|
49
56
|
FROM LoginHistory
|
|
50
|
-
WHERE
|
|
51
|
-
GROUP BY
|
|
57
|
+
WHERE LoginTime > LAST_N_DAYS:7
|
|
58
|
+
GROUP BY UserId, Status
|
|
52
59
|
ORDER BY COUNT(Id) DESC
|
|
53
|
-
LIMIT
|
|
54
|
-
|
|
60
|
+
LIMIT ${MAX_GROUPS}`);
|
|
61
|
+
const failuresByUser = new Map();
|
|
62
|
+
for (const r of aggResult.records) {
|
|
63
|
+
if (r.Status === SUCCESS)
|
|
64
|
+
continue;
|
|
65
|
+
failuresByUser.set(r.UserId, (failuresByUser.get(r.UserId) ?? 0) + r.expr0);
|
|
66
|
+
}
|
|
67
|
+
const ranked = [...failuresByUser.entries()].sort((a, b) => b[1] - a[1]).slice(0, 50);
|
|
68
|
+
// LoginHistory has no Username field and no User relationship: resolve names separately.
|
|
69
|
+
const names = new Map();
|
|
70
|
+
if (ranked.length > 0) {
|
|
71
|
+
const inClause = ranked.map(([id]) => `'${id}'`).join(',');
|
|
72
|
+
const users = await ctx.soql.queryAll(`SELECT Id, Username FROM User WHERE Id IN (${inClause})`);
|
|
73
|
+
for (const u of users)
|
|
74
|
+
names.set(u.Id, u.Username);
|
|
75
|
+
}
|
|
76
|
+
perUserCounts = ranked.map(([id, n]) => ({ Username: names.get(id) ?? id, expr0: n }));
|
|
77
|
+
// Groups are ranked by size across every status, so a full page may have cut off smaller
|
|
78
|
+
// failure groups. Targets found stand; "no target" is then not a conclusion.
|
|
79
|
+
if (aggResult.records.length >= MAX_GROUPS && !perUserCounts.some((r) => r.expr0 >= BRUTE_FORCE_PER_USER)) {
|
|
80
|
+
perUserUnavailable = true;
|
|
81
|
+
}
|
|
55
82
|
}
|
|
56
83
|
catch {
|
|
57
84
|
// Recorded: without the per-user breakdown, "no brute-force pattern" is not a
|
|
@@ -14,16 +14,18 @@ export class FieldHistoryTrackingCheck {
|
|
|
14
14
|
const setupUrl = `${baseUrl}/lightning/setup/ObjectManager/home`;
|
|
15
15
|
const objectList = SENSITIVE_OBJECTS.map((o) => `'${o}'`).join(', ');
|
|
16
16
|
try {
|
|
17
|
-
// Tooling API:
|
|
18
|
-
//
|
|
19
|
-
|
|
17
|
+
// Tooling API: the tracked fields on each sensitive object, counted here. FieldDefinition
|
|
18
|
+
// supports no aggregates (its Id is not aggregatable), so COUNT/GROUP BY is rejected.
|
|
19
|
+
// Objects with zero tracked fields are absent from the result — those are violations.
|
|
20
|
+
const results = await ctx.tooling.query(`SELECT EntityDefinition.QualifiedApiName, QualifiedApiName
|
|
20
21
|
FROM FieldDefinition
|
|
21
22
|
WHERE EntityDefinition.QualifiedApiName IN (${objectList})
|
|
22
|
-
AND IsFieldHistoryTracked = true
|
|
23
|
-
GROUP BY EntityDefinition.QualifiedApiName`);
|
|
23
|
+
AND IsFieldHistoryTracked = true`);
|
|
24
24
|
const trackedMap = new Map();
|
|
25
25
|
for (const r of results) {
|
|
26
|
-
|
|
26
|
+
const obj = r.EntityDefinition?.QualifiedApiName;
|
|
27
|
+
if (obj)
|
|
28
|
+
trackedMap.set(obj, (trackedMap.get(obj) ?? 0) + 1);
|
|
27
29
|
}
|
|
28
30
|
const withTracking = SENSITIVE_OBJECTS.filter((o) => (trackedMap.get(o) ?? 0) > 0);
|
|
29
31
|
const withoutTracking = SENSITIVE_OBJECTS.filter((o) => (trackedMap.get(o) ?? 0) === 0);
|
|
@@ -42,8 +44,9 @@ export class FieldHistoryTrackingCheck {
|
|
|
42
44
|
findings.push({
|
|
43
45
|
id: 'field-history-tracking-missing',
|
|
44
46
|
category: this.category,
|
|
45
|
-
|
|
46
|
-
|
|
47
|
+
// Missing history limits investigation; it exposes nothing. RULE-078.
|
|
48
|
+
riskLevel: withoutTracking.length >= 3 ? 'MEDIUM' : 'LOW',
|
|
49
|
+
title: `${withoutTracking.length} sensitive object(s) have no field history tracking (investigation gap): SBS-DATA-004`,
|
|
47
50
|
detail: `SBS-DATA-004 requires field history tracking on sensitive objects to capture who changed what data and when, enabling post-incident investigation and audit evidence. The following objects have no tracked fields: ${withoutTracking.join(', ')}. ${withTracking.length > 0 ? `Objects already configured: ${withTracking.map((o) => `${o} (${trackedMap.get(o)} field(s))`).join(', ')}.` : ''}`,
|
|
48
51
|
remediation: 'Enable field history tracking on each listed object in Setup → Object Manager → [Object] → Fields & Relationships → Set History Tracking. At minimum track key sensitive fields: email addresses, phone numbers, revenue fields, owner changes, and status changes.',
|
|
49
52
|
affectedItems: withoutTracking.map((name) => ({
|
|
@@ -53,15 +56,15 @@ export class FieldHistoryTrackingCheck {
|
|
|
53
56
|
})),
|
|
54
57
|
});
|
|
55
58
|
}
|
|
56
|
-
catch {
|
|
59
|
+
catch (err) {
|
|
57
60
|
findings.push({
|
|
58
61
|
id: 'field-history-tracking-inconclusive',
|
|
59
62
|
category: this.category,
|
|
60
63
|
riskLevel: 'INFO',
|
|
61
64
|
inconclusive: true,
|
|
62
65
|
title: 'Field history tracking status could not be determined',
|
|
63
|
-
detail:
|
|
64
|
-
remediation: '
|
|
66
|
+
detail: `SBS-DATA-004 requires field history tracking on sensitive objects. The Tooling API FieldDefinition query failed, so tracking is unassessed, not absent: ${err instanceof Error ? err.message : String(err)}`,
|
|
67
|
+
remediation: 'Check the error above. If it is an access error, confirm the audit user has API Enabled and View Setup and Configuration; otherwise verify field history tracking manually in Setup → Object Manager for Account, Contact, Lead, Opportunity, Case, Contract, and User.',
|
|
65
68
|
});
|
|
66
69
|
}
|
|
67
70
|
return { findings };
|
|
@@ -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, NamedCredential, NamedCredentialReferenceId FROM ExternalServiceRegistration'));
|
|
21
|
+
const uncredentialedServices = externalServices.filter((s) => !(s.NamedCredential ?? '').trim() && !(s.NamedCredentialReferenceId ?? '').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
|
}
|