@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,11 +1,27 @@
1
1
  import { ApexRepository } from '@cclabsnz/sf-core';
2
- const WITHOUT_SHARING = /\bwithout\s+sharing\b/i;
3
- const WITH_SHARING = /\bwith\s+sharing\b/i;
2
+ import { declaresWithoutSharing, effectiveSharing, parentClass, usesSystemMode } from '../support/apexAccess.js';
3
+ /**
4
+ * The org-local classes a class calls, as its compiled SymbolTable records them. A reference with a
5
+ * namespace is to packaged code, which the audit does not read, so it never resolves to a local
6
+ * class that happens to share its name.
7
+ */
8
+ function referencedClasses(symbolTable) {
9
+ const refs = symbolTable
10
+ ?.externalReferences;
11
+ if (!Array.isArray(refs))
12
+ return [];
13
+ return refs
14
+ .filter((r) => !(typeof r?.namespace === 'string' && r.namespace !== ''))
15
+ .map((r) => r?.name)
16
+ .filter((n) => typeof n === 'string' && n !== '')
17
+ // An inner class is referenced as Outer.Inner; its code lives in the outer class's body.
18
+ .map((n) => n.split('.')[0]);
19
+ }
4
20
  export class GuestExecutableApexCheck {
5
21
  id = 'guest-executable-apex';
6
22
  name = 'Guest-Executable Apex';
7
23
  category = 'Access Control';
8
- description = 'Finds Apex classes that unauthenticated guest profiles can execute, flagging those that run without sharing: the classic unauthenticated data-exfiltration vector';
24
+ description = 'Finds Apex classes that unauthenticated guest profiles can execute, flagging those that run without sharing, call a without-sharing helper, or switch off CRUD/FLS with SYSTEM_MODE';
9
25
  // Use cached Apex bodies (from HardcodedCredentialsCheck) when available to classify sharing.
10
26
  dependsOnCache = ['apexBodies'];
11
27
  async run(ctx) {
@@ -45,18 +61,75 @@ export class GuestExecutableApexCheck {
45
61
  // fails the whole query with "invalid ID field", losing every good row with it.
46
62
  const nameById = await new ApexRepository(ctx.tooling).namesByIds(classIds);
47
63
  const bodies = ctx.cache.apexBodies ?? [];
48
- const bodyByName = new Map(bodies.map((b) => [b.name, b.body]));
64
+ // Apex names are case-insensitive, and a SymbolTable may spell one differently from its declaration.
65
+ const byName = new Map(bodies.map((b) => [b.name.toLowerCase(), b]));
66
+ /**
67
+ * Everything reachable from `start` through SymbolTable references: whichever class is declared
68
+ * without sharing, at any depth, runs its own code without sharing (spec RULE-004), and SYSTEM_MODE
69
+ * anywhere on the path lifts CRUD/FLS for the guest (RULE-003).
70
+ */
71
+ const bodyOf = (n) => byName.get(n.toLowerCase())?.body;
72
+ // A class reaches what its SymbolTable references, and the class it extends: inherited methods
73
+ // run with the parent's own sharing.
74
+ const neighbours = (n) => {
75
+ const entry = byName.get(n.toLowerCase());
76
+ const parent = entry?.body ? parentClass(n, entry.body) : undefined;
77
+ return [...referencedClasses(entry?.symbolTable), ...(parent ? [parent] : [])];
78
+ };
79
+ const reach = (start) => {
80
+ const seen = new Set([start.toLowerCase()]);
81
+ const queue = neighbours(start);
82
+ let systemModeAt;
83
+ while (queue.length > 0) {
84
+ const ref = queue.shift();
85
+ if (seen.has(ref.toLowerCase()))
86
+ continue;
87
+ seen.add(ref.toLowerCase());
88
+ const helper = byName.get(ref.toLowerCase());
89
+ if (!helper?.body)
90
+ continue;
91
+ if (declaresWithoutSharing(helper.body))
92
+ return { withoutSharing: helper.name };
93
+ if (!systemModeAt && usesSystemMode(helper.body))
94
+ systemModeAt = helper.name;
95
+ queue.push(...neighbours(helper.name));
96
+ }
97
+ return { systemMode: systemModeAt };
98
+ };
99
+ // spec/apex-access-mode.md. A guest call is an entry point: no keyword means without sharing,
100
+ // and inherited sharing means with sharing. SYSTEM_MODE bypasses CRUD/FLS only (RULE-003); a
101
+ // helper declared without sharing bypasses sharing for whatever it does (RULE-004).
49
102
  const unprotected = [];
103
+ const systemMode = [];
50
104
  const exposed = [];
51
105
  for (const id of classIds) {
52
106
  const name = nameById.get(id) ?? id;
53
- const body = bodyByName.get(name);
54
- if (body && WITHOUT_SHARING.test(body)) {
55
- unprotected.push(name);
107
+ const entry = byName.get(name.toLowerCase());
108
+ const body = entry?.body;
109
+ // A class with no keyword takes the sharing of the class it extends (spec MN-001).
110
+ const keyword = body ? effectiveSharing(name, body, bodyOf) : null;
111
+ if (keyword === 'without' || (keyword !== null && body && declaresWithoutSharing(body))) {
112
+ unprotected.push({
113
+ name,
114
+ note: keyword === 'without' ? 'Declared "without sharing": fix immediately' : 'Contains an inner class declared "without sharing"',
115
+ });
116
+ continue;
117
+ }
118
+ if (keyword === 'none') {
119
+ unprotected.push({ name, note: 'No sharing declaration: runs without sharing when a guest calls it' });
120
+ continue;
121
+ }
122
+ if (keyword === null || !body) {
123
+ // No readable body (managed or hidden): its sharing cannot be judged.
124
+ exposed.push(name);
125
+ continue;
126
+ }
127
+ const path = reach(name);
128
+ if (path.withoutSharing) {
129
+ unprotected.push({ name, note: `Reaches "${path.withoutSharing}", which is declared "without sharing"` });
56
130
  }
57
- else if (body && !WITH_SHARING.test(body)) {
58
- // No sharing declaration in a guest-reachable class is also dangerous.
59
- unprotected.push(name);
131
+ else if (usesSystemMode(body) || path.systemMode) {
132
+ systemMode.push({ name, via: usesSystemMode(body) ? undefined : path.systemMode });
60
133
  }
61
134
  else {
62
135
  exposed.push(name);
@@ -68,12 +141,30 @@ export class GuestExecutableApexCheck {
68
141
  id: 'guest-executable-apex-unprotected',
69
142
  category: this.category,
70
143
  riskLevel: 'CRITICAL',
71
- title: `${unprotected.length} guest-executable Apex class(es) run without "with sharing"`,
72
- detail: 'These Apex classes can be invoked by unauthenticated guest users AND do not enforce record-level sharing. ' +
144
+ title: `${unprotected.length} guest-executable Apex class(es) run without sharing, directly or through a helper`,
145
+ detail: 'These Apex classes can be invoked by unauthenticated guest users AND do not enforce record-level sharing, ' +
146
+ 'either themselves or in a helper class they call that is declared "without sharing". ' +
73
147
  'This is the classic Salesforce guest-user exploit chain: an attacker calls the class and reads or writes ' +
74
148
  'business data in bulk with no login. Object-level guest permissions do not mitigate this: the class runs in system context.',
75
- remediation: 'Add "with sharing" to every guest-reachable Apex class, enforce CRUD/FLS, and remove guest execution access from any class that does not strictly need it.',
76
- affectedItems: unprotected.map((n) => ({ label: n, url: apexUrl, note: 'Guest-executable + without/with-no sharing: fix immediately' })),
149
+ remediation: 'Add "with sharing" to every guest-reachable Apex class and to every helper it calls, enforce CRUD/FLS, and remove guest execution access from any class that does not strictly need it.',
150
+ affectedItems: unprotected.map((u) => ({ label: u.name, url: apexUrl, note: u.note })),
151
+ });
152
+ }
153
+ if (systemMode.length > 0) {
154
+ findings.push({
155
+ id: 'guest-executable-apex-system-mode',
156
+ category: this.category,
157
+ riskLevel: 'HIGH',
158
+ title: `${systemMode.length} guest-executable Apex class(es) switch off CRUD/FLS with SYSTEM_MODE`,
159
+ detail: 'Guest users can execute these classes, which enforce sharing but run queries or DML with WITH SYSTEM_MODE or ' +
160
+ 'AccessLevel.SYSTEM_MODE. Sharing still limits which records a guest reaches, but not which objects and fields: ' +
161
+ 'a guest can read or change fields the guest profile is denied on any record shared with guests.',
162
+ remediation: 'Replace SYSTEM_MODE with USER_MODE in guest-reachable code, or strip fields with Security.stripInaccessible() before returning results. Remove guest access where unnecessary.',
163
+ affectedItems: systemMode.map(({ name, via }) => ({
164
+ label: name,
165
+ url: apexUrl,
166
+ note: via ? `Calls "${via}", which uses SYSTEM_MODE: guest CRUD/FLS not enforced` : 'SYSTEM_MODE: guest CRUD/FLS not enforced',
167
+ })),
77
168
  });
78
169
  }
79
170
  if (exposed.length > 0) {
@@ -1,3 +1,16 @@
1
+ import { fieldsOf } from '../support/schema.js';
2
+ /**
3
+ * Whether a Tooling ReleaseUpdate status means the update is enabled. Invoked and Revocable
4
+ * (enabled, can still be reverted) are on; Invocable (available) and Revoked are off; any other
5
+ * status is unknown.
6
+ */
7
+ function releaseUpdateEnabled(status) {
8
+ if (status === 'Invoked' || status === 'Revocable')
9
+ return true;
10
+ if (status === 'Invocable' || status === 'Revoked')
11
+ return false;
12
+ return null;
13
+ }
1
14
  /**
2
15
  * Verifies the PREVENTIVE guardrail that stops the guest-ownership-defeats-OWD
3
16
  * exfiltration vector: "Secure guest user record access".
@@ -41,8 +54,8 @@ export class GuestRecordAccessPolicyCheck {
41
54
  try {
42
55
  guests = await ctx.soql.queryAll("SELECT Id FROM User WHERE UserType = 'Guest' AND IsActive = true");
43
56
  }
44
- catch {
45
- findings.push(this.inconclusive('guest-record-access-policy-inaccessible', 'Guest users could not be queried'));
57
+ catch (err) {
58
+ findings.push(this.inconclusive('guest-record-access-policy-inaccessible', 'Guest users could not be queried', err));
46
59
  return { findings };
47
60
  }
48
61
  if (guests.length === 0) {
@@ -59,14 +72,27 @@ export class GuestRecordAccessPolicyCheck {
59
72
  }
60
73
  let updates;
61
74
  try {
62
- updates = await ctx.tooling.query('SELECT Id, Name, Description, IsEnabled FROM CriticalUpdate');
75
+ // Current orgs serve Release Updates as Tooling ReleaseUpdate (Status 'Invocable' = available
76
+ // but not enabled); CriticalUpdate is the older object. Read whichever this org serves.
77
+ if (await fieldsOf(ctx, 'ReleaseUpdate', 'tooling')) {
78
+ const rows = await ctx.tooling.query('SELECT Id, DeveloperName, Title, Description, Status FROM ReleaseUpdate');
79
+ updates = rows.map((r) => ({
80
+ Id: r.Id,
81
+ Name: r.Title ?? r.DeveloperName,
82
+ Description: r.Description,
83
+ IsEnabled: releaseUpdateEnabled(r.Status),
84
+ }));
85
+ }
86
+ else {
87
+ updates = await ctx.tooling.query('SELECT Id, Name, Description, IsEnabled FROM CriticalUpdate');
88
+ }
63
89
  }
64
- catch {
65
- findings.push(this.inconclusive('guest-record-access-policy-tooling-inaccessible', 'Release updates could not be queried'));
90
+ catch (err) {
91
+ findings.push(this.inconclusive('guest-record-access-policy-tooling-inaccessible', 'Release updates could not be queried', err));
66
92
  return { findings };
67
93
  }
68
94
  const match = updates.find((u) => this.matchesSecureGuestAccess(u));
69
- if (match && !match.IsEnabled) {
95
+ if (match && match.IsEnabled === false) {
70
96
  findings.push({
71
97
  id: 'guest-record-access-policy-not-enforced',
72
98
  category: this.category,
@@ -78,7 +104,7 @@ export class GuestRecordAccessPolicyCheck {
78
104
  });
79
105
  return { findings };
80
106
  }
81
- if (match && match.IsEnabled) {
107
+ if (match && match.IsEnabled === true) {
82
108
  findings.push({
83
109
  id: 'guest-record-access-policy-enforced',
84
110
  category: this.category,
@@ -91,6 +117,20 @@ export class GuestRecordAccessPolicyCheck {
91
117
  });
92
118
  return { findings };
93
119
  }
120
+ if (match) {
121
+ // Present, but its status says neither enabled nor available (e.g. a new status value):
122
+ // never read as enforced. MN-051.
123
+ findings.push({
124
+ id: 'guest-record-access-policy-verify-manually',
125
+ category: this.category,
126
+ riskLevel: 'LOW',
127
+ title: `Confirm guest record-access guardrails manually (${guests.length} active guest user(s))`,
128
+ detail: `The "Secure guest user record access" Release Update is present, but its status does not say whether it is enabled, so enforcement is not assumed.`,
129
+ remediation: 'In Setup → Release Updates and Setup → Sharing Settings, confirm "Secure guest user record access" is on and "Assign new records created by guest users to the default owner" is enabled.',
130
+ affectedItems: [{ label: match.Name, url: `${ctx.orgInfo.instanceUrl}/lightning/setup/ReleaseUpdates/home`, note: 'Status unknown' }],
131
+ });
132
+ return { findings };
133
+ }
94
134
  // No matching update surfaced — typical of orgs where it was auto-activated in
95
135
  // an earlier release and no longer appears in CriticalUpdate. We got data, so
96
136
  // this is advisory (LOW), not inconclusive: point the operator at the manual toggles.
@@ -105,15 +145,16 @@ export class GuestRecordAccessPolicyCheck {
105
145
  });
106
146
  return { findings };
107
147
  }
108
- inconclusive(id, what) {
148
+ inconclusive(id, what, err) {
149
+ const msg = err instanceof Error ? err.message : String(err);
109
150
  return {
110
151
  id,
111
152
  category: this.category,
112
153
  riskLevel: 'INFO',
113
154
  inconclusive: true,
114
- title: `${what} (insufficient access)`,
115
- detail: 'The audit user could not gather the data needed to evaluate guest record-access enforcement.',
116
- remediation: 'Grant the audit user View Setup and Configuration plus Tooling API access, then re-run.',
155
+ title: what,
156
+ detail: `The audit user could not gather the data needed to evaluate guest record-access enforcement. The org returned: ${msg}`,
157
+ remediation: 'If the error is an access error, grant the audit user View Setup and Configuration (see PERMISSIONS.md) and re-run. Otherwise the area is unassessed, not clean.',
117
158
  };
118
159
  }
119
160
  }
@@ -1,3 +1,4 @@
1
+ import { apexCode } from '../support/apexAccess.js';
1
2
  import { ApexRepository } from '@cclabsnz/sf-core';
2
3
  const HIGH_RISK_PATTERNS = [
3
4
  /Bearer\s+[A-Za-z0-9\-_.~+/]{20,}=*/gi, // Bearer tokens (min length to avoid test stubs)
@@ -38,10 +39,14 @@ export class HardcodedCredentialsCheck {
38
39
  Body: c.body ?? '',
39
40
  LengthWithoutComments: (c.body ?? '').length,
40
41
  NamespacePrefix: c.namespace,
42
+ SymbolTable: c.symbolTable,
41
43
  }));
42
44
  // Cache apex bodies for downstream checks — exclude test classes and filter null bodies
43
- const nonTestRecords = records.filter((r) => !IS_TEST_CLASS.test(r.Body ?? ''));
44
- ctx.cache.apexBodies = nonTestRecords.map((r) => ({ name: r.Name, body: r.Body ?? '' }));
45
+ // @IsTest is read from code only: a production helper mentioning it in a comment must still
46
+ // reach the cache, or the checks that follow calls into it never see its sharing (spec MN-002).
47
+ const nonTestRecords = records.filter((r) => !IS_TEST_CLASS.test(apexCode(r.Body ?? '')));
48
+ // The SymbolTable travels with the body so GuestExecutableApexCheck can follow calls into helpers.
49
+ ctx.cache.apexBodies = nonTestRecords.map((r) => ({ name: r.Name, body: r.Body ?? '', symbolTable: r.SymbolTable }));
45
50
  const namedCredentialEndpoints = (ctx.cache.namedCredentialEndpoints ?? []).filter(Boolean);
46
51
  const remoteSiteUrls = (ctx.cache.remoteSiteUrls ?? []).filter(Boolean);
47
52
  const classesWithCredentials = [];
@@ -20,6 +20,7 @@ export class HealthCheckCheck {
20
20
  category: this.category,
21
21
  riskLevel: scoreRisk,
22
22
  title: `Salesforce Security Health Check Score: ${score}/100`,
23
+ passed: scoreRisk === 'LOW' || undefined,
23
24
  detail: `The Salesforce Security Health Check scored ${score}/100. Scores below 85 indicate security configuration gaps that should be addressed.`,
24
25
  remediation: 'Review the Security Health Check in Setup → Security Center → Health Check.',
25
26
  });
@@ -1,6 +1,10 @@
1
- // Session timeouts are in seconds in SOQL for ConnectedApplication.
2
- // 8 hours = 28800s; 12 hours = 43200s.
3
- const LONG_TIMEOUT_SECONDS = 8 * 3600;
1
+ // 8 hours, in minutes: the unit of ConnectedApplication.SessionTimeout.
2
+ const LONG_TIMEOUT_MINUTES = 8 * 60;
3
+ /** Minutes, or null when the app sets no timeout of its own. */
4
+ function timeoutMinutes(app) {
5
+ const n = app.SessionTimeout === null || app.SessionTimeout === '' ? NaN : Number(app.SessionTimeout);
6
+ return Number.isFinite(n) && n > 0 ? n : null;
7
+ }
4
8
  // Patterns that suggest an app has elevated / admin capabilities
5
9
  const ADMIN_APP_PATTERNS = [/admin/i, /manage/i, /setup/i, /deploy/i, /devops/i, /audit/i, /monitor/i];
6
10
  export class HighAssuranceSessionCheck {
@@ -14,20 +18,20 @@ export class HighAssuranceSessionCheck {
14
18
  const setupUrl = `${baseUrl}/lightning/setup/ConnectedApplication/home`;
15
19
  let apps;
16
20
  try {
17
- const result = await ctx.soql.query(`SELECT Id, Name, SessionTimeout, OptionsAllowAdminApprovedUsersOnly
21
+ // SessionTimeout is served only by the Tooling API; the standard API rejects the column.
22
+ apps = await ctx.tooling.query(`SELECT Id, Name, SessionTimeout, OptionsAllowAdminApprovedUsersOnly
18
23
  FROM ConnectedApplication
19
24
  ORDER BY Name
20
25
  LIMIT 200`);
21
- apps = result.records;
22
26
  }
23
- catch {
27
+ catch (err) {
24
28
  findings.push({
25
29
  id: 'high-assurance-session-inaccessible',
26
30
  category: this.category,
27
31
  riskLevel: 'INFO',
28
32
  inconclusive: true,
29
33
  title: 'Connected app session settings could not be read',
30
- detail: 'ConnectedApplication session fields were not accessible. High assurance session configuration cannot be verified.',
34
+ detail: `ConnectedApplication session fields could not be read, so high assurance session configuration cannot be verified: ${err instanceof Error ? err.message : String(err)}`,
31
35
  remediation: 'Manually review connected apps in Setup → Connected Apps → Manage Connected Apps and verify session timeout policies.',
32
36
  });
33
37
  return { findings };
@@ -45,11 +49,12 @@ export class HighAssuranceSessionCheck {
45
49
  return { findings };
46
50
  }
47
51
  // Identify apps with no session timeout (unlimited) — any session remains valid until logout
48
- const noTimeout = apps.filter((a) => a.SessionTimeout === null || a.SessionTimeout === 0);
52
+ const noTimeout = apps.filter((a) => timeoutMinutes(a) === null);
49
53
  // Identify admin-pattern apps with very long or no timeouts
50
54
  const adminAppsLongTimeout = apps.filter((a) => {
51
55
  const isAdminLike = ADMIN_APP_PATTERNS.some((p) => p.test(a.Name));
52
- const hasLongTimeout = (a.SessionTimeout === null || a.SessionTimeout === 0 || a.SessionTimeout > LONG_TIMEOUT_SECONDS);
56
+ const minutes = timeoutMinutes(a);
57
+ const hasLongTimeout = minutes === null || minutes > LONG_TIMEOUT_MINUTES;
53
58
  return isAdminLike && hasLongTimeout;
54
59
  });
55
60
  // Org-level risk: majority of apps have no timeout
@@ -65,9 +70,9 @@ export class HighAssuranceSessionCheck {
65
70
  affectedItems: adminAppsLongTimeout.map((a) => ({
66
71
  label: a.Name,
67
72
  url: setupUrl,
68
- note: a.SessionTimeout === null || a.SessionTimeout === 0
73
+ note: timeoutMinutes(a) === null
69
74
  ? 'No session timeout: sessions never expire'
70
- : `Session timeout: ${Math.round(a.SessionTimeout / 3600)}h, reduce to ≤2h`,
75
+ : `Session timeout: ${Math.round(timeoutMinutes(a) / 60)}h, reduce to ≤2h`,
71
76
  })),
72
77
  });
73
78
  }
@@ -14,7 +14,7 @@ export class InactiveUsersCheck {
14
14
  const baseUrl = ctx.orgInfo.instanceUrl;
15
15
  // Q1: true count — query with LIMIT returns totalSize = min(actual, LIMIT),
16
16
  // so a separate COUNT query is required for an accurate number.
17
- const countResult = await ctx.soql.query(`SELECT COUNT(Id) expr0 FROM User WHERE ${BASE_FILTER}`);
17
+ const countResult = await ctx.soql.query(`SELECT COUNT(Id) FROM User WHERE ${BASE_FILTER}`);
18
18
  const totalCount = countResult.records[0]?.expr0 ?? 0;
19
19
  if (totalCount === 0) {
20
20
  findings.push({
@@ -0,0 +1,10 @@
1
+ import type { AuditContext } from '@cclabsnz/sf-core';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class InboundEmailHandlerExposureCheck implements SecurityCheck {
4
+ readonly id = "inbound-email-handler-exposure";
5
+ readonly name = "Inbound Email Handler Unauthenticated Execution";
6
+ readonly category = "External Connectivity";
7
+ readonly description = "Detects active inbound email services open to all senders without SPF/DKIM verification executing Apex under privileged users.";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=InboundEmailHandlerExposureCheck.d.ts.map
@@ -0,0 +1,136 @@
1
+ export class InboundEmailHandlerExposureCheck {
2
+ id = 'inbound-email-handler-exposure';
3
+ name = 'Inbound Email Handler Unauthenticated Execution';
4
+ category = 'External Connectivity';
5
+ description = 'Detects active inbound email services open to all senders without SPF/DKIM verification executing Apex under privileged users.';
6
+ async run(ctx) {
7
+ const findings = [];
8
+ const baseUrl = ctx.orgInfo.instanceUrl;
9
+ const emailToApexUrl = `${baseUrl}/lightning/setup/EmailToApex/home`;
10
+ let functions = [];
11
+ try {
12
+ functions = await ctx.soql.queryAll('SELECT Id, FunctionName, IsActive, ApexClassId, AuthenticationFailureAction FROM EmailServicesFunction WHERE IsActive = true');
13
+ }
14
+ catch (err) {
15
+ // This object exists in every org, so a failure is lack of access, never an absent feature.
16
+ findings.push({
17
+ id: 'inbound-email-handler-exposure-inaccessible',
18
+ category: this.category,
19
+ riskLevel: 'INFO',
20
+ inconclusive: true,
21
+ title: 'Email Services Functions could not be queried',
22
+ detail: `Query to EmailServicesFunction failed: ${err instanceof Error ? err.message : String(err)}`,
23
+ remediation: 'Grant the audit user "View Setup and Configuration".',
24
+ });
25
+ return { findings };
26
+ }
27
+ if (functions.length === 0) {
28
+ findings.push({
29
+ id: 'inbound-email-handler-exposure-ok',
30
+ category: this.category,
31
+ riskLevel: 'LOW',
32
+ passed: true,
33
+ title: 'No active inbound Email-to-Apex services found',
34
+ detail: 'Zero active EmailServicesFunction records exist in the org.',
35
+ remediation: 'When creating inbound email services, enforce sender restrictions and SPF/DKIM verification.',
36
+ });
37
+ return { findings };
38
+ }
39
+ // Query active EmailServicesAddress records
40
+ let addresses = [];
41
+ addresses = await ctx.soql.queryAll('SELECT Id, FunctionId, LocalPart, EmailDomainName, IsActive, AuthorizedSenders, RunAsUserId FROM EmailServicesAddress WHERE IsActive = true');
42
+ const addressesByFunction = new Map();
43
+ for (const a of addresses) {
44
+ const list = addressesByFunction.get(a.FunctionId) ?? [];
45
+ list.push(a);
46
+ addressesByFunction.set(a.FunctionId, list);
47
+ }
48
+ // Query RunAs users
49
+ const runAsUserIds = [
50
+ ...new Set(addresses.map((a) => a.RunAsUserId).filter((id) => Boolean(id))),
51
+ ];
52
+ let adminUsers = new Set();
53
+ let userDetails = new Map();
54
+ if (runAsUserIds.length > 0) {
55
+ const users = await ctx.soql.queryAll(`SELECT Id, Username, Profile.Name FROM User WHERE Id IN ('${runAsUserIds.join("','")}')`);
56
+ for (const u of users) {
57
+ const prof = u.Profile?.Name ?? '';
58
+ userDetails.set(u.Id, `${u.Username} (${prof})`);
59
+ if (prof === 'System Administrator' || prof.toLowerCase().includes('admin')) {
60
+ adminUsers.add(u.Id);
61
+ }
62
+ }
63
+ }
64
+ // Query Apex Classes
65
+ const apexClassIds = [
66
+ ...new Set(functions.map((f) => f.ApexClassId).filter((id) => Boolean(id))),
67
+ ];
68
+ let classBodies = new Map();
69
+ let classNames = new Map();
70
+ if (apexClassIds.length > 0) {
71
+ const classes = await ctx.soql.queryAll(`SELECT Id, Name, Body FROM ApexClass WHERE Id IN ('${apexClassIds.join("','")}')`);
72
+ for (const c of classes) {
73
+ classNames.set(c.Id, c.Name);
74
+ classBodies.set(c.Id, c.Body ?? '');
75
+ }
76
+ }
77
+ const exposedFunctions = [];
78
+ for (const fn of functions) {
79
+ const funcAddresses = addressesByFunction.get(fn.Id) ?? [];
80
+ // Check 1: Any address with empty/blank AuthorizedSenders
81
+ const openAddress = funcAddresses.find((a) => !a.AuthorizedSenders || a.AuthorizedSenders.trim() === '');
82
+ // Check 2: AuthenticationFailureAction is 0 or '0' (None / accept even spoofed emails)
83
+ const authFailureAction = String(fn.AuthenticationFailureAction ?? '0');
84
+ const acceptsSpoofedEmail = authFailureAction === '0' || authFailureAction === '';
85
+ // Check 3: the open address runs as an admin, or the class runs without sharing / performs DML
86
+ const isRunAsAdmin = openAddress?.RunAsUserId ? adminUsers.has(openAddress.RunAsUserId) : false;
87
+ const classBody = fn.ApexClassId ? classBodies.get(fn.ApexClassId) ?? '' : '';
88
+ const isWithoutSharing = /without\s+sharing/i.test(classBody);
89
+ const hasDmlOrDynamicSoql = /insert\s+|update\s+|upsert\s+|delete\s+|Database\.execute/i.test(classBody);
90
+ if (openAddress && acceptsSpoofedEmail && (isRunAsAdmin || isWithoutSharing || hasDmlOrDynamicSoql)) {
91
+ const addrStr = `${openAddress.LocalPart}${openAddress.EmailDomainName ? '@' + openAddress.EmailDomainName : ''}`;
92
+ const reasons = [
93
+ 'No sender restriction (AuthorizedSenders is blank)',
94
+ 'AuthenticationFailureAction is set to None (accepts spoofed SPF/DKIM)',
95
+ isRunAsAdmin ? 'Runs as System Administrator' : '',
96
+ isWithoutSharing ? 'Apex runs without sharing' : '',
97
+ ]
98
+ .filter(Boolean)
99
+ .join('; ');
100
+ exposedFunctions.push({
101
+ func: fn,
102
+ address: addrStr,
103
+ reason: reasons,
104
+ });
105
+ }
106
+ }
107
+ if (exposedFunctions.length > 0) {
108
+ findings.push({
109
+ id: 'inbound-email-handler-unauthenticated-execution',
110
+ category: this.category,
111
+ riskLevel: 'HIGH',
112
+ title: `${exposedFunctions.length} inbound email service(s) allow unauthenticated remote Apex execution`,
113
+ detail: 'Active EmailServicesFunction records accept messages from any internet sender with no SPF/DKIM authentication enforcement (AuthenticationFailureAction = 0 / None) and execute under a privileged System Administrator or in an Apex class running without sharing. An external attacker sending an email can trigger unauthenticated backend DML or privilege escalation.',
114
+ remediation: 'Configure "Accept Email From" with an authorized domain allowlist, set the Failure Action to "Bounce message" or "Discard message" upon SPF/DKIM verification failure, and run the service under a least-privileged execution user.',
115
+ affectedItems: exposedFunctions.map((item) => ({
116
+ label: `${item.func.FunctionName} (${item.address})`,
117
+ url: emailToApexUrl,
118
+ note: item.reason,
119
+ })),
120
+ });
121
+ }
122
+ else {
123
+ findings.push({
124
+ id: 'inbound-email-handler-exposure-ok',
125
+ category: this.category,
126
+ riskLevel: 'LOW',
127
+ passed: true,
128
+ title: 'Inbound email services enforce sender restrictions and authentication controls',
129
+ detail: `${functions.length} active inbound email service(s) inspected; all require authentication, enforce sender allowlists, or execute under constrained least-privilege contexts.`,
130
+ remediation: 'Continue enforcing sender allowlists and bounce/discard policies on SPF/DKIM failure.',
131
+ });
132
+ }
133
+ return { findings };
134
+ }
135
+ }
136
+ //# sourceMappingURL=InboundEmailHandlerExposureCheck.js.map
@@ -112,8 +112,8 @@ export class IntegrationLeastPrivilegeCheck {
112
112
  psa = await ctx.soql.queryAll(`SELECT AssigneeId, PermissionSetId, PermissionSet.Name, PermissionSet.IsOwnedByProfile, ${permFields}
113
113
  FROM PermissionSetAssignment WHERE AssigneeId IN (${idList})`);
114
114
  }
115
- catch {
116
- findings.push(this.inconclusive('integration-least-privilege-permissions-inaccessible', 'Integration account permissions could not be queried'));
115
+ catch (err) {
116
+ findings.push(this.inconclusive('integration-least-privilege-permissions-inaccessible', 'Integration account permissions could not be queried', err instanceof Error ? err.message : String(err)));
117
117
  return { findings };
118
118
  }
119
119
  const grants = [];
@@ -452,15 +452,16 @@ export class IntegrationLeastPrivilegeCheck {
452
452
  })),
453
453
  });
454
454
  }
455
- inconclusive(id, what) {
455
+ inconclusive(id, what, orgError) {
456
456
  return {
457
457
  id,
458
458
  category: this.category,
459
459
  riskLevel: 'INFO',
460
460
  inconclusive: true,
461
- title: `${what} (insufficient access)`,
462
- detail: 'The audit user could not gather the data needed to evaluate integration account privilege.',
463
- remediation: 'Grant the audit user View Setup and Configuration and re-run.',
461
+ title: what,
462
+ detail: 'The audit user could not gather the data needed to evaluate integration account privilege, so it is unassessed.' +
463
+ (orgError ? ` The org said: ${orgError}` : ''),
464
+ remediation: 'If the cause is an access error, confirm the audit user has View Setup and Configuration and View All Users, then re-run.',
464
465
  };
465
466
  }
466
467
  }
@@ -1,3 +1,4 @@
1
+ import { hasField } from '../support/schema.js';
1
2
  export class InternalUserMfaCheck {
2
3
  id = 'internal-user-mfa';
3
4
  name = 'Internal User MFA Enforcement';
@@ -28,22 +29,38 @@ export class InternalUserMfaCheck {
28
29
  }
29
30
  let mfaUserIds = new Set();
30
31
  try {
32
+ // The permission is absent from some orgs and API versions. Without it, per-user MFA
33
+ // enforcement cannot be read from permissions at all: MFA may still be enforced org-wide
34
+ // (Session Settings) or by an SSO provider, so this is unknown, never a gap or a pass.
35
+ if (!(await hasField(ctx, 'PermissionSet', 'PermissionsForceTwoFactor'))) {
36
+ findings.push({
37
+ id: 'internal-user-mfa-not-available',
38
+ category: this.category,
39
+ riskLevel: 'INFO',
40
+ inconclusive: true,
41
+ notAssessed: true,
42
+ title: 'MFA enforcement for internal users cannot be read from permissions in this org',
43
+ detail: `This org does not expose the "Multi-Factor Authentication for User Interface Logins" permission (PermissionSet.PermissionsForceTwoFactor), so whether its ${users.length} active internal user(s) have MFA enforced cannot be established from permission assignments. MFA may still be enforced org-wide in Session Settings or by an SSO identity provider.`,
44
+ remediation: 'Confirm "Require multi-factor authentication (MFA) for all direct UI logins" in Setup → Session Settings, and MFA at the identity provider for SSO users.',
45
+ });
46
+ return { findings };
47
+ }
31
48
  const psaResult = await ctx.soql.query(`SELECT AssigneeId
32
49
  FROM PermissionSetAssignment
33
- WHERE PermissionSet.PermissionsMultiFactorForUiLogins = true
50
+ WHERE PermissionSet.PermissionsForceTwoFactor = true
34
51
  AND Assignee.IsActive = true
35
52
  AND Assignee.UserType = 'Standard'`);
36
53
  mfaUserIds = new Set(psaResult.records.map((r) => r.AssigneeId));
37
54
  }
38
- catch {
55
+ catch (err) {
39
56
  findings.push({
40
57
  id: 'internal-user-mfa-inaccessible',
41
58
  category: this.category,
42
59
  riskLevel: 'INFO',
43
60
  inconclusive: true,
44
61
  title: 'MFA permission set assignments could not be queried',
45
- detail: 'The PermissionSetAssignment query for PermissionsMultiFactorForUiLogins was not accessible. This may indicate insufficient permissions to query permission set assignments.',
46
- remediation: 'Grant "View All Users" or "Manage Users" permission to the audit user. Review MFA enforcement manually in Setup → Users → Permission Sets.',
62
+ detail: `Which users hold PermissionsForceTwoFactor could not be read, so MFA enforcement for internal users is unassessed. The org said: ${err instanceof Error ? err.message : String(err)}`,
63
+ remediation: 'Check the error above. If it is an access error, confirm the audit user can read PermissionSetAssignment (View Setup and Configuration); otherwise review MFA enforcement manually in Setup → Users → Permission Sets.',
47
64
  });
48
65
  return { findings };
49
66
  }
@@ -55,18 +72,19 @@ export class InternalUserMfaCheck {
55
72
  riskLevel: 'LOW',
56
73
  passed: true,
57
74
  title: `All ${users.length} active internal user(s) have MFA explicitly enforced via permission`,
58
- detail: 'All active, unfrozen standard users have the PermissionsMultiFactorForUiLogins permission assigned. Salesforce auto-enforced MFA at the system level in Spring 2023; this explicit permission provides belt-and-suspenders assurance that MFA is enforced even if system-level enforcement has edge cases.',
75
+ detail: 'All active, unfrozen standard users have the PermissionsForceTwoFactor permission assigned. Salesforce auto-enforced MFA at the system level in Spring 2023; this explicit permission provides belt-and-suspenders assurance that MFA is enforced even if system-level enforcement has edge cases.',
59
76
  remediation: 'Continue to ensure all new users are assigned MFA enforcement via their profile or a permission set.',
60
77
  });
61
78
  return { findings };
62
79
  }
63
- const riskLevel = usersWithoutMfa.length > 20 ? 'HIGH' : 'MEDIUM';
80
+ // Salesforce enforces MFA for UI logins at org level; the explicit permission is a second layer. RULE-078.
81
+ const riskLevel = usersWithoutMfa.length > 20 ? 'MEDIUM' : 'LOW';
64
82
  findings.push({
65
83
  id: 'internal-user-mfa-gaps',
66
84
  category: this.category,
67
85
  riskLevel,
68
- title: `${usersWithoutMfa.length} of ${users.length} active internal user(s) lack explicit MFA enforcement permission`,
69
- detail: `${usersWithoutMfa.length} active standard users do not have the PermissionsMultiFactorForUiLogins permission assigned. Salesforce auto-enforced MFA at the system level in Spring 2023, but the explicit permission provides belt-and-suspenders assurance. Users without it rely solely on system-level enforcement, which can have edge cases in API-heavy or SSO-integrated environments. Users without the explicit permission should be reviewed to confirm they are subject to effective MFA controls.`,
86
+ title: `${usersWithoutMfa.length} of ${users.length} active internal user(s) lack the explicit MFA permission (second layer over org-level MFA)`,
87
+ detail: `${usersWithoutMfa.length} active standard users do not have the PermissionsForceTwoFactor permission assigned. Salesforce auto-enforced MFA at the system level in Spring 2023, but the explicit permission provides belt-and-suspenders assurance. Users without it rely solely on system-level enforcement, which can have edge cases in API-heavy or SSO-integrated environments. Users without the explicit permission should be reviewed to confirm they are subject to effective MFA controls.`,
70
88
  remediation: 'Assign the "Multi-Factor Authentication for User Interface Logins" permission to all internal standard users via their profile or a permission set. This ensures MFA is explicitly enforced regardless of system-level settings. Prioritise users with privileged access or access to sensitive data.',
71
89
  affectedItems: usersWithoutMfa.slice(0, 50).map((u) => ({
72
90
  label: u.Username,