@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
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { isMissingObjectError } from '../support/missingObject.js';
|
|
2
|
+
export class ShieldTenantSecretLifecycleCheck {
|
|
3
|
+
id = 'shield-tenant-secret-lifecycle';
|
|
4
|
+
name = 'Shield Platform Encryption Tenant Secret Lifecycle';
|
|
5
|
+
category = 'Data Security';
|
|
6
|
+
description = 'Monitors Shield TenantSecret rotation frequency (>365 days) and destroyed key status for cryptographic compliance.';
|
|
7
|
+
async run(ctx) {
|
|
8
|
+
const findings = [];
|
|
9
|
+
const baseUrl = ctx.orgInfo.instanceUrl;
|
|
10
|
+
const keyMgmtUrl = `${baseUrl}/lightning/setup/PlatformEncryptionKeyManagement/home`;
|
|
11
|
+
let secrets = [];
|
|
12
|
+
try {
|
|
13
|
+
secrets = await ctx.soql.queryAll('SELECT Id, Status, Type, Version, CreatedDate FROM TenantSecret');
|
|
14
|
+
}
|
|
15
|
+
catch (err) {
|
|
16
|
+
if (isMissingObjectError(err)) {
|
|
17
|
+
findings.push({
|
|
18
|
+
id: 'shield-tenant-secret-not-enabled',
|
|
19
|
+
category: this.category,
|
|
20
|
+
riskLevel: 'LOW',
|
|
21
|
+
passed: true,
|
|
22
|
+
title: 'Shield Platform Encryption is not enabled or TenantSecret is not accessible',
|
|
23
|
+
detail: 'TenantSecret object is not available; Shield Platform Encryption is not licensed or enabled.',
|
|
24
|
+
remediation: 'No action required if Shield Platform Encryption is not in use.',
|
|
25
|
+
});
|
|
26
|
+
return { findings };
|
|
27
|
+
}
|
|
28
|
+
findings.push({
|
|
29
|
+
id: 'shield-tenant-secret-inaccessible',
|
|
30
|
+
category: this.category,
|
|
31
|
+
riskLevel: 'INFO',
|
|
32
|
+
inconclusive: true,
|
|
33
|
+
title: 'TenantSecret could not be queried',
|
|
34
|
+
detail: `Failed to query TenantSecret: ${err instanceof Error ? err.message : String(err)}`,
|
|
35
|
+
remediation: 'Grant the audit user "Manage Encryption Keys" or "View Setup and Configuration".',
|
|
36
|
+
});
|
|
37
|
+
return { findings };
|
|
38
|
+
}
|
|
39
|
+
if (secrets.length === 0) {
|
|
40
|
+
findings.push({
|
|
41
|
+
id: 'shield-tenant-secret-ok',
|
|
42
|
+
category: this.category,
|
|
43
|
+
riskLevel: 'LOW',
|
|
44
|
+
passed: true,
|
|
45
|
+
title: 'No active Shield TenantSecret keys generated',
|
|
46
|
+
detail: 'Zero TenantSecret records were returned.',
|
|
47
|
+
remediation: 'Generate tenant encryption secrets if Shield Platform Encryption is enabled.',
|
|
48
|
+
});
|
|
49
|
+
return { findings };
|
|
50
|
+
}
|
|
51
|
+
const now = Date.now();
|
|
52
|
+
const ONE_YEAR_MS = 365 * 24 * 60 * 60 * 1000;
|
|
53
|
+
const activeSecrets = secrets.filter((s) => s.Status.toLowerCase() === 'active');
|
|
54
|
+
const unrotatedSecrets = [];
|
|
55
|
+
for (const secret of activeSecrets) {
|
|
56
|
+
const createdTime = new Date(secret.CreatedDate).getTime();
|
|
57
|
+
if (now - createdTime > ONE_YEAR_MS) {
|
|
58
|
+
unrotatedSecrets.push(secret);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (unrotatedSecrets.length > 0) {
|
|
62
|
+
findings.push({
|
|
63
|
+
id: 'shield-tenant-secret-unrotated',
|
|
64
|
+
category: this.category,
|
|
65
|
+
riskLevel: 'MEDIUM',
|
|
66
|
+
title: `${unrotatedSecrets.length} active Shield Tenant Secret(s) have not been rotated in >365 days`,
|
|
67
|
+
detail: 'Active Shield tenant encryption keys (Data, SearchIndex, EventBus) have exceeded the 365-day rotation window. Cryptographic key lifecycle standards (ISO/IEC 27001:2022 A.8.24, NZISM 17.2, HISO 10029) require cryptographic keys to be rotated at least annually to minimize key exposure and compromise blast radius.',
|
|
68
|
+
remediation: 'Generate a new Tenant Secret in Setup → Platform Encryption → Key Management and re-encrypt affected archive data if required by corporate compliance policies.',
|
|
69
|
+
affectedItems: unrotatedSecrets.map((s) => ({
|
|
70
|
+
label: `Type: ${s.Type || 'Data'}, Version: ${s.Version ?? 'N/A'}`,
|
|
71
|
+
url: keyMgmtUrl,
|
|
72
|
+
note: `Created on ${new Date(s.CreatedDate).toISOString().slice(0, 10)} (>365 days active)`,
|
|
73
|
+
})),
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
findings.push({
|
|
78
|
+
id: 'shield-tenant-secret-ok',
|
|
79
|
+
category: this.category,
|
|
80
|
+
riskLevel: 'LOW',
|
|
81
|
+
passed: true,
|
|
82
|
+
title: 'Active Shield Tenant Secrets are rotated within cryptographic lifecycle standards',
|
|
83
|
+
detail: `${activeSecrets.length} active Tenant Secret(s) verified; all active keys were created or rotated within the last 365 days.`,
|
|
84
|
+
remediation: 'Continue regular annual tenant secret key rotation.',
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
return { findings };
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
//# sourceMappingURL=ShieldTenantSecretLifecycleCheck.js.map
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { hasField } from '../support/schema.js';
|
|
1
2
|
/**
|
|
2
3
|
* Ninety days rather than thirty. SOAP callers are disproportionately the least routine
|
|
3
4
|
* things in an org: a quarterly reconciliation job, a backup tool, a device switched on
|
|
@@ -48,7 +49,21 @@ export class SoapLoginApiAuthCheck {
|
|
|
48
49
|
// grant paths, because a profile's own permissions live on a PermissionSet with
|
|
49
50
|
// IsOwnedByProfile = true. Orgs on a release without the field will throw here.
|
|
50
51
|
let holders = [];
|
|
52
|
+
const notYet = {
|
|
53
|
+
id: 'soap-login-api-auth-inconclusive-field',
|
|
54
|
+
category: this.category,
|
|
55
|
+
riskLevel: 'INFO',
|
|
56
|
+
inconclusive: true,
|
|
57
|
+
title: '"Use Any API Auth" permission is not queryable in this org yet',
|
|
58
|
+
detail: 'The PermissionsUseAnyApiAuth field is not available. That is expected on orgs not yet upgraded to a release that carries it, and it means readiness for the Winter \'27 SOAP login() change cannot be assessed here. Note this permission is not the same as "Use Any API Client", which is covered separately by the api-client-permission check.',
|
|
59
|
+
remediation: `Re-run this audit after the org takes Winter '27, or check Setup → Permission Sets for "Use Any API Auth" directly: ${permSetUrl}`,
|
|
60
|
+
};
|
|
51
61
|
try {
|
|
62
|
+
// Describe first: on a release without the field, filtering on it is rejected outright.
|
|
63
|
+
if (!(await hasField(ctx, 'PermissionSet', 'PermissionsUseAnyApiAuth'))) {
|
|
64
|
+
findings.push(notYet);
|
|
65
|
+
return { findings };
|
|
66
|
+
}
|
|
52
67
|
const result = await ctx.soql.query(`SELECT Assignee.Id, Assignee.Username, Assignee.Profile.Name,
|
|
53
68
|
PermissionSet.Name, PermissionSet.IsOwnedByProfile
|
|
54
69
|
FROM PermissionSetAssignment
|
|
@@ -56,15 +71,12 @@ export class SoapLoginApiAuthCheck {
|
|
|
56
71
|
AND Assignee.IsActive = true`);
|
|
57
72
|
holders = result.records;
|
|
58
73
|
}
|
|
59
|
-
catch {
|
|
74
|
+
catch (err) {
|
|
60
75
|
findings.push({
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
title: '"Use Any API Auth" permission is not queryable in this org yet',
|
|
66
|
-
detail: 'The PermissionsUseAnyApiAuth field was not available. That is expected on orgs not yet upgraded to a release that carries it, and it means readiness for the Winter \'27 SOAP login() change cannot be assessed here. Note this permission is not the same as "Use Any API Client", which is covered separately by the api-client-permission check.',
|
|
67
|
-
remediation: `Re-run this audit after the org takes Winter '27, or check Setup → Permission Sets for "Use Any API Auth" directly: ${permSetUrl}`,
|
|
76
|
+
...notYet,
|
|
77
|
+
title: '"Use Any API Auth" holders could not be read',
|
|
78
|
+
detail: `Who holds "Use Any API Auth" could not be read, so readiness for the Winter '27 SOAP login() change is unassessed. The org said: ${err instanceof Error ? err.message : String(err)}`,
|
|
79
|
+
remediation: 'Check the error above. If it is an access error, confirm the audit user can read PermissionSetAssignment (View Setup and Configuration), then re-run.',
|
|
68
80
|
});
|
|
69
81
|
return { findings };
|
|
70
82
|
}
|
|
@@ -10,7 +10,9 @@ export class SsoEnforcementCheck {
|
|
|
10
10
|
// Single query: recent credential logins over the past 30 days.
|
|
11
11
|
// Presence of 'Username-Password' logins is direct evidence that SBS-AUTH-001
|
|
12
12
|
// (org-wide SSO enforcement) is not fully applied.
|
|
13
|
-
const result = await ctx.soql.queryAll(
|
|
13
|
+
const result = await ctx.soql.queryAll(
|
|
14
|
+
// LoginHistory carries no Username field and no User relationship; names are resolved below.
|
|
15
|
+
`SELECT Id, UserId, LoginType, LoginTime
|
|
14
16
|
FROM LoginHistory
|
|
15
17
|
WHERE LoginTime > LAST_N_DAYS:30
|
|
16
18
|
AND LoginType = 'Username-Password'
|
|
@@ -37,9 +39,17 @@ export class SsoEnforcementCheck {
|
|
|
37
39
|
existing.count++;
|
|
38
40
|
}
|
|
39
41
|
else {
|
|
40
|
-
byUser.set(r.UserId, { username: r.
|
|
42
|
+
byUser.set(r.UserId, { username: r.UserId, count: 1, latest: r.LoginTime });
|
|
41
43
|
}
|
|
42
44
|
}
|
|
45
|
+
// At most 300 logins, so at most 300 distinct users: one bounded lookup.
|
|
46
|
+
const inClause = [...byUser.keys()].map((id) => `'${id}'`).join(',');
|
|
47
|
+
const users = await ctx.soql.queryAll(`SELECT Id, Username FROM User WHERE Id IN (${inClause})`);
|
|
48
|
+
for (const u of users) {
|
|
49
|
+
const entry = byUser.get(u.Id);
|
|
50
|
+
if (entry)
|
|
51
|
+
entry.username = u.Username;
|
|
52
|
+
}
|
|
43
53
|
const uniqueUsers = [...byUser.entries()];
|
|
44
54
|
findings.push({
|
|
45
55
|
id: 'sso-password-logins-detected',
|
|
@@ -72,14 +82,15 @@ export class SsoEnforcementCheck {
|
|
|
72
82
|
});
|
|
73
83
|
}
|
|
74
84
|
}
|
|
75
|
-
catch {
|
|
85
|
+
catch (err) {
|
|
86
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
76
87
|
findings.push({
|
|
77
88
|
id: 'sso-enforcement-inconclusive',
|
|
78
89
|
category: this.category,
|
|
79
90
|
riskLevel: 'INFO',
|
|
80
91
|
inconclusive: true,
|
|
81
|
-
title: 'SSO enforcement status could not be determined: LoginHistory not
|
|
82
|
-
detail:
|
|
92
|
+
title: 'SSO enforcement status could not be determined: LoginHistory could not be read',
|
|
93
|
+
detail: `SBS-AUTH-001/002 require SSO enforcement configuration to be verified. LoginHistory could not be read: ${reason}`,
|
|
83
94
|
remediation: 'Manually verify in Setup → Single Sign-On Settings that "Prevent Login with Salesforce Credentials" is enabled.',
|
|
84
95
|
});
|
|
85
96
|
}
|
|
@@ -9,17 +9,17 @@ export class TransactionSecurityPolicyCheck {
|
|
|
9
9
|
const setupUrl = `${baseUrl}/lightning/setup/TransactionSecurityPolicies/home`;
|
|
10
10
|
let policies;
|
|
11
11
|
try {
|
|
12
|
-
policies = await ctx.tooling.query(`SELECT Id,
|
|
12
|
+
policies = await ctx.tooling.query(`SELECT Id, DeveloperName, MasterLabel, EventType, State FROM TransactionSecurityPolicy WHERE State = 'Enabled'`);
|
|
13
13
|
}
|
|
14
|
-
catch {
|
|
14
|
+
catch (err) {
|
|
15
15
|
findings.push({
|
|
16
16
|
id: 'transaction-security-policy-inaccessible',
|
|
17
17
|
category: this.category,
|
|
18
18
|
riskLevel: 'INFO',
|
|
19
19
|
inconclusive: true,
|
|
20
20
|
title: 'Transaction Security Policies could not be queried',
|
|
21
|
-
detail:
|
|
22
|
-
remediation: '
|
|
21
|
+
detail: `The Tooling API TransactionSecurityPolicy query failed, so whether automated threat response exists is unassessed, not absent: ${err instanceof Error ? err.message : String(err)}`,
|
|
22
|
+
remediation: 'Check the error above. If it is an access error, confirm the audit user has API Enabled and View Setup and Configuration, then re-run.',
|
|
23
23
|
});
|
|
24
24
|
return { findings };
|
|
25
25
|
}
|
|
@@ -51,7 +51,7 @@ export class TransactionSecurityPolicyCheck {
|
|
|
51
51
|
detail: `Active Transaction Security Policies covering: ${eventTypes.join(', ')}. Automated threat detection and response is in place for these event types.`,
|
|
52
52
|
remediation: 'Periodically review policies to ensure coverage includes login anomalies, bulk data exports, and high-volume API usage. Verify that policy actions (Block/Notify) are appropriate for each event type.',
|
|
53
53
|
affectedItems: policies.map((p) => ({
|
|
54
|
-
label: p.
|
|
54
|
+
label: p.MasterLabel || p.DeveloperName,
|
|
55
55
|
url: setupUrl,
|
|
56
56
|
note: `EventType: ${p.EventType}`,
|
|
57
57
|
})),
|
|
@@ -13,27 +13,36 @@ export class TrustedIPRangesCheck {
|
|
|
13
13
|
const findings = [];
|
|
14
14
|
const baseUrl = ctx.orgInfo.instanceUrl;
|
|
15
15
|
const setupUrl = `${baseUrl}/lightning/setup/SecurityNetworkAccess/home`;
|
|
16
|
-
let
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
16
|
+
let settings = null;
|
|
17
|
+
let error = 'this run has no Metadata API client';
|
|
18
|
+
if (ctx.metadata) {
|
|
19
|
+
try {
|
|
20
|
+
settings = await ctx.metadata.read('SecuritySettings', 'Security');
|
|
21
|
+
if (!settings)
|
|
22
|
+
error = 'the Security settings were not returned';
|
|
23
|
+
}
|
|
24
|
+
catch (err) {
|
|
25
|
+
error = err instanceof Error ? err.message : String(err);
|
|
26
|
+
}
|
|
23
27
|
}
|
|
24
|
-
|
|
28
|
+
if (!settings) {
|
|
25
29
|
findings.push({
|
|
26
30
|
id: 'trusted-ip-inaccessible',
|
|
27
31
|
category: this.category,
|
|
28
32
|
riskLevel: 'INFO',
|
|
29
33
|
inconclusive: true,
|
|
30
34
|
title: 'Trusted IP ranges could not be retrieved',
|
|
31
|
-
detail:
|
|
35
|
+
detail: `Trusted IP ranges are read from the Security settings in the Metadata API, and could not be: ${error}.`,
|
|
32
36
|
remediation: 'Review trusted IP ranges manually in Setup → Security → Network Access. Ensure the audit user has "View Setup and Configuration" permission.',
|
|
33
37
|
affectedItems: [{ label: 'Network Access Setup', url: setupUrl }],
|
|
34
38
|
});
|
|
35
39
|
return { findings };
|
|
36
40
|
}
|
|
41
|
+
// The Metadata API returns a single range as an object, several as an array.
|
|
42
|
+
const raw = settings.networkAccess?.ipRanges;
|
|
43
|
+
const ranges = (raw === undefined ? [] : Array.isArray(raw) ? raw : [raw])
|
|
44
|
+
.filter((r) => r.start && r.end)
|
|
45
|
+
.map((r) => ({ StartAddress: r.start, EndAddress: r.end, Description: r.description ?? null }));
|
|
37
46
|
if (ranges.length === 0) {
|
|
38
47
|
findings.push({
|
|
39
48
|
id: 'trusted-ip-none',
|
|
@@ -43,6 +43,12 @@ export class UsersAndAdminsCheck {
|
|
|
43
43
|
const viewAllCount = viewAllIds.size;
|
|
44
44
|
const customizeAppCount = uniqueIds(customizeAppUsers).size;
|
|
45
45
|
const authorApexCount = uniqueIds(authorApexUsers).size;
|
|
46
|
+
// In a sandbox, developers routinely hold admin: cap admin-count findings at HIGH, and say so.
|
|
47
|
+
const isSandbox = ctx.orgInfo.isSandbox;
|
|
48
|
+
const sandboxCap = (level) => isSandbox && level === 'CRITICAL' ? 'HIGH' : level;
|
|
49
|
+
const sandboxNote = isSandbox
|
|
50
|
+
? ' Rated at most HIGH because this org is a sandbox, where developers commonly hold admin; treat it as CRITICAL if this sandbox holds production data.'
|
|
51
|
+
: '';
|
|
46
52
|
// SBS-ACS-004: flag users with ALL THREE super-admin permissions simultaneously
|
|
47
53
|
const superAdminIds = [...modifyAllIds].filter((id) => viewAllIds.has(id) && manageUsersIds.has(id));
|
|
48
54
|
if (superAdminIds.length > 0) {
|
|
@@ -53,20 +59,33 @@ export class UsersAndAdminsCheck {
|
|
|
53
59
|
findings.push({
|
|
54
60
|
id: 'users-super-admin-combo',
|
|
55
61
|
category: this.category,
|
|
56
|
-
|
|
62
|
+
// Every org needs an administrator: grade on how many hold unrestricted control.
|
|
63
|
+
riskLevel: sandboxCap(superAdminIds.length > 5 ? 'CRITICAL' : superAdminIds.length > 3 ? 'HIGH' : 'LOW'),
|
|
57
64
|
title: `${superAdminIds.length} user(s) hold the super-admin permission combination (ViewAllData + ModifyAllData + ManageUsers)`,
|
|
58
|
-
detail: 'SBS-ACS-004 requires documented justification for any user holding all three of ViewAllData, ModifyAllData, and ManageUsers simultaneously. This combination is equivalent to unrestricted org control.'
|
|
65
|
+
detail: 'SBS-ACS-004 requires documented justification for any user holding all three of ViewAllData, ModifyAllData, and ManageUsers simultaneously. This combination is equivalent to unrestricted org control.' +
|
|
66
|
+
(superAdminIds.length > 5 ? sandboxNote : ''),
|
|
59
67
|
remediation: 'Reduce to the minimum necessary permissions. Document justification for each user in the system of record. Consider breaking this into role-specific permission sets.',
|
|
60
68
|
affectedItems: superAdminItems,
|
|
61
69
|
});
|
|
62
70
|
}
|
|
63
|
-
|
|
71
|
+
// Rate Modify All Data on the holders the super-admin finding does not already cover, so the
|
|
72
|
+
// same users are not counted towards the grade twice. The finding still lists every holder.
|
|
73
|
+
const superAdminSet = new Set(superAdminIds);
|
|
74
|
+
const otherModifyAll = [...modifyAllIds].filter((id) => !superAdminSet.has(id)).length;
|
|
75
|
+
const modifyRisk = sandboxCap(otherModifyAll > 5 ? 'CRITICAL' : otherModifyAll > 3 ? 'HIGH' : 'LOW');
|
|
76
|
+
const coveredNote = superAdminSet.size > 0
|
|
77
|
+
? ` ${superAdminSet.size} of them also hold the super-admin combination and are rated in that finding; this severity reflects the other ${otherModifyAll}.`
|
|
78
|
+
: '';
|
|
64
79
|
findings.push({
|
|
65
80
|
id: 'users-modify-all-data',
|
|
66
81
|
category: this.category,
|
|
67
82
|
riskLevel: modifyRisk,
|
|
68
83
|
title: `${modifyAllCount} user(s) have Modify All Data permission`,
|
|
69
|
-
|
|
84
|
+
// The population is always reported; at the lowest band it asks for no change.
|
|
85
|
+
passed: modifyRisk === 'LOW' || undefined,
|
|
86
|
+
detail: 'Modify All Data grants unrestricted write access across all objects. This is one of the most powerful permissions in Salesforce.' +
|
|
87
|
+
coveredNote +
|
|
88
|
+
(modifyRisk === 'HIGH' && otherModifyAll > 5 ? sandboxNote : ''),
|
|
70
89
|
remediation: 'Limit Modify All Data to essential system administrators only. Review each user and remove the permission from any non-essential accounts.',
|
|
71
90
|
affectedItems: modifyAllUsers.map((r) => userItem(r)),
|
|
72
91
|
});
|
|
@@ -76,6 +95,7 @@ export class UsersAndAdminsCheck {
|
|
|
76
95
|
category: this.category,
|
|
77
96
|
riskLevel: viewRisk,
|
|
78
97
|
title: `${viewAllCount} user(s) have View All Data permission`,
|
|
98
|
+
passed: viewRisk === 'LOW' || undefined,
|
|
79
99
|
detail: 'View All Data grants unrestricted read access across all objects, bypassing sharing rules and record-level security.',
|
|
80
100
|
remediation: 'Limit View All Data to essential users. Consider using permission sets scoped to specific objects instead.',
|
|
81
101
|
affectedItems: viewAllUsers.map((r) => userItem(r)),
|
|
@@ -31,7 +31,7 @@ export const DANGEROUS_PERMS = [
|
|
|
31
31
|
why: 'Bypass API Access Control to reach the org from any tool.' },
|
|
32
32
|
{ key: 'ManageEventLogFiles', field: 'PermissionsManageEventLogFiles', label: 'Manage Event Log Files', tier: 'MEDIUM',
|
|
33
33
|
why: 'Access detailed monitoring/event data across the org.' },
|
|
34
|
-
{ key: 'ManageSession', field: '
|
|
34
|
+
{ key: 'ManageSession', field: 'PermissionsManageSessionPermissionSets', label: 'Manage Session Permission Set Activations', tier: 'MEDIUM',
|
|
35
35
|
why: 'Activate session-based permission sets, elevating access on demand.' },
|
|
36
36
|
{ key: 'ViewAllUsers', field: 'PermissionsViewAllUsers', label: 'View All Users', tier: 'MEDIUM',
|
|
37
37
|
why: 'Enumerate every user in the org: reconnaissance for targeting.' },
|
package/lib/checks/registry.js
CHANGED
|
@@ -101,6 +101,21 @@ import { AgentMonitoringCoverageCheck } from './impl/AgentMonitoringCoverageChec
|
|
|
101
101
|
import { AgentQueryReachCheck } from './impl/AgentQueryReachCheck.js';
|
|
102
102
|
import { AgentOutboundActionsCheck } from './impl/AgentOutboundActionsCheck.js';
|
|
103
103
|
import { TrustedUrlHygieneCheck } from './impl/TrustedUrlHygieneCheck.js';
|
|
104
|
+
// 14 New Checks & Attack Chains
|
|
105
|
+
import { GenAiPromptTemplateGroundingCheck } from './impl/GenAiPromptTemplateGroundingCheck.js';
|
|
106
|
+
import { DataCloudDataSpaceIsolationCheck } from './impl/DataCloudDataSpaceIsolationCheck.js';
|
|
107
|
+
import { PlatformEventSubscriberContextCheck } from './impl/PlatformEventSubscriberContextCheck.js';
|
|
108
|
+
import { FlowHttpCalloutCredentialBypassCheck } from './impl/FlowHttpCalloutCredentialBypassCheck.js';
|
|
109
|
+
import { OauthDeviceAndAssetTokenFlowsCheck } from './impl/OauthDeviceAndAssetTokenFlowsCheck.js';
|
|
110
|
+
import { DelegatedAuthenticationExposureCheck } from './impl/DelegatedAuthenticationExposureCheck.js';
|
|
111
|
+
import { DelegatedAdministrationGroupsCheck } from './impl/DelegatedAdministrationGroupsCheck.js';
|
|
112
|
+
import { AuthProviderRegistrationHandlerCheck } from './impl/AuthProviderRegistrationHandlerCheck.js';
|
|
113
|
+
import { InboundEmailHandlerExposureCheck } from './impl/InboundEmailHandlerExposureCheck.js';
|
|
114
|
+
import { OrgWideEmailSpoofingCheck } from './impl/OrgWideEmailSpoofingCheck.js';
|
|
115
|
+
import { ExternalAccountHierarchyExposureCheck } from './impl/ExternalAccountHierarchyExposureCheck.js';
|
|
116
|
+
import { RestrictionRulesIntegrityCheck } from './impl/RestrictionRulesIntegrityCheck.js';
|
|
117
|
+
import { PackagePostInstallSupplyChainCheck } from './impl/PackagePostInstallSupplyChainCheck.js';
|
|
118
|
+
import { ShieldTenantSecretLifecycleCheck } from './impl/ShieldTenantSecretLifecycleCheck.js';
|
|
104
119
|
// Order matters: a check's dependsOnCache must be satisfied by a preceding check's populatesCache.
|
|
105
120
|
// CheckEngine.validateCacheOrdering() enforces this at startup.
|
|
106
121
|
export const CHECKS = [
|
|
@@ -178,6 +193,21 @@ export const CHECKS = [
|
|
|
178
193
|
new ExperienceCspCheck(), // Experience Cloud CSP / Lightning Web Security advisory
|
|
179
194
|
new SandboxDataMaskingCheck(), // sandbox with populated (likely unmasked) PII
|
|
180
195
|
new PrivilegedAccessCheck(), // writes: effectivePermissions; shadow-admin detection
|
|
196
|
+
// 14 New Checks across 5 Salesforce surfaces
|
|
197
|
+
new GenAiPromptTemplateGroundingCheck(), // Tooling: GenAiPromptTemplate (AI & Agents)
|
|
198
|
+
new DataCloudDataSpaceIsolationCheck(), // SOQL: DataSpace, DataShareTarget (Data Access & Sharing)
|
|
199
|
+
new PlatformEventSubscriberContextCheck(), // Tooling: PlatformEventSubscriberConfig (Apex & Code Security)
|
|
200
|
+
new FlowHttpCalloutCredentialBypassCheck(), // Tooling: Flow, ExternalServiceRegistration (Apex & Code Security)
|
|
201
|
+
new OauthDeviceAndAssetTokenFlowsCheck(), // Metadata: OauthOidcSettings (Identity & Authentication)
|
|
202
|
+
new DelegatedAuthenticationExposureCheck(), // Metadata: SecuritySettings (Identity & Authentication)
|
|
203
|
+
new DelegatedAdministrationGroupsCheck(), // SOQL: DelegateGroup (Users, Permissions & Privilege)
|
|
204
|
+
new AuthProviderRegistrationHandlerCheck(), // SOQL: AuthProvider, ApexClass (Identity & Authentication)
|
|
205
|
+
new InboundEmailHandlerExposureCheck(), // SOQL: EmailServicesFunction (Integrations)
|
|
206
|
+
new OrgWideEmailSpoofingCheck(), // SOQL: OrgWideEmailAddress, DkimKey (Integrations)
|
|
207
|
+
new ExternalAccountHierarchyExposureCheck(), // SOQL: User.IsPrmSuperUser (Guest & External-Facing Access)
|
|
208
|
+
new RestrictionRulesIntegrityCheck(), // Tooling: RestrictionRule (Data Access & Sharing)
|
|
209
|
+
new PackagePostInstallSupplyChainCheck(), // Tooling: InstalledSubscriberPackage (Integrations)
|
|
210
|
+
new ShieldTenantSecretLifecycleCheck(), // SOQL: TenantSecret (Data Access & Sharing)
|
|
181
211
|
// AI & Agents block (v1.5) — Agentforce / GenAI. AgentInventoryCheck writes agentInventory,
|
|
182
212
|
// agentUsers, agentAccess; the Phase 2 dependent checks are registered after it.
|
|
183
213
|
new AgentInventoryCheck(), // writes: agentInventory, agentUsers, agentAccess
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How an Apex class's record sharing and CRUD/FLS are controlled (spec/apex-access-mode.md).
|
|
3
|
+
*
|
|
4
|
+
* Record sharing follows the class's own sharing keyword. WITH SYSTEM_MODE and
|
|
5
|
+
* AccessLevel.SYSTEM_MODE switch off only CRUD/FLS for the operation they are on. A class with no
|
|
6
|
+
* keyword runs with its caller's sharing, and as an entry point (Aura, REST, guest) without it.
|
|
7
|
+
*/
|
|
8
|
+
export type SharingKeyword = 'with' | 'without' | 'inherited' | 'none';
|
|
9
|
+
export declare const SYSTEM_MODE: RegExp;
|
|
10
|
+
/**
|
|
11
|
+
* The body with comments removed. A class's keywords and access modes are read from code only:
|
|
12
|
+
* a `without sharing` class with "with sharing" in a comment must not read as protected.
|
|
13
|
+
* String literals are kept (dynamic SOQL carries WITH SYSTEM_MODE inside one), and scanned past
|
|
14
|
+
* correctly, so `@RestResource(urlMapping='/x/*')` does not open a comment.
|
|
15
|
+
*/
|
|
16
|
+
export declare function apexCode(body: string): string;
|
|
17
|
+
/** The code with string literals blanked, for matching declarations and enforcement that must not hide in text. */
|
|
18
|
+
export declare function codeWithoutStrings(body: string): string;
|
|
19
|
+
interface ClassDeclaration {
|
|
20
|
+
name: string;
|
|
21
|
+
/** The modifiers before `class`, from the previous statement or block boundary. */
|
|
22
|
+
modifiers: string;
|
|
23
|
+
/** The parent class named by `extends`, if any. */
|
|
24
|
+
parent?: string;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Every class declared in the body, outer and inner, found with literal patterns in one linear
|
|
28
|
+
* pass (a regex built around the name backtracked badly on long runs of words).
|
|
29
|
+
*/
|
|
30
|
+
export declare function classDeclarations(body: string): ClassDeclaration[];
|
|
31
|
+
/**
|
|
32
|
+
* The sharing keyword on the declaration of `className` itself, or null when the body declares no
|
|
33
|
+
* class of that name (an interface, enum or trigger). Modifiers may sit on either side of the
|
|
34
|
+
* keyword (`public virtual without sharing class`, `global with sharing virtual class`).
|
|
35
|
+
*/
|
|
36
|
+
export declare function sharingKeyword(className: string, body: string): SharingKeyword | null;
|
|
37
|
+
/** The class `className` extends, as written in its declaration (namespace and outer class stripped). */
|
|
38
|
+
export declare function parentClass(className: string, body: string): string | undefined;
|
|
39
|
+
/**
|
|
40
|
+
* The sharing a class actually runs with. A class with no keyword takes its parent's when it
|
|
41
|
+
* extends one: Apex classes inherit the sharing setting of the class they extend (spec MN-001).
|
|
42
|
+
* `lookup` returns a class body by name; unknown parents leave the keyword as declared.
|
|
43
|
+
*/
|
|
44
|
+
export declare function effectiveSharing(className: string, body: string, lookup: (name: string) => string | undefined): SharingKeyword | null;
|
|
45
|
+
/** Whether the class's code (not its comments) uses SYSTEM_MODE anywhere. */
|
|
46
|
+
export declare function usesSystemMode(body: string): boolean;
|
|
47
|
+
/**
|
|
48
|
+
* Whether any class declared in the body, outer or inner, is `without sharing`. An inner class
|
|
49
|
+
* keeps its own keyword, so a `with sharing` class can still run queries without sharing through
|
|
50
|
+
* one (spec MN-002).
|
|
51
|
+
*/
|
|
52
|
+
export declare function declaresWithoutSharing(body: string): boolean;
|
|
53
|
+
export declare const DML_AS_SYSTEM: RegExp;
|
|
54
|
+
export declare const DML_AS_USER: RegExp;
|
|
55
|
+
export {};
|
|
56
|
+
//# sourceMappingURL=apexAccess.d.ts.map
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { testApexPattern } from '@cclabsnz/sf-core';
|
|
2
|
+
export const SYSTEM_MODE = /\bWITH\s+SYSTEM_MODE\b|\bAccessLevel\s*\.\s*SYSTEM_MODE\b/i;
|
|
3
|
+
/**
|
|
4
|
+
* The body with comments removed. A class's keywords and access modes are read from code only:
|
|
5
|
+
* a `without sharing` class with "with sharing" in a comment must not read as protected.
|
|
6
|
+
* String literals are kept (dynamic SOQL carries WITH SYSTEM_MODE inside one), and scanned past
|
|
7
|
+
* correctly, so `@RestResource(urlMapping='/x/*')` does not open a comment.
|
|
8
|
+
*/
|
|
9
|
+
export function apexCode(body) {
|
|
10
|
+
let out = '';
|
|
11
|
+
let i = 0;
|
|
12
|
+
while (i < body.length) {
|
|
13
|
+
const c = body[i];
|
|
14
|
+
const next = body[i + 1];
|
|
15
|
+
if (c === "'") {
|
|
16
|
+
let j = i + 1;
|
|
17
|
+
while (j < body.length && body[j] !== "'" && body[j] !== '\n')
|
|
18
|
+
j += body[j] === '\\' ? 2 : 1;
|
|
19
|
+
out += body.slice(i, j + 1);
|
|
20
|
+
i = j + 1;
|
|
21
|
+
}
|
|
22
|
+
else if (c === '/' && next === '/') {
|
|
23
|
+
while (i < body.length && body[i] !== '\n')
|
|
24
|
+
i++;
|
|
25
|
+
}
|
|
26
|
+
else if (c === '/' && next === '*') {
|
|
27
|
+
const end = body.indexOf('*/', i + 2);
|
|
28
|
+
out += ' ';
|
|
29
|
+
i = end === -1 ? body.length : end + 2;
|
|
30
|
+
}
|
|
31
|
+
else {
|
|
32
|
+
out += c;
|
|
33
|
+
i++;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return out;
|
|
37
|
+
}
|
|
38
|
+
/** The code with string literals blanked, for matching declarations and enforcement that must not hide in text. */
|
|
39
|
+
export function codeWithoutStrings(body) {
|
|
40
|
+
return apexCode(body).replace(/'(?:[^'\\\n]|\\.)*'/g, "''");
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Every class declared in the body, outer and inner, found with literal patterns in one linear
|
|
44
|
+
* pass (a regex built around the name backtracked badly on long runs of words).
|
|
45
|
+
*/
|
|
46
|
+
export function classDeclarations(body) {
|
|
47
|
+
const code = codeWithoutStrings(body);
|
|
48
|
+
const out = [];
|
|
49
|
+
const decl = /\bclass\s+(\w+)/gi;
|
|
50
|
+
for (let m = decl.exec(code); m !== null; m = decl.exec(code)) {
|
|
51
|
+
const start = Math.max(code.lastIndexOf(';', m.index), code.lastIndexOf('{', m.index), code.lastIndexOf('}', m.index)) + 1;
|
|
52
|
+
const end = code.indexOf('{', m.index);
|
|
53
|
+
const header = code.slice(m.index, end === -1 ? code.length : end);
|
|
54
|
+
out.push({
|
|
55
|
+
name: m[1],
|
|
56
|
+
modifiers: code.slice(start, m.index).toLowerCase(),
|
|
57
|
+
parent: /\bextends\s+([\w.]+)/i.exec(header)?.[1],
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
function keywordOf(modifiers) {
|
|
63
|
+
if (/\bwithout\s+sharing\b/.test(modifiers))
|
|
64
|
+
return 'without';
|
|
65
|
+
if (/\binherited\s+sharing\b/.test(modifiers))
|
|
66
|
+
return 'inherited';
|
|
67
|
+
if (/\bwith\s+sharing\b/.test(modifiers))
|
|
68
|
+
return 'with';
|
|
69
|
+
return 'none';
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* The sharing keyword on the declaration of `className` itself, or null when the body declares no
|
|
73
|
+
* class of that name (an interface, enum or trigger). Modifiers may sit on either side of the
|
|
74
|
+
* keyword (`public virtual without sharing class`, `global with sharing virtual class`).
|
|
75
|
+
*/
|
|
76
|
+
export function sharingKeyword(className, body) {
|
|
77
|
+
const target = className.toLowerCase();
|
|
78
|
+
const own = classDeclarations(body).find((d) => d.name.toLowerCase() === target);
|
|
79
|
+
return own ? keywordOf(own.modifiers) : null;
|
|
80
|
+
}
|
|
81
|
+
/** The class `className` extends, as written in its declaration (namespace and outer class stripped). */
|
|
82
|
+
export function parentClass(className, body) {
|
|
83
|
+
const target = className.toLowerCase();
|
|
84
|
+
const parent = classDeclarations(body).find((d) => d.name.toLowerCase() === target)?.parent;
|
|
85
|
+
return parent?.split('.').pop();
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* The sharing a class actually runs with. A class with no keyword takes its parent's when it
|
|
89
|
+
* extends one: Apex classes inherit the sharing setting of the class they extend (spec MN-001).
|
|
90
|
+
* `lookup` returns a class body by name; unknown parents leave the keyword as declared.
|
|
91
|
+
*/
|
|
92
|
+
export function effectiveSharing(className, body, lookup) {
|
|
93
|
+
let name = className;
|
|
94
|
+
let current = body;
|
|
95
|
+
const seen = new Set();
|
|
96
|
+
for (;;) {
|
|
97
|
+
const keyword = sharingKeyword(name, current);
|
|
98
|
+
if (keyword !== 'none')
|
|
99
|
+
return keyword;
|
|
100
|
+
const parent = parentClass(name, current);
|
|
101
|
+
if (!parent || seen.has(parent.toLowerCase()))
|
|
102
|
+
return keyword;
|
|
103
|
+
seen.add(parent.toLowerCase());
|
|
104
|
+
const parentBody = lookup(parent);
|
|
105
|
+
if (parentBody === undefined)
|
|
106
|
+
return keyword;
|
|
107
|
+
name = parent;
|
|
108
|
+
current = parentBody;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
/** Whether the class's code (not its comments) uses SYSTEM_MODE anywhere. */
|
|
112
|
+
export function usesSystemMode(body) {
|
|
113
|
+
const code = apexCode(body);
|
|
114
|
+
return testApexPattern(code, SYSTEM_MODE) || testApexPattern(code, DML_AS_SYSTEM);
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Whether any class declared in the body, outer or inner, is `without sharing`. An inner class
|
|
118
|
+
* keeps its own keyword, so a `with sharing` class can still run queries without sharing through
|
|
119
|
+
* one (spec MN-002).
|
|
120
|
+
*/
|
|
121
|
+
export function declaresWithoutSharing(body) {
|
|
122
|
+
return classDeclarations(body).some((d) => keywordOf(d.modifiers) === 'without');
|
|
123
|
+
}
|
|
124
|
+
// Data-model access modes on DML: `insert as system rows;` / `update as user rows;`.
|
|
125
|
+
export const DML_AS_SYSTEM = /\b(?:insert|update|upsert|delete|undelete|merge)\s+as\s+system\b/i;
|
|
126
|
+
export const DML_AS_USER = /\b(?:insert|update|upsert|delete|undelete|merge)\s+as\s+user\b/i;
|
|
127
|
+
//# sourceMappingURL=apexAccess.js.map
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* True when a query failed because the object or feature does not exist in this org (an
|
|
3
|
+
* unlicensed cloud, a disabled feature): the evidence is genuinely absent, so the check may
|
|
4
|
+
* treat the result as empty.
|
|
5
|
+
*
|
|
6
|
+
* Anything else, a permission error above all, must be rethrown so CheckEngine reports the
|
|
7
|
+
* check as inconclusive. Swallowing it reads as "nothing found", which a report then states
|
|
8
|
+
* as a pass.
|
|
9
|
+
*/
|
|
10
|
+
export declare function isMissingObjectError(err: unknown): boolean;
|
|
11
|
+
/** Run a query, returning [] only when the object does not exist in this org. Other errors propagate. */
|
|
12
|
+
export declare function queryIfPresent<T>(run: () => Promise<T[]>): Promise<T[]>;
|
|
13
|
+
//# sourceMappingURL=missingObject.d.ts.map
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { isApiError } from '@cclabsnz/sf-core';
|
|
2
|
+
/**
|
|
3
|
+
* True when a query failed because the object or feature does not exist in this org (an
|
|
4
|
+
* unlicensed cloud, a disabled feature): the evidence is genuinely absent, so the check may
|
|
5
|
+
* treat the result as empty.
|
|
6
|
+
*
|
|
7
|
+
* Anything else, a permission error above all, must be rethrown so CheckEngine reports the
|
|
8
|
+
* check as inconclusive. Swallowing it reads as "nothing found", which a report then states
|
|
9
|
+
* as a pass.
|
|
10
|
+
*/
|
|
11
|
+
export function isMissingObjectError(err) {
|
|
12
|
+
if (isApiError(err)) {
|
|
13
|
+
// MALFORMED_QUERY is a bug in the query, never an absent feature: treating it as "no rows"
|
|
14
|
+
// would report an unchecked area as clean.
|
|
15
|
+
if (/INVALID_TYPE|NOT_FOUND/i.test(err.errorCode))
|
|
16
|
+
return true;
|
|
17
|
+
if (err.statusCode === 404)
|
|
18
|
+
return true;
|
|
19
|
+
}
|
|
20
|
+
const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();
|
|
21
|
+
return (msg.includes('not supported') ||
|
|
22
|
+
msg.includes('invalid type') ||
|
|
23
|
+
msg.includes('is not supported') ||
|
|
24
|
+
msg.includes('sobject type'));
|
|
25
|
+
}
|
|
26
|
+
/** Run a query, returning [] only when the object does not exist in this org. Other errors propagate. */
|
|
27
|
+
export async function queryIfPresent(run) {
|
|
28
|
+
try {
|
|
29
|
+
return await run();
|
|
30
|
+
}
|
|
31
|
+
catch (err) {
|
|
32
|
+
if (isMissingObjectError(err))
|
|
33
|
+
return [];
|
|
34
|
+
throw err;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
//# sourceMappingURL=missingObject.js.map
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { AuditContext } from '@cclabsnz/sf-core';
|
|
2
|
+
/**
|
|
3
|
+
* Which fields an object has in this org, by describe (a GET, so read-only).
|
|
4
|
+
*
|
|
5
|
+
* Use it before querying a field that only some editions, licences or releases carry, such as a
|
|
6
|
+
* permission like PermissionsManageEventLogFiles. Querying an absent field fails the whole query;
|
|
7
|
+
* describing first lets a check say "not available in this org" instead of failing, and never
|
|
8
|
+
* lets the absence read as a pass.
|
|
9
|
+
*/
|
|
10
|
+
export type Api = 'soql' | 'tooling';
|
|
11
|
+
/** The object's field names, or null when this API does not serve the object in this org. */
|
|
12
|
+
export declare function fieldsOf(ctx: AuditContext, object: string, api?: Api): Promise<ReadonlySet<string> | null>;
|
|
13
|
+
/** The subset of `wanted` the object has, in the order given. Empty when the object is absent. */
|
|
14
|
+
export declare function presentFields(ctx: AuditContext, object: string, wanted: readonly string[], api?: Api): Promise<string[]>;
|
|
15
|
+
/** True when the object has the field. */
|
|
16
|
+
export declare function hasField(ctx: AuditContext, object: string, field: string, api?: Api): Promise<boolean>;
|
|
17
|
+
//# sourceMappingURL=schema.d.ts.map
|