@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.
Files changed (170) hide show
  1. package/CHANGELOG.md +172 -1
  2. package/PERMISSIONS.md +139 -0
  3. package/README.md +98 -26
  4. package/config/scoring.sample.json +104 -5
  5. package/docs/permissionset/SF_Audit_ReadOnly.permissionset-meta.xml +54 -0
  6. package/lib/apps/analyzeApps.d.ts +8 -2
  7. package/lib/apps/analyzeApps.js +7 -2
  8. package/lib/apps/apiLogSource.d.ts +39 -0
  9. package/lib/apps/apiLogSource.js +75 -0
  10. package/lib/apps/appResolver.js +30 -4
  11. package/lib/apps/grantedAccess.js +16 -3
  12. package/lib/apps/leastPrivilege.d.ts +3 -1
  13. package/lib/apps/leastPrivilege.js +7 -3
  14. package/lib/apps/permissionSetGenerator.d.ts +22 -0
  15. package/lib/apps/permissionSetGenerator.js +100 -0
  16. package/lib/apps/types.d.ts +6 -0
  17. package/lib/apps/usageCollector.d.ts +7 -1
  18. package/lib/apps/usageCollector.js +57 -26
  19. package/lib/chains/CapabilityRegistry.js +26 -0
  20. package/lib/chains/ChainEngine.js +11 -1
  21. package/lib/chains/namedChains.js +130 -24
  22. package/lib/checks/CheckEngine.d.ts +3 -1
  23. package/lib/checks/CheckEngine.js +65 -26
  24. package/lib/checks/impl/AgentUserPrivilegeCheck.js +5 -4
  25. package/lib/checks/impl/AnonymousApexAuditCheck.js +41 -8
  26. package/lib/checks/impl/ApexCrudFLSCheck.js +45 -10
  27. package/lib/checks/impl/ApexSharingCheck.js +19 -26
  28. package/lib/checks/impl/ApiClientPermissionCheck.js +21 -5
  29. package/lib/checks/impl/AuditTrailCheck.js +23 -8
  30. package/lib/checks/impl/AuthProviderRegistrationHandlerCheck.d.ts +10 -0
  31. package/lib/checks/impl/AuthProviderRegistrationHandlerCheck.js +131 -0
  32. package/lib/checks/impl/CertificateExpiryCheck.js +2 -1
  33. package/lib/checks/impl/ConnectedAppScopeCheck.js +61 -5
  34. package/lib/checks/impl/ConnectedAppsCheck.js +60 -5
  35. package/lib/checks/impl/ContentLinksCheck.js +33 -9
  36. package/lib/checks/impl/CorsAllowlistCheck.js +3 -2
  37. package/lib/checks/impl/DataClassificationCheck.js +15 -13
  38. package/lib/checks/impl/DataCloudDataSpaceIsolationCheck.d.ts +10 -0
  39. package/lib/checks/impl/DataCloudDataSpaceIsolationCheck.js +116 -0
  40. package/lib/checks/impl/DebugLogAccessCheck.js +4 -4
  41. package/lib/checks/impl/DelegatedAdministrationGroupsCheck.d.ts +10 -0
  42. package/lib/checks/impl/DelegatedAdministrationGroupsCheck.js +76 -0
  43. package/lib/checks/impl/DelegatedAuthenticationExposureCheck.d.ts +10 -0
  44. package/lib/checks/impl/DelegatedAuthenticationExposureCheck.js +105 -0
  45. package/lib/checks/impl/DeploymentIdentityCheck.js +32 -5
  46. package/lib/checks/impl/EmailSecurityCheck.d.ts +1 -1
  47. package/lib/checks/impl/EmailSecurityCheck.js +14 -34
  48. package/lib/checks/impl/EncryptionCoverageCheck.js +21 -15
  49. package/lib/checks/impl/EnhancedDomainsCheck.js +17 -2
  50. package/lib/checks/impl/EscalationPermsCheck.d.ts +2 -0
  51. package/lib/checks/impl/EscalationPermsCheck.js +88 -21
  52. package/lib/checks/impl/ExperienceCloudSiteCheck.js +56 -5
  53. package/lib/checks/impl/ExternalAccountHierarchyExposureCheck.d.ts +10 -0
  54. package/lib/checks/impl/ExternalAccountHierarchyExposureCheck.js +65 -0
  55. package/lib/checks/impl/ExternalCredentialsCheck.js +6 -3
  56. package/lib/checks/impl/FailedLoginCheck.js +36 -9
  57. package/lib/checks/impl/FieldHistoryTrackingCheck.js +14 -11
  58. package/lib/checks/impl/FlowHttpCalloutCredentialBypassCheck.d.ts +10 -0
  59. package/lib/checks/impl/FlowHttpCalloutCredentialBypassCheck.js +115 -0
  60. package/lib/checks/impl/GenAiPromptTemplateGroundingCheck.d.ts +10 -0
  61. package/lib/checks/impl/GenAiPromptTemplateGroundingCheck.js +227 -0
  62. package/lib/checks/impl/GuestExecutableApexCheck.d.ts +1 -1
  63. package/lib/checks/impl/GuestExecutableApexCheck.js +105 -14
  64. package/lib/checks/impl/GuestRecordAccessPolicyCheck.js +52 -11
  65. package/lib/checks/impl/HardcodedCredentialsCheck.js +7 -2
  66. package/lib/checks/impl/HealthCheckCheck.js +1 -0
  67. package/lib/checks/impl/HighAssuranceSessionCheck.js +16 -11
  68. package/lib/checks/impl/InactiveUsersCheck.js +1 -1
  69. package/lib/checks/impl/InboundEmailHandlerExposureCheck.d.ts +10 -0
  70. package/lib/checks/impl/InboundEmailHandlerExposureCheck.js +136 -0
  71. package/lib/checks/impl/IntegrationLeastPrivilegeCheck.js +7 -6
  72. package/lib/checks/impl/InternalUserMfaCheck.js +26 -8
  73. package/lib/checks/impl/IpRestrictionsCheck.js +35 -16
  74. package/lib/checks/impl/LoginAccessPolicyCheck.js +5 -4
  75. package/lib/checks/impl/LoginAnomalyCheck.js +10 -7
  76. package/lib/checks/impl/LoginSessionCheck.js +2 -0
  77. package/lib/checks/impl/MfaEnforcementCheck.js +23 -6
  78. package/lib/checks/impl/MfaMethodStrengthCheck.js +18 -3
  79. package/lib/checks/impl/MfaRegistrationCheck.js +4 -3
  80. package/lib/checks/impl/MyDomainLoginPolicyCheck.js +23 -10
  81. package/lib/checks/impl/OauthDeviceAndAssetTokenFlowsCheck.d.ts +10 -0
  82. package/lib/checks/impl/OauthDeviceAndAssetTokenFlowsCheck.js +84 -0
  83. package/lib/checks/impl/OrgWideEmailSpoofingCheck.d.ts +10 -0
  84. package/lib/checks/impl/OrgWideEmailSpoofingCheck.js +106 -0
  85. package/lib/checks/impl/OutboundMessagesCheck.js +48 -6
  86. package/lib/checks/impl/PackagePostInstallSupplyChainCheck.d.ts +10 -0
  87. package/lib/checks/impl/PackagePostInstallSupplyChainCheck.js +89 -0
  88. package/lib/checks/impl/PlatformEventSubscriberContextCheck.d.ts +10 -0
  89. package/lib/checks/impl/PlatformEventSubscriberContextCheck.js +88 -0
  90. package/lib/checks/impl/PrivilegedAccessCheck.js +12 -5
  91. package/lib/checks/impl/ReleaseUpdatesCheck.js +18 -3
  92. package/lib/checks/impl/RemoteSitesCheck.js +4 -4
  93. package/lib/checks/impl/RestrictionRulesIntegrityCheck.d.ts +10 -0
  94. package/lib/checks/impl/RestrictionRulesIntegrityCheck.js +105 -0
  95. package/lib/checks/impl/SeparationOfDutiesCheck.js +14 -3
  96. package/lib/checks/impl/ShieldTenantSecretLifecycleCheck.d.ts +10 -0
  97. package/lib/checks/impl/ShieldTenantSecretLifecycleCheck.js +90 -0
  98. package/lib/checks/impl/SoapLoginApiAuthCheck.js +20 -8
  99. package/lib/checks/impl/SsoEnforcementCheck.js +16 -5
  100. package/lib/checks/impl/TransactionSecurityPolicyCheck.js +5 -5
  101. package/lib/checks/impl/TrustedIPRangesCheck.js +18 -9
  102. package/lib/checks/impl/UsersAndAdminsCheck.js +24 -4
  103. package/lib/checks/permCatalog.js +1 -1
  104. package/lib/checks/registry.js +30 -0
  105. package/lib/checks/support/apexAccess.d.ts +56 -0
  106. package/lib/checks/support/apexAccess.js +127 -0
  107. package/lib/checks/support/missingObject.d.ts +13 -0
  108. package/lib/checks/support/missingObject.js +37 -0
  109. package/lib/checks/support/schema.d.ts +17 -0
  110. package/lib/checks/support/schema.js +41 -0
  111. package/lib/commands/audit/apps.d.ts +1 -0
  112. package/lib/commands/audit/apps.js +86 -30
  113. package/lib/commands/audit/diff.js +2 -2
  114. package/lib/commands/audit/events/pull.js +3 -1
  115. package/lib/commands/audit/history.js +2 -2
  116. package/lib/commands/audit/incident/collect.js +3 -1
  117. package/lib/commands/audit/incident/report.js +2 -2
  118. package/lib/commands/audit/security.d.ts +3 -0
  119. package/lib/commands/audit/security.js +65 -10
  120. package/lib/commands/audit/timeline.js +2 -2
  121. package/lib/compliance/mapping.js +28 -7
  122. package/lib/findings/AuditResult.d.ts +10 -0
  123. package/lib/findings/CheckMeta.js +15 -0
  124. package/lib/findings/Finding.d.ts +4 -0
  125. package/lib/findings/ScoringConfig.d.ts +10 -8
  126. package/lib/findings/ScoringConfig.js +12 -5
  127. package/lib/findings/coverage.d.ts +34 -0
  128. package/lib/findings/coverage.js +42 -0
  129. package/lib/findings/exitCode.js +1 -1
  130. package/lib/findings/loadScoringConfig.js +51 -8
  131. package/lib/findings/scoring.js +61 -10
  132. package/lib/history/HistoryStore.js +9 -3
  133. package/lib/history/archivePolicy.d.ts +19 -0
  134. package/lib/history/archivePolicy.js +34 -0
  135. package/lib/incident/bundleIo.js +4 -3
  136. package/lib/incident/collect/collectBundle.d.ts +1 -1
  137. package/lib/incident/collect/collectBundle.js +4 -3
  138. package/lib/incident/collect/streamGuestLogs.d.ts +1 -1
  139. package/lib/incident/collect/streamGuestLogs.js +3 -2
  140. package/lib/incident/csv.js +4 -4
  141. package/lib/incident/render/evidence.js +3 -3
  142. package/lib/incident/render/html.js +2 -3
  143. package/lib/index.d.ts +2 -0
  144. package/lib/index.js +2 -0
  145. package/lib/lib/packageInfo.d.ts +6 -0
  146. package/lib/lib/packageInfo.js +19 -0
  147. package/lib/preflight/permissionMap.d.ts +2 -20
  148. package/lib/preflight/permissionMap.js +2 -43
  149. package/lib/preflight/permissions.d.ts +25 -0
  150. package/lib/preflight/permissions.js +50 -0
  151. package/lib/renderers/AttackChainDagRenderer.d.ts +7 -0
  152. package/lib/renderers/AttackChainDagRenderer.js +139 -0
  153. package/lib/renderers/ClientReportRenderer.d.ts +2 -0
  154. package/lib/renderers/ClientReportRenderer.js +34 -6
  155. package/lib/renderers/DiffHtmlRenderer.js +2 -7
  156. package/lib/renderers/HistoryRenderer.js +19 -11
  157. package/lib/renderers/HtmlRenderer.js +23 -6
  158. package/lib/renderers/MarkdownRenderer.js +11 -1
  159. package/lib/renderers/SarifRenderer.d.ts +43 -0
  160. package/lib/renderers/SarifRenderer.js +250 -0
  161. package/lib/report/ExecutivePriorities.js +1 -1
  162. package/lib/report/RemediationRoadmap.d.ts +5 -1
  163. package/lib/report/RemediationRoadmap.js +6 -2
  164. package/lib/waivers/WaiverLoader.d.ts +28 -0
  165. package/lib/waivers/WaiverLoader.js +103 -0
  166. package/lib/waivers/WaiverModel.d.ts +32 -0
  167. package/lib/waivers/WaiverModel.js +28 -0
  168. package/lib/waivers/applyWaivers.d.ts +22 -0
  169. package/lib/waivers/applyWaivers.js +85 -0
  170. package/package.json +6 -4
@@ -1,3 +1,6 @@
1
+ // The endpoint and the session-ID flag live only in the Metadata column, which the Tooling API
2
+ // returns one record at a time, so each message is fetched by id, up to this many.
3
+ const MAX_RECORD_READS = 100;
1
4
  export class OutboundMessagesCheck {
2
5
  id = 'outbound-messages';
3
6
  name = 'Workflow Outbound Messages';
@@ -6,9 +9,9 @@ export class OutboundMessagesCheck {
6
9
  async run(ctx) {
7
10
  const findings = [];
8
11
  const setupUrl = `${ctx.orgInfo.instanceUrl}/lightning/setup/WorkflowOutboundMessaging/home`;
9
- let rows;
12
+ let listed;
10
13
  try {
11
- rows = await ctx.tooling.query('SELECT Id, Name, EndpointUrl, IncludeSessionId FROM WorkflowOutboundMessage');
14
+ listed = await ctx.tooling.query('SELECT Id, Name FROM WorkflowOutboundMessage');
12
15
  }
13
16
  catch (err) {
14
17
  const msg = err instanceof Error ? err.message : String(err);
@@ -18,12 +21,51 @@ export class OutboundMessagesCheck {
18
21
  riskLevel: 'INFO',
19
22
  inconclusive: true,
20
23
  title: 'Workflow outbound messages could not be read',
21
- detail: `The WorkflowOutboundMessage Tooling query was not accessible: ${msg}`,
24
+ detail: `The WorkflowOutboundMessage Tooling query failed: ${msg}`,
22
25
  remediation: 'Grant the audit user "View Setup and Configuration", then re-run the audit.',
23
26
  });
24
27
  return { findings };
25
28
  }
26
- if (rows.length === 0) {
29
+ const rows = [];
30
+ const unread = [];
31
+ for (const [i, row] of listed.entries()) {
32
+ let meta;
33
+ if (i < MAX_RECORD_READS) {
34
+ try {
35
+ const rec = await ctx.tooling.getRecord('WorkflowOutboundMessage', row.Id);
36
+ meta = rec?.Metadata ?? undefined;
37
+ }
38
+ catch {
39
+ meta = undefined;
40
+ }
41
+ }
42
+ if (meta && typeof meta.endpointUrl === 'string') {
43
+ rows.push({
44
+ ...row,
45
+ EndpointUrl: meta.endpointUrl,
46
+ IncludeSessionId: meta.includeSessionId === true || meta.includeSessionId === 'true',
47
+ });
48
+ }
49
+ else
50
+ unread.push(row);
51
+ }
52
+ // A message whose definition could not be read is unassessed, and keeps the inventory from passing.
53
+ if (unread.length > 0) {
54
+ findings.push({
55
+ id: 'outbound-messages-unread',
56
+ category: this.category,
57
+ riskLevel: 'INFO',
58
+ inconclusive: true,
59
+ title: `${unread.length} outbound message(s) could not be read`,
60
+ detail: 'Their endpoint and Include Session ID settings were not returned by the Tooling API ' +
61
+ `(reads stop after ${MAX_RECORD_READS} messages), so they are unassessed, not clean.`,
62
+ remediation: 'Review these outbound messages in Setup → Outbound Messages.',
63
+ affectedItems: unread.map((r) => ({ label: r.Name, url: setupUrl })),
64
+ });
65
+ if (rows.length === 0)
66
+ return { findings };
67
+ }
68
+ if (listed.length === 0) {
27
69
  findings.push({
28
70
  id: 'outbound-messages-none',
29
71
  category: this.category,
@@ -71,8 +113,8 @@ export class OutboundMessagesCheck {
71
113
  findings.push({
72
114
  id: 'outbound-messages-inventory',
73
115
  category: this.category,
74
- riskLevel: sessionId.length === 0 && cleartext.length === 0 ? 'LOW' : 'INFO',
75
- passed: sessionId.length === 0 && cleartext.length === 0 ? true : undefined,
116
+ riskLevel: sessionId.length === 0 && cleartext.length === 0 && unread.length === 0 ? 'LOW' : 'INFO',
117
+ passed: sessionId.length === 0 && cleartext.length === 0 && unread.length === 0 ? true : undefined,
76
118
  title: `${rows.length} workflow outbound message(s) configured (${sessionId.length} include session ID, ${cleartext.length} cleartext)`,
77
119
  detail: 'Outbound messages POST record data to external endpoints automatically. Each destination should be a reviewed, currently-used HTTPS integration.',
78
120
  remediation: 'Audit each outbound message endpoint to confirm it is still used and points to a trusted HTTPS destination. Remove unused entries.',
@@ -0,0 +1,10 @@
1
+ import type { AuditContext } from '@cclabsnz/sf-core';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class PackagePostInstallSupplyChainCheck implements SecurityCheck {
4
+ readonly id = "package-post-install-supply-chain";
5
+ readonly name = "Package Post-Install Supply Chain Risk";
6
+ readonly category = "Platform Hygiene";
7
+ readonly description = "Finds packaged Apex implementing InstallHandler, which runs in system context on every install and push upgrade.";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=PackagePostInstallSupplyChainCheck.d.ts.map
@@ -0,0 +1,89 @@
1
+ import { isMissingObjectError } from '../support/missingObject.js';
2
+ // Managed-package Apex is returned with its body replaced by this marker, so whether such a
3
+ // class implements InstallHandler cannot be read from the org.
4
+ const HIDDEN_BODY = '(hidden)';
5
+ const IMPLEMENTS_INSTALL_HANDLER = /\bimplements\b[^{]*\bInstallHandler\b/i;
6
+ export class PackagePostInstallSupplyChainCheck {
7
+ id = 'package-post-install-supply-chain';
8
+ name = 'Package Post-Install Supply Chain Risk';
9
+ category = 'Platform Hygiene';
10
+ description = 'Finds packaged Apex implementing InstallHandler, which runs in system context on every install and push upgrade.';
11
+ async run(ctx) {
12
+ const findings = [];
13
+ const packagesUrl = `${ctx.orgInfo.instanceUrl}/lightning/setup/ImportedPackage/home`;
14
+ let installedPackages;
15
+ try {
16
+ installedPackages = await ctx.tooling.query('SELECT Id, SubscriberPackageId FROM InstalledSubscriberPackage');
17
+ }
18
+ catch (err) {
19
+ if (!isMissingObjectError(err))
20
+ throw err;
21
+ installedPackages = [];
22
+ }
23
+ if (installedPackages.length === 0) {
24
+ findings.push({
25
+ id: 'package-post-install-ok',
26
+ category: this.category,
27
+ riskLevel: 'LOW',
28
+ passed: true,
29
+ title: 'No installed subscriber packages found in org',
30
+ detail: 'Zero InstalledSubscriberPackage records were identified.',
31
+ remediation: 'Continue inventorying new packages when installed.',
32
+ });
33
+ return { findings };
34
+ }
35
+ const namespacedClasses = await ctx.tooling.query('SELECT Id, Name, NamespacePrefix, Body FROM ApexClass WHERE NamespacePrefix != null');
36
+ const handlers = [];
37
+ const hiddenNamespaces = new Set();
38
+ for (const c of namespacedClasses) {
39
+ const classBody = c.Body ?? '';
40
+ if (classBody.trim() === HIDDEN_BODY || classBody === '') {
41
+ if (c.NamespacePrefix)
42
+ hiddenNamespaces.add(c.NamespacePrefix);
43
+ }
44
+ else if (IMPLEMENTS_INSTALL_HANDLER.test(classBody)) {
45
+ handlers.push(c);
46
+ }
47
+ }
48
+ if (handlers.length > 0) {
49
+ findings.push({
50
+ id: 'package-post-install-system-script',
51
+ category: this.category,
52
+ riskLevel: 'MEDIUM',
53
+ title: `${handlers.length} packaged class(es) implement InstallHandler and run on install and upgrade`,
54
+ detail: 'A class implementing InstallHandler runs unattended Apex in system context whenever its package is installed or upgraded, including vendor push upgrades. That execution bypasses admin approval and change-management gates.',
55
+ remediation: 'Review what each post-install script does, confirm the vendor publishes it, and agree a push-upgrade schedule with the vendor.',
56
+ affectedItems: handlers.map((c) => ({
57
+ label: `${c.NamespacePrefix}.${c.Name}`,
58
+ url: packagesUrl,
59
+ note: 'Implements InstallHandler',
60
+ })),
61
+ });
62
+ }
63
+ if (hiddenNamespaces.size > 0) {
64
+ const namespaces = [...hiddenNamespaces].sort();
65
+ findings.push({
66
+ id: 'package-post-install-unverifiable',
67
+ category: this.category,
68
+ riskLevel: 'INFO',
69
+ title: `${namespaces.length} managed package namespace(s) hide their Apex, so post-install scripts cannot be checked`,
70
+ detail: 'Managed packages hide their Apex source, so this run cannot tell whether any of them implements InstallHandler. A package that does runs Apex in system context on every install and push upgrade.',
71
+ remediation: 'Ask each vendor whether the package runs a post-install script and what it does, and review push-upgrade notices before they apply.',
72
+ affectedItems: namespaces.map((ns) => ({ label: `Namespace: ${ns}`, url: packagesUrl })),
73
+ });
74
+ }
75
+ if (handlers.length === 0 && hiddenNamespaces.size === 0) {
76
+ findings.push({
77
+ id: 'package-post-install-ok',
78
+ category: this.category,
79
+ riskLevel: 'LOW',
80
+ passed: true,
81
+ title: 'No post-install scripts found in installed packages',
82
+ detail: `${installedPackages.length} package(s) installed; none of their readable Apex implements InstallHandler.`,
83
+ remediation: 'Review post-install scripts and permissions whenever new packages are installed.',
84
+ });
85
+ }
86
+ return { findings };
87
+ }
88
+ }
89
+ //# sourceMappingURL=PackagePostInstallSupplyChainCheck.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 PlatformEventSubscriberContextCheck implements SecurityCheck {
4
+ readonly id = "platform-event-subscriber-context";
5
+ readonly name = "Platform Event Subscriber Context & Privilege Escalation";
6
+ readonly category = "Code Security";
7
+ readonly description = "Detects Platform Event subscribers executing in system context or as Admin while low-trust or guest users hold Publish permissions.";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=PlatformEventSubscriberContextCheck.d.ts.map
@@ -0,0 +1,88 @@
1
+ export class PlatformEventSubscriberContextCheck {
2
+ id = 'platform-event-subscriber-context';
3
+ name = 'Platform Event Subscriber Context & Privilege Escalation';
4
+ category = 'Code Security';
5
+ description = 'Detects Platform Event subscribers executing in system context or as Admin while low-trust or guest users hold Publish permissions.';
6
+ async run(ctx) {
7
+ const findings = [];
8
+ const baseUrl = ctx.orgInfo.instanceUrl;
9
+ // ApexTrigger exists in every org, so a failure here is never "feature absent". It propagates
10
+ // and CheckEngine reports the check as inconclusive.
11
+ const triggers = await ctx.tooling.query("SELECT Id, Name, TableEnumOrId, Status FROM ApexTrigger WHERE Status = 'Active'");
12
+ // TableEnumOrId holds a standard object's name, but a custom object's (and so every custom
13
+ // platform event's) 01I Id. Resolve Ids to API names before testing for the __e suffix.
14
+ const ids = [...new Set(triggers.map((t) => t.TableEnumOrId).filter((v) => !v.includes('_') && v.startsWith('01I')))];
15
+ const nameById = new Map();
16
+ if (ids.length > 0) {
17
+ const defs = await ctx.tooling.query(`SELECT DurableId, QualifiedApiName FROM EntityDefinition WHERE DurableId IN (${ids.map((i) => `'${i.slice(0, 15)}'`).join(', ')})`);
18
+ for (const d of defs)
19
+ nameById.set(d.DurableId.slice(0, 15), d.QualifiedApiName);
20
+ }
21
+ const objectName = (t) => nameById.get(t.TableEnumOrId.slice(0, 15)) ?? t.TableEnumOrId;
22
+ const eventTriggers = triggers.filter((t) => objectName(t).endsWith('__e'));
23
+ if (eventTriggers.length === 0) {
24
+ findings.push({
25
+ id: 'platform-event-subscriber-context-ok',
26
+ category: this.category,
27
+ riskLevel: 'LOW',
28
+ passed: true,
29
+ title: 'No active triggers on custom Platform Events identified',
30
+ detail: 'Zero active Apex triggers subscribe to custom Platform Event objects (__e).',
31
+ remediation: 'When subscribing to Platform Events, ensure publish permissions are strictly scoped to internal authorized actors.',
32
+ });
33
+ return { findings };
34
+ }
35
+ // Low-trust profiles (guest, portal, Experience Cloud) holding Create on a subscribed event.
36
+ // ObjectPermissions.ParentId is a PermissionSet Id, so each profile is reached through the
37
+ // permission set it owns.
38
+ const eventObjectNames = new Set(eventTriggers.map(objectName));
39
+ const lowTrustProfilesWithCreate = [];
40
+ const profiles = await ctx.soql.queryAll("SELECT Id, Name, UserType FROM Profile WHERE UserType IN ('Guest', 'CspLitePortal', 'PowerPartner', 'CustomerSuccess', 'PowerCustomerSuccess')");
41
+ if (profiles.length > 0) {
42
+ const profileNameById = new Map(profiles.map((p) => [p.Id, p.Name]));
43
+ const owned = await ctx.soql.queryAll(`SELECT Id, ProfileId FROM PermissionSet WHERE IsOwnedByProfile = true AND ProfileId IN (${profiles.map((p) => `'${p.Id}'`).join(', ')})`);
44
+ const profileByPermSet = new Map(owned.map((ps) => [ps.Id, ps.ProfileId]));
45
+ // SobjectType does not accept LIKE ("invalid operator on id field"): select these profiles'
46
+ // Create grants and keep the platform events (__e) in code.
47
+ const objectPerms = owned.length === 0
48
+ ? []
49
+ : await ctx.soql.queryAll(`SELECT Id, ParentId, SobjectType, PermissionsCreate FROM ObjectPermissions WHERE PermissionsCreate = true AND ParentId IN (${owned.map((ps) => `'${ps.Id}'`).join(', ')})`);
50
+ for (const op of objectPerms) {
51
+ const profileId = profileByPermSet.get(op.ParentId);
52
+ if (profileId && eventObjectNames.has(op.SobjectType)) {
53
+ lowTrustProfilesWithCreate.push(`${op.SobjectType} (${profileNameById.get(profileId) ?? profileId})`);
54
+ }
55
+ }
56
+ }
57
+ // If low-trust profiles have Create permission on any custom platform event subscribed to by Apex:
58
+ // This is an unauthenticated or portal-to-system privilege escalation bridge!
59
+ if (lowTrustProfilesWithCreate.length > 0) {
60
+ findings.push({
61
+ id: 'platform-event-subscriber-escalation',
62
+ category: this.category,
63
+ riskLevel: 'CRITICAL',
64
+ title: `${lowTrustProfilesWithCreate.length} Platform Event(s) publishable by low-trust users trigger system-mode subscribers`,
65
+ detail: 'Guest or Experience Cloud profiles hold Create (publish) permissions on custom Platform Events that have active Apex subscribers. By default, Platform Event triggers execute under the Automated Process system identity (bypassing user permissions and sharing), creating an unauthenticated-to-system-context privilege escalation bridge.',
66
+ remediation: 'Revoke Create permissions on Platform Events from guest and portal profiles, or configure PlatformEventSubscriberConfig to run subscribers as a dedicated, least-privileged service account with explicit input validation.',
67
+ affectedItems: lowTrustProfilesWithCreate.map((item) => ({
68
+ label: item,
69
+ url: `${baseUrl}/lightning/setup/EventObjects/home`,
70
+ note: 'Event publishable by low-trust actor executes as Automated Process or Admin',
71
+ })),
72
+ });
73
+ }
74
+ else {
75
+ findings.push({
76
+ id: 'platform-event-subscriber-context-ok',
77
+ category: this.category,
78
+ riskLevel: 'LOW',
79
+ passed: true,
80
+ title: 'Platform Event subscriber triggers are protected from low-trust publish escalation',
81
+ detail: `${eventTriggers.length} active Platform Event trigger(s) inspected; no guest or portal profiles hold Publish permissions on subscribed events.`,
82
+ remediation: 'Ensure low-trust profiles never receive Create permissions on custom Platform Events that execute privileged backend logic.',
83
+ });
84
+ }
85
+ return { findings };
86
+ }
87
+ }
88
+ //# sourceMappingURL=PlatformEventSubscriberContextCheck.js.map
@@ -1,4 +1,5 @@
1
1
  import { DANGEROUS_PERMS } from '../permCatalog.js';
2
+ import { presentFields } from '../support/schema.js';
2
3
  const ADMIN_PROFILE = 'System Administrator';
3
4
  /** Admin-equivalent = holds Modify All Data, OR can self-escalate to it (Manage Users + Assign Permission Sets). */
4
5
  function isAdminEquivalent(perms) {
@@ -13,10 +14,16 @@ export class PrivilegedAccessCheck {
13
14
  async run(ctx) {
14
15
  const findings = [];
15
16
  const setupUrl = `${ctx.orgInfo.instanceUrl}/lightning/setup/ManageUsers/home`;
16
- const permFields = DANGEROUS_PERMS.map((p) => `PermissionSet.${p.field}`).join(', ');
17
- const permWhere = DANGEROUS_PERMS.map((p) => `PermissionSet.${p.field} = true`).join(' OR ');
18
17
  let rows;
18
+ // Some catalogued permissions exist only with a licence or feature (Event Monitoring, API
19
+ // Access Control). One absent field fails the whole query, so select only those this org
20
+ // has. A permission the org lacks cannot be held, so leaving it out loses nothing.
21
+ let perms = DANGEROUS_PERMS;
19
22
  try {
23
+ const present = new Set(await presentFields(ctx, 'PermissionSet', DANGEROUS_PERMS.map((p) => p.field)));
24
+ perms = DANGEROUS_PERMS.filter((p) => present.has(p.field));
25
+ const permFields = perms.map((p) => `PermissionSet.${p.field}`).join(', ');
26
+ const permWhere = perms.map((p) => `PermissionSet.${p.field} = true`).join(' OR ');
20
27
  rows = await ctx.soql.queryAll(`SELECT AssigneeId, Assignee.Username, Assignee.Name, Assignee.Profile.Name, ${permFields}
21
28
  FROM PermissionSetAssignment
22
29
  WHERE (${permWhere}) AND Assignee.IsActive = true`);
@@ -29,8 +36,8 @@ export class PrivilegedAccessCheck {
29
36
  riskLevel: 'INFO',
30
37
  inconclusive: true,
31
38
  title: 'Effective-permission resolution could not be completed',
32
- detail: `The PermissionSetAssignment query was not accessible: ${msg}`,
33
- remediation: 'Grant the audit user "View Setup and Configuration" and "View All Users", then re-run the audit.',
39
+ detail: `Effective permissions could not be read, so privileged access is unassessed. The org said: ${msg}`,
40
+ remediation: 'Check the error above. If it is an access error, confirm the audit user has "View Setup and Configuration" and "View All Users", then re-run the audit.',
34
41
  });
35
42
  return { findings };
36
43
  }
@@ -39,7 +46,7 @@ export class PrivilegedAccessCheck {
39
46
  const byUser = new Map();
40
47
  for (const row of rows) {
41
48
  const ps = row.PermissionSet ?? {};
42
- const held = DANGEROUS_PERMS.filter((p) => ps[p.field]).map((p) => p.key);
49
+ const held = perms.filter((p) => ps[p.field]).map((p) => p.key);
43
50
  if (held.length === 0)
44
51
  continue;
45
52
  let g = byUser.get(row.AssigneeId);
@@ -1,3 +1,4 @@
1
+ import { fieldsOf } from '../support/schema.js';
1
2
  export class ReleaseUpdatesCheck {
2
3
  id = 'release-updates';
3
4
  name = 'Pending Release Updates';
@@ -9,16 +10,30 @@ export class ReleaseUpdatesCheck {
9
10
  const today = new Date();
10
11
  let pendingUpdates = [];
11
12
  try {
12
- pendingUpdates = await ctx.tooling.query('SELECT Id, Name, Description, AutoActivationDate, IsEnabled FROM CriticalUpdate WHERE IsEnabled = false');
13
+ // Current orgs expose Release Updates as Tooling ReleaseUpdate; CriticalUpdate is the older
14
+ // object, absent from current releases. Use whichever this org serves.
15
+ if (await fieldsOf(ctx, 'ReleaseUpdate', 'tooling')) {
16
+ const rows = await ctx.tooling.query("SELECT Id, DeveloperName, Title, Description, DueDate, Status FROM ReleaseUpdate WHERE Status IN ('Invocable', 'Revoked')");
17
+ pendingUpdates = rows.map((r) => ({
18
+ Id: r.Id,
19
+ Name: r.Title || r.DeveloperName,
20
+ Description: r.Description,
21
+ AutoActivationDate: r.DueDate,
22
+ IsEnabled: false,
23
+ }));
24
+ }
25
+ else {
26
+ pendingUpdates = await ctx.tooling.query('SELECT Id, Name, Description, AutoActivationDate, IsEnabled FROM CriticalUpdate WHERE IsEnabled = false');
27
+ }
13
28
  }
14
- catch {
29
+ catch (err) {
15
30
  findings.push({
16
31
  id: 'release-updates-inconclusive',
17
32
  category: this.category,
18
33
  riskLevel: 'INFO',
19
34
  inconclusive: true,
20
35
  title: 'Pending release updates check could not be completed',
21
- detail: 'The CriticalUpdate Tooling API object was not accessible. This can occur if the audit user lacks the "Customize Application" permission or if the org is on a restricted edition.',
36
+ detail: `Pending release updates could not be read, so this is unassessed, not clean. The org said: ${err instanceof Error ? err.message : String(err)}`,
22
37
  remediation: 'Review pending Release Updates manually in Setup → Release Updates.',
23
38
  });
24
39
  return { findings };
@@ -9,13 +9,13 @@ export class RemoteSitesCheck {
9
9
  const baseUrl = ctx.orgInfo.instanceUrl;
10
10
  const setupUrl = `${baseUrl}/lightning/setup/SecurityRemoteProxy/home`;
11
11
  // Query active remote site settings using Tooling API
12
- const records = await ctx.tooling.query('SELECT Id, SiteName, EndpointUrl, IsActive, DisableProtocolSecurity FROM RemoteProxy WHERE IsActive = true');
12
+ const records = await ctx.tooling.query('SELECT Id, SiteName, EndpointUrl, IsActive, ProtocolMismatch FROM RemoteProxy WHERE IsActive = true');
13
13
  const count = records.length;
14
14
  // Cache the URLs for use by HardcodedCredentialsCheck
15
15
  ctx.cache.remoteSiteUrls = records.map((r) => r.EndpointUrl);
16
16
  // Flag sites with protocol security disabled — these allow insecure HTTP callouts
17
- const insecureSites = records.filter((r) => r.DisableProtocolSecurity);
18
- const secureSites = records.filter((r) => !r.DisableProtocolSecurity);
17
+ const insecureSites = records.filter((r) => r.ProtocolMismatch);
18
+ const secureSites = records.filter((r) => !r.ProtocolMismatch);
19
19
  if (insecureSites.length > 0) {
20
20
  findings.push({
21
21
  id: 'remote-sites-protocol-security-disabled',
@@ -44,7 +44,7 @@ export class RemoteSitesCheck {
44
44
  affectedItems: records.map((r) => ({
45
45
  label: r.SiteName,
46
46
  url: setupUrl,
47
- note: `${r.EndpointUrl}${r.DisableProtocolSecurity ? ' ⚠ Protocol security disabled' : ''}`,
47
+ note: `${r.EndpointUrl}${r.ProtocolMismatch ? ' ⚠ Protocol security disabled' : ''}`,
48
48
  })),
49
49
  });
50
50
  }
@@ -0,0 +1,10 @@
1
+ import type { AuditContext } from '@cclabsnz/sf-core';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class RestrictionRulesIntegrityCheck implements SecurityCheck {
4
+ readonly id = "restriction-rules-integrity";
5
+ readonly name = "Restriction Rules Integrity & Conflict Detection";
6
+ readonly category = "Data Security";
7
+ readonly description = "Detects inactive or conflicting Restriction Rules on sensitive standard and custom objects.";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=RestrictionRulesIntegrityCheck.d.ts.map
@@ -0,0 +1,105 @@
1
+ import { isMissingObjectError } from '../support/missingObject.js';
2
+ export class RestrictionRulesIntegrityCheck {
3
+ id = 'restriction-rules-integrity';
4
+ name = 'Restriction Rules Integrity & Conflict Detection';
5
+ category = 'Data Security';
6
+ description = 'Detects inactive or conflicting Restriction Rules on sensitive standard and custom objects.';
7
+ async run(ctx) {
8
+ const findings = [];
9
+ const baseUrl = ctx.orgInfo.instanceUrl;
10
+ const rulesUrl = `${baseUrl}/lightning/setup/ObjectManager/home`;
11
+ let rules = [];
12
+ try {
13
+ rules = await ctx.tooling.query('SELECT Id, MasterLabel, TargetEntity, IsActive, EnforcementType FROM RestrictionRule');
14
+ }
15
+ catch (err) {
16
+ if (isMissingObjectError(err)) {
17
+ findings.push({
18
+ id: 'restriction-rules-integrity-ok',
19
+ category: this.category,
20
+ riskLevel: 'LOW',
21
+ passed: true,
22
+ title: 'Restriction Rules are not enabled or no rules configured',
23
+ detail: 'RestrictionRule tooling object is not accessible or not in use.',
24
+ remediation: 'No action required.',
25
+ });
26
+ return { findings };
27
+ }
28
+ findings.push({
29
+ id: 'restriction-rules-integrity-inaccessible',
30
+ category: this.category,
31
+ riskLevel: 'INFO',
32
+ inconclusive: true,
33
+ title: 'Restriction Rules could not be queried',
34
+ detail: `Failed to query RestrictionRule: ${err instanceof Error ? err.message : String(err)}`,
35
+ remediation: 'Grant the audit user "View Setup and Configuration" and Tooling API access.',
36
+ });
37
+ return { findings };
38
+ }
39
+ if (rules.length === 0) {
40
+ findings.push({
41
+ id: 'restriction-rules-integrity-ok',
42
+ category: this.category,
43
+ riskLevel: 'LOW',
44
+ passed: true,
45
+ title: 'No Restriction Rules configured',
46
+ detail: 'Zero RestrictionRule records configured across standard and custom objects.',
47
+ remediation: 'When deploying Restriction Rules, ensure they remain active and avoid multiple conflicting rules on the same entity.',
48
+ });
49
+ return { findings };
50
+ }
51
+ // 1. Check for inactive restriction rules
52
+ const inactiveRules = rules.filter((r) => r.IsActive === false);
53
+ if (inactiveRules.length > 0) {
54
+ findings.push({
55
+ id: 'restriction-rules-inactive',
56
+ category: this.category,
57
+ riskLevel: 'HIGH',
58
+ title: `${inactiveRules.length} inactive Restriction Rule(s) detected`,
59
+ detail: 'Inactive Restriction Rules (often disabled temporarily during testing or maintenance and forgotten) leave the underlying object protected only by Org-Wide Defaults. If the object OWD is Public Read/Write or Public Read Only, deactivating the Restriction Rule immediately and silently exposes the entire table to all users.',
60
+ remediation: 'Re-activate necessary Restriction Rules or delete obsolete rules to prevent false assumptions of record isolation.',
61
+ affectedItems: inactiveRules.map((r) => ({
62
+ label: `${r.TargetEntity}: ${r.MasterLabel || r.Name || r.Id}`,
63
+ url: rulesUrl,
64
+ note: 'Restriction Rule is INACTIVE',
65
+ })),
66
+ });
67
+ }
68
+ // 2. Check for multiple active rules on the same TargetEntity (Salesforce anti-pattern)
69
+ const activeRulesByEntity = new Map();
70
+ for (const r of rules.filter((r) => r.IsActive === true)) {
71
+ const list = activeRulesByEntity.get(r.TargetEntity) ?? [];
72
+ list.push(r);
73
+ activeRulesByEntity.set(r.TargetEntity, list);
74
+ }
75
+ const conflictingEntities = [...activeRulesByEntity.entries()].filter(([, entityRules]) => entityRules.length > 1);
76
+ if (conflictingEntities.length > 0) {
77
+ findings.push({
78
+ id: 'restriction-rules-conflicting',
79
+ category: this.category,
80
+ riskLevel: 'HIGH',
81
+ title: `${conflictingEntities.length} object(s) have multiple active Restriction Rules (conflicting evaluation)`,
82
+ detail: 'Salesforce Restriction Rules evaluate with first-match / OR logic across multiple rules. Defining multiple active restriction rules on the same object creates non-deterministic or overly broad access where a user matching any one rule gains visibility, breaking least-privilege scoping.',
83
+ remediation: 'Consolidate multiple Restriction Rules per entity into a single unified rule with clear record and user criteria.',
84
+ affectedItems: conflictingEntities.map(([entity, entityRules]) => ({
85
+ label: `${entity} (${entityRules.length} active rules)`,
86
+ url: rulesUrl,
87
+ note: `Multiple rules: ${entityRules.map((r) => r.MasterLabel || r.Name || r.Id).join(', ')}`,
88
+ })),
89
+ });
90
+ }
91
+ if (inactiveRules.length === 0 && conflictingEntities.length === 0) {
92
+ findings.push({
93
+ id: 'restriction-rules-integrity-ok',
94
+ category: this.category,
95
+ riskLevel: 'LOW',
96
+ passed: true,
97
+ title: 'All Restriction Rules are active with single-rule entity isolation',
98
+ detail: `${rules.length} Restriction Rule(s) inspected; all rules are active and no entity-level rule conflicts detected.`,
99
+ remediation: 'Maintain single active restriction rules per object.',
100
+ });
101
+ }
102
+ return { findings };
103
+ }
104
+ }
105
+ //# sourceMappingURL=RestrictionRulesIntegrityCheck.js.map
@@ -72,12 +72,20 @@ export class SeparationOfDutiesCheck {
72
72
  });
73
73
  return { findings };
74
74
  }
75
+ // A super-admin (Modify All Data + View All Data + Manage Users) already has unrestricted control,
76
+ // rated by users-super-admin-combo; a combination adds nothing for them. Rate the others, so the
77
+ // same users are not counted towards the grade again.
78
+ const isSuperAdmin = (g) => ['ModifyAllData', 'ViewAllData', 'ManageUsers'].every((p) => g.perms.includes(p));
75
79
  let anyViolation = false;
80
+ let superAdminHolders = 0;
76
81
  for (const combo of COMBOS) {
77
- const holders = grants.filter((g) => {
82
+ const all = grants.filter((g) => {
78
83
  const s = new Set(g.perms);
79
84
  return combo.perms.every((p) => s.has(p));
80
85
  });
86
+ const holders = all.filter((g) => !isSuperAdmin(g));
87
+ const leftOut = all.length - holders.length;
88
+ superAdminHolders = Math.max(superAdminHolders, leftOut);
81
89
  if (holders.length === 0)
82
90
  continue;
83
91
  anyViolation = true;
@@ -86,7 +94,8 @@ export class SeparationOfDutiesCheck {
86
94
  category: this.category,
87
95
  riskLevel: combo.risk,
88
96
  title: `${holders.length} user(s) hold a toxic permission combination: ${combo.label}`,
89
- detail: `${combo.why} Each permission may look acceptable in isolation, which is why combination review matters.`,
97
+ detail: `${combo.why} Each permission may look acceptable in isolation, which is why combination review matters.` +
98
+ (leftOut > 0 ? ` ${leftOut} super-admin(s) also hold it and are rated in the super-admin finding instead.` : ''),
90
99
  remediation: combo.fix,
91
100
  affectedItems: holders.map((g) => ({
92
101
  label: g.username,
@@ -104,7 +113,9 @@ export class SeparationOfDutiesCheck {
104
113
  title: 'No toxic permission combinations detected',
105
114
  detail: grants.length === 0
106
115
  ? 'No active users hold catalogued high-risk permissions, so no separation-of-duties conflicts arise.'
107
- : 'No active user holds a flagged combination of permissions that would violate separation of duties.',
116
+ : superAdminHolders > 0
117
+ ? `Only super-admins hold flagged combinations; they already have unrestricted control and are rated in the super-admin finding (users-super-admin-combo). No other active user holds a flagged combination.`
118
+ : 'No active user holds a flagged combination of permissions that would violate separation of duties.',
108
119
  remediation: 'Continue to separate user administration, code authorship, identity, and data-access duties across roles.',
109
120
  });
110
121
  }
@@ -0,0 +1,10 @@
1
+ import type { AuditContext } from '@cclabsnz/sf-core';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class ShieldTenantSecretLifecycleCheck implements SecurityCheck {
4
+ readonly id = "shield-tenant-secret-lifecycle";
5
+ readonly name = "Shield Platform Encryption Tenant Secret Lifecycle";
6
+ readonly category = "Data Security";
7
+ readonly description = "Monitors Shield TenantSecret rotation frequency (>365 days) and destroyed key status for cryptographic compliance.";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=ShieldTenantSecretLifecycleCheck.d.ts.map