@cclabsnz/sf-audit 1.17.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 (83) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/PERMISSIONS.md +139 -0
  3. package/README.md +4 -2
  4. package/docs/permissionset/SF_Audit_ReadOnly.permissionset-meta.xml +54 -0
  5. package/lib/chains/ChainEngine.js +11 -1
  6. package/lib/chains/namedChains.js +42 -24
  7. package/lib/checks/CheckEngine.js +55 -24
  8. package/lib/checks/impl/AgentUserPrivilegeCheck.js +5 -4
  9. package/lib/checks/impl/AnonymousApexAuditCheck.js +41 -8
  10. package/lib/checks/impl/ApexSharingCheck.js +3 -1
  11. package/lib/checks/impl/ApiClientPermissionCheck.js +21 -5
  12. package/lib/checks/impl/AuditTrailCheck.js +23 -8
  13. package/lib/checks/impl/CertificateExpiryCheck.js +2 -1
  14. package/lib/checks/impl/ConnectedAppScopeCheck.js +61 -5
  15. package/lib/checks/impl/ConnectedAppsCheck.js +13 -4
  16. package/lib/checks/impl/ContentLinksCheck.js +33 -9
  17. package/lib/checks/impl/CorsAllowlistCheck.js +3 -2
  18. package/lib/checks/impl/DataClassificationCheck.js +15 -13
  19. package/lib/checks/impl/DebugLogAccessCheck.js +4 -4
  20. package/lib/checks/impl/DelegatedAdministrationGroupsCheck.js +3 -2
  21. package/lib/checks/impl/DelegatedAuthenticationExposureCheck.js +8 -1
  22. package/lib/checks/impl/DeploymentIdentityCheck.js +32 -5
  23. package/lib/checks/impl/EmailSecurityCheck.d.ts +1 -1
  24. package/lib/checks/impl/EmailSecurityCheck.js +14 -34
  25. package/lib/checks/impl/EncryptionCoverageCheck.js +21 -15
  26. package/lib/checks/impl/EnhancedDomainsCheck.js +17 -2
  27. package/lib/checks/impl/EscalationPermsCheck.d.ts +2 -0
  28. package/lib/checks/impl/EscalationPermsCheck.js +88 -21
  29. package/lib/checks/impl/ExperienceCloudSiteCheck.js +56 -5
  30. package/lib/checks/impl/ExternalAccountHierarchyExposureCheck.js +7 -15
  31. package/lib/checks/impl/ExternalCredentialsCheck.js +6 -3
  32. package/lib/checks/impl/FailedLoginCheck.js +36 -9
  33. package/lib/checks/impl/FieldHistoryTrackingCheck.js +14 -11
  34. package/lib/checks/impl/FlowHttpCalloutCredentialBypassCheck.js +2 -2
  35. package/lib/checks/impl/GuestRecordAccessPolicyCheck.js +52 -11
  36. package/lib/checks/impl/HealthCheckCheck.js +1 -0
  37. package/lib/checks/impl/HighAssuranceSessionCheck.js +16 -11
  38. package/lib/checks/impl/InactiveUsersCheck.js +1 -1
  39. package/lib/checks/impl/InboundEmailHandlerExposureCheck.js +5 -5
  40. package/lib/checks/impl/IntegrationLeastPrivilegeCheck.js +7 -6
  41. package/lib/checks/impl/InternalUserMfaCheck.js +26 -8
  42. package/lib/checks/impl/IpRestrictionsCheck.js +35 -16
  43. package/lib/checks/impl/LoginAccessPolicyCheck.js +5 -4
  44. package/lib/checks/impl/LoginAnomalyCheck.js +10 -7
  45. package/lib/checks/impl/LoginSessionCheck.js +2 -0
  46. package/lib/checks/impl/MfaEnforcementCheck.js +23 -6
  47. package/lib/checks/impl/MfaMethodStrengthCheck.js +18 -3
  48. package/lib/checks/impl/MfaRegistrationCheck.js +4 -3
  49. package/lib/checks/impl/MyDomainLoginPolicyCheck.js +23 -10
  50. package/lib/checks/impl/OutboundMessagesCheck.js +48 -6
  51. package/lib/checks/impl/PlatformEventSubscriberContextCheck.js +5 -1
  52. package/lib/checks/impl/PrivilegedAccessCheck.js +12 -5
  53. package/lib/checks/impl/ReleaseUpdatesCheck.js +18 -3
  54. package/lib/checks/impl/RemoteSitesCheck.js +4 -4
  55. package/lib/checks/impl/RestrictionRulesIntegrityCheck.js +3 -3
  56. package/lib/checks/impl/SeparationOfDutiesCheck.js +14 -3
  57. package/lib/checks/impl/SoapLoginApiAuthCheck.js +20 -8
  58. package/lib/checks/impl/SsoEnforcementCheck.js +16 -5
  59. package/lib/checks/impl/TransactionSecurityPolicyCheck.js +5 -5
  60. package/lib/checks/impl/TrustedIPRangesCheck.js +18 -9
  61. package/lib/checks/impl/UsersAndAdminsCheck.js +24 -4
  62. package/lib/checks/permCatalog.js +1 -1
  63. package/lib/checks/support/missingObject.js +3 -1
  64. package/lib/checks/support/schema.d.ts +17 -0
  65. package/lib/checks/support/schema.js +41 -0
  66. package/lib/commands/audit/apps.js +3 -1
  67. package/lib/commands/audit/events/pull.js +3 -1
  68. package/lib/commands/audit/incident/collect.js +3 -1
  69. package/lib/commands/audit/security.js +9 -3
  70. package/lib/findings/AuditResult.d.ts +2 -0
  71. package/lib/findings/coverage.d.ts +6 -0
  72. package/lib/findings/coverage.js +12 -0
  73. package/lib/findings/scoring.js +51 -9
  74. package/lib/preflight/permissionMap.d.ts +2 -20
  75. package/lib/preflight/permissionMap.js +2 -43
  76. package/lib/preflight/permissions.d.ts +25 -0
  77. package/lib/preflight/permissions.js +50 -0
  78. package/lib/renderers/ClientReportRenderer.js +3 -3
  79. package/lib/renderers/HtmlRenderer.js +6 -2
  80. package/lib/renderers/MarkdownRenderer.js +6 -3
  81. package/lib/report/RemediationRoadmap.d.ts +5 -1
  82. package/lib/report/RemediationRoadmap.js +6 -2
  83. package/package.json +4 -2
@@ -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
  }
@@ -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({
@@ -9,7 +9,7 @@ export class InboundEmailHandlerExposureCheck {
9
9
  const emailToApexUrl = `${baseUrl}/lightning/setup/EmailToApex/home`;
10
10
  let functions = [];
11
11
  try {
12
- functions = await ctx.soql.queryAll('SELECT Id, FunctionName, IsActive, RunAsUserId, ApexClassId, AuthenticationFailureAction FROM EmailServicesFunction WHERE IsActive = true');
12
+ functions = await ctx.soql.queryAll('SELECT Id, FunctionName, IsActive, ApexClassId, AuthenticationFailureAction FROM EmailServicesFunction WHERE IsActive = true');
13
13
  }
14
14
  catch (err) {
15
15
  // This object exists in every org, so a failure is lack of access, never an absent feature.
@@ -38,7 +38,7 @@ export class InboundEmailHandlerExposureCheck {
38
38
  }
39
39
  // Query active EmailServicesAddress records
40
40
  let addresses = [];
41
- addresses = await ctx.soql.queryAll('SELECT Id, FunctionId, LocalPart, EmailDomainName, IsActive, AuthorizedSenders FROM EmailServicesAddress WHERE IsActive = true');
41
+ addresses = await ctx.soql.queryAll('SELECT Id, FunctionId, LocalPart, EmailDomainName, IsActive, AuthorizedSenders, RunAsUserId FROM EmailServicesAddress WHERE IsActive = true');
42
42
  const addressesByFunction = new Map();
43
43
  for (const a of addresses) {
44
44
  const list = addressesByFunction.get(a.FunctionId) ?? [];
@@ -47,7 +47,7 @@ export class InboundEmailHandlerExposureCheck {
47
47
  }
48
48
  // Query RunAs users
49
49
  const runAsUserIds = [
50
- ...new Set(functions.map((f) => f.RunAsUserId).filter((id) => Boolean(id))),
50
+ ...new Set(addresses.map((a) => a.RunAsUserId).filter((id) => Boolean(id))),
51
51
  ];
52
52
  let adminUsers = new Set();
53
53
  let userDetails = new Map();
@@ -82,8 +82,8 @@ export class InboundEmailHandlerExposureCheck {
82
82
  // Check 2: AuthenticationFailureAction is 0 or '0' (None / accept even spoofed emails)
83
83
  const authFailureAction = String(fn.AuthenticationFailureAction ?? '0');
84
84
  const acceptsSpoofedEmail = authFailureAction === '0' || authFailureAction === '';
85
- // Check 3: RunAsUserId is admin or class runs without sharing / performs DML
86
- const isRunAsAdmin = fn.RunAsUserId ? adminUsers.has(fn.RunAsUserId) : false;
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
87
  const classBody = fn.ApexClassId ? classBodies.get(fn.ApexClassId) ?? '' : '';
88
88
  const isWithoutSharing = /without\s+sharing/i.test(classBody);
89
89
  const hasDmlOrDynamicSoql = /insert\s+|update\s+|upsert\s+|delete\s+|Database\.execute/i.test(classBody);
@@ -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,
@@ -1,3 +1,6 @@
1
+ const BYPASS_VALUES = new Set(['BYPASS', 'ALL']);
2
+ const RELAX_VALUES = new Set(['ENFORCE_ACTIVATED_DEVICES', 'RELAX']);
3
+ const MAX_METADATA_READS = 100;
1
4
  // SBS-AUTH-003: detect ranges covering the full public internet or overly broad blocks.
2
5
  // Anything larger than a /16 (65 536 hosts) is flagged; 0.0.0.0 start is always flagged.
3
6
  function ipToNumber(ip) {
@@ -39,30 +42,44 @@ export class IpRestrictionsCheck {
39
42
  rangesUnavailable = true;
40
43
  }
41
44
  }
42
- // 3. Connected apps — single Tooling SOQL with Metadata field (same pattern as
43
- // SELECT Body FROM ApexClass). Replaces the previous N+1 getRecord loop.
44
- // Salesforce ConnectedApp.Metadata.oauthConfig.ipRelaxation enum:
45
- // 'All' → bypass IP restrictions (every IP allowed)
46
- // 'Relax' → relax restrictions for this app's users
47
- // 'WhiteList'→ enforce the org-level IP whitelist (secure)
45
+ // 3. Connected apps: listed via Tooling (which has no Metadata column on this object), then each
46
+ // app's IP Relaxation read from its Metadata API definition. An app that cannot be read leaves
47
+ // the question open, so it blocks the pass rather than counting as enforcing.
48
48
  const ipBypassingApps = [];
49
49
  const ipRelaxingApps = [];
50
50
  let appsUnavailable = false;
51
+ let unreadApps = 0;
52
+ let appsError = '';
51
53
  try {
52
- const connectedApps = await ctx.tooling.query('SELECT Id, Name, Metadata FROM ConnectedApplication');
53
- for (const app of connectedApps) {
54
- const relaxation = app.Metadata?.oauthConfig?.ipRelaxation;
55
- if (relaxation === 'All') {
54
+ const connectedApps = await ctx.tooling.query('SELECT Id, Name, DeveloperName FROM ConnectedApplication');
55
+ for (const [i, app] of connectedApps.entries()) {
56
+ let meta = null;
57
+ if (ctx.metadata && i < MAX_METADATA_READS) {
58
+ try {
59
+ meta = await ctx.metadata.read('ConnectedApp', app.DeveloperName);
60
+ }
61
+ catch {
62
+ meta = null;
63
+ }
64
+ }
65
+ if (!meta) {
66
+ unreadApps++;
67
+ continue;
68
+ }
69
+ const relaxation = (meta.oauthPolicy?.ipRelaxation ?? meta.oauthConfig?.ipRelaxation ?? '').toUpperCase();
70
+ if (BYPASS_VALUES.has(relaxation)) {
56
71
  ipBypassingApps.push({ name: app.Name, id: app.Id });
57
72
  }
58
- else if (relaxation === 'Relax') {
73
+ else if (RELAX_VALUES.has(relaxation)) {
59
74
  ipRelaxingApps.push({ name: app.Name, id: app.Id });
60
75
  }
61
76
  }
77
+ appsUnavailable = unreadApps > 0;
62
78
  }
63
- catch {
79
+ catch (err) {
64
80
  // Recorded so the result cannot be read as "no relaxed apps".
65
81
  appsUnavailable = true;
82
+ appsError = err instanceof Error ? err.message : String(err);
66
83
  }
67
84
  // Determine which profile IDs have at least one IP range
68
85
  const profilesWithRanges = new Set(ipRanges.map((r) => r.ProfileId));
@@ -75,8 +92,8 @@ export class IpRestrictionsCheck {
75
92
  riskLevel: 'INFO',
76
93
  inconclusive: true,
77
94
  title: `Login IP ranges could not be read; ${adminUsers.length} admin profile(s) were not evaluated`,
78
- detail: 'ProfileLoginIpRange was not queryable via SOQL or the Tooling API, so whether these admin profiles restrict login by IP is unknown. It is not reported as unrestricted, because the data does not support that conclusion.',
79
- remediation: 'Grant the audit user access to ProfileLoginIpRange and re-run, or review Login IP Ranges manually in Setup → Profiles.',
95
+ detail: 'This org does not serve ProfileLoginIpRange through SOQL or the Tooling API, so whether these admin profiles restrict login by IP is unknown. It is not reported as unrestricted, because the data does not support that conclusion.',
96
+ remediation: 'Review Login IP Ranges for these admin profiles manually in Setup → Profiles.',
80
97
  affectedItems: adminUsers.map((u) => ({
81
98
  label: u.Username,
82
99
  url: `${baseUrl}/${u.Id}`,
@@ -106,8 +123,10 @@ export class IpRestrictionsCheck {
106
123
  riskLevel: 'INFO',
107
124
  inconclusive: true,
108
125
  title: 'Connected app IP relaxation settings could not be read',
109
- detail: 'The ConnectedApplication Metadata field was not accessible, so whether any connected app bypasses or relaxes login IP enforcement is unknown.',
110
- remediation: 'Grant the audit user access to the Tooling API ConnectedApplication Metadata field and re-run, or review IP Relaxation per app in Setup → Connected Apps.',
126
+ detail: appsError
127
+ ? `Connected apps could not be listed, so whether any of them bypasses or relaxes login IP enforcement is unknown: ${appsError}`
128
+ : `The Metadata API definitions of ${unreadApps} connected app(s) could not be read, so whether they bypass or relax login IP enforcement is unknown.`,
129
+ remediation: 'Review IP Relaxation per app in Setup → App Manager → Manage → OAuth Policies.',
111
130
  });
112
131
  }
113
132
  if (ipBypassingApps.length > 0) {
@@ -18,16 +18,17 @@ export class LoginAccessPolicyCheck {
18
18
  const baseUrl = ctx.orgInfo.instanceUrl;
19
19
  let groups;
20
20
  try {
21
- groups = await ctx.soql.queryAll('SELECT Id, DeveloperName FROM DelegateGroup');
21
+ // DelegateGroup is served by the Tooling API only.
22
+ groups = await ctx.tooling.query('SELECT Id, DeveloperName FROM DelegateGroup');
22
23
  }
23
- catch {
24
+ catch (err) {
24
25
  findings.push({
25
26
  id: 'login-access-policy-inconclusive',
26
27
  category: this.category,
27
28
  riskLevel: 'INFO',
28
29
  inconclusive: true,
29
- title: 'Delegated administration could not be queried (insufficient access)',
30
- detail: 'DelegateGroup was not accessible, so delegated-admin escalation paths could not be evaluated.',
30
+ title: 'Delegated administration could not be queried',
31
+ detail: `The DelegateGroup query failed (${err instanceof Error ? err.message : String(err)}), so delegated-admin escalation paths could not be evaluated.`,
31
32
  remediation: 'Grant the audit user View Setup and Configuration, then re-run. Also manually verify Setup → Login Access Policies.',
32
33
  });
33
34
  return { findings };
@@ -18,24 +18,27 @@ export class LoginAnomalyCheck {
18
18
  async run(ctx) {
19
19
  const findings = [];
20
20
  const setupUrl = `${ctx.orgInfo.instanceUrl}/lightning/setup/OrgLoginHistory/home`;
21
- let rows;
21
+ let fetched;
22
22
  try {
23
- rows = await ctx.soql.queryAll(`SELECT UserId, SourceIp, LoginTime FROM LoginHistory
24
- WHERE Status = 'Success' AND LoginTime = LAST_N_DAYS:7
23
+ // Status cannot be filtered in SOQL, so successful logins are selected in code.
24
+ fetched = await ctx.soql.queryAll(`SELECT UserId, SourceIp, LoginTime, Status FROM LoginHistory
25
+ WHERE LoginTime = LAST_N_DAYS:7
25
26
  ORDER BY LoginTime DESC LIMIT ${MAX_ROWS}`);
26
27
  }
27
- catch {
28
+ catch (err) {
28
29
  findings.push({
29
30
  id: 'login-anomaly-inconclusive',
30
31
  category: this.category,
31
32
  riskLevel: 'INFO',
32
33
  inconclusive: true,
33
34
  title: 'LoginHistory could not be queried — anomalous-login analysis skipped',
34
- detail: 'LoginHistory was not accessible. This may indicate the audit user lacks "View All Users"/"Manage Users" or the org restricts login history.',
35
+ detail: `The LoginHistory query failed: ${err instanceof Error ? err.message : String(err)}. ` +
36
+ 'If the org denied access, the audit user may lack "View All Users".',
35
37
  remediation: 'Grant the audit user access to LoginHistory and re-run.',
36
38
  });
37
39
  return { findings };
38
40
  }
41
+ const rows = fetched.filter((r) => r.Status === undefined || r.Status === 'Success');
39
42
  if (rows.length === 0) {
40
43
  findings.push({
41
44
  id: 'login-anomaly-none',
@@ -57,13 +60,13 @@ export class LoginAnomalyCheck {
57
60
  ipsByUser.set(r.UserId, set);
58
61
  }
59
62
  const anomalous = [...ipsByUser.entries()].filter(([, ips]) => ips.size >= DISTINCT_IP_THRESHOLD);
60
- if (rows.length >= MAX_ROWS) {
63
+ if (fetched.length >= MAX_ROWS) {
61
64
  findings.push({
62
65
  id: 'login-anomaly-truncated',
63
66
  category: this.category,
64
67
  riskLevel: 'INFO',
65
68
  title: `Login history truncated at ${MAX_ROWS} rows — analysis is partial`,
66
- detail: `The last-7-day successful-login volume exceeded ${MAX_ROWS} rows, so this analysis covers only the most recent window. Some per-user IP spread may be undercounted.`,
69
+ detail: `The last-7-day login volume exceeded ${MAX_ROWS} rows, so this analysis covers only the most recent window. Some per-user IP spread may be undercounted.`,
67
70
  remediation: 'Forward LoginHistory to a SIEM for complete, continuous analysis rather than point-in-time sampling.',
68
71
  });
69
72
  }
@@ -21,6 +21,8 @@ export class LoginSessionCheck {
21
21
  category: this.category,
22
22
  riskLevel: failedRiskLevel,
23
23
  title: `${failedCount} failed login attempt(s) in the last 30 days`,
24
+ // A handful of failures is ordinary typing; only the higher bands ask for action.
25
+ passed: failedRiskLevel === 'LOW' || undefined,
24
26
  detail: `There were ${failedCount} failed login attempts out of ${totalLogins} total logins in the last 30 days.`,
25
27
  remediation: 'Investigate accounts with repeated failures. Consider IP restrictions or additional MFA policies for high-failure accounts.',
26
28
  });
@@ -1,3 +1,4 @@
1
+ import { hasField } from '../support/schema.js';
1
2
  // Experience Cloud / portal user types that represent external human users
2
3
  const EXTERNAL_USER_TYPES = ['CsnOnly', 'CustomerSuccess', 'PowerPartner', 'PowerCustomerSuccess', 'SelfService'];
3
4
  export class MfaEnforcementCheck {
@@ -32,16 +33,32 @@ export class MfaEnforcementCheck {
32
33
  // Query 2: portal users who have MFA explicitly enforced via permission
33
34
  let mfaEnforcedIds = new Set();
34
35
  try {
36
+ // Absent permission: MFA cannot be read from permissions, so it is unknown (see the catch).
37
+ if (!(await hasField(ctx, 'PermissionSet', 'PermissionsForceTwoFactor'))) {
38
+ return {
39
+ findings: [
40
+ {
41
+ id: 'mfa-enforcement-not-available',
42
+ category: this.category,
43
+ riskLevel: 'INFO',
44
+ inconclusive: true,
45
+ notAssessed: true,
46
+ title: `MFA enforcement for ${allPortalUsers.length} external/portal user(s) cannot be read from permissions in this org`,
47
+ detail: `This org has ${allPortalUsers.length} active external/portal user(s) but does not expose the "Multi-Factor Authentication for User Interface Logins" permission (PermissionSet.PermissionsForceTwoFactor), so whether they have MFA enforced cannot be established from permission assignments. SBS-AUTH-004 is unevaluated rather than failed.`,
48
+ remediation: 'Verify MFA for external users in the Experience Cloud site login settings, and at the identity provider where portal logins are federated.',
49
+ },
50
+ ],
51
+ };
52
+ }
35
53
  const mfaResult = await ctx.soql.query(`SELECT AssigneeId
36
54
  FROM PermissionSetAssignment
37
- WHERE PermissionSet.PermissionsMultiFactorForUiLogins = true
55
+ WHERE PermissionSet.PermissionsForceTwoFactor = true
38
56
  AND Assignee.IsActive = true
39
57
  AND Assignee.UserType IN (${userTypeList})`);
40
58
  mfaEnforcedIds = new Set(mfaResult.records.map((r) => r.AssigneeId));
41
59
  }
42
- catch {
43
- // PermissionsMultiFactorForUiLogins is absent in some editions, so this query legitimately
44
- // fails. It previously fell through with an empty set, which is not a neutral default: with
60
+ catch (err) {
61
+ // The query failed (the absent-field case is handled above). It previously fell through with an empty set, which is not a neutral default: with
45
62
  // nothing enforced every portal user lands in `withoutMfa`, and the check then stated as
46
63
  // established fact, at HIGH, that each named user lacks MFA. Over-reporting is not the safe
47
64
  // direction — it produces a remediation task against real users and an SBS-AUTH-004 claim
@@ -54,8 +71,8 @@ export class MfaEnforcementCheck {
54
71
  riskLevel: 'INFO',
55
72
  inconclusive: true,
56
73
  title: `MFA enforcement for ${allPortalUsers.length} external/portal user(s) could not be determined`,
57
- detail: `This org has ${allPortalUsers.length} active external/portal user(s), but PermissionSetAssignment could not be filtered on PermissionsMultiFactorForUiLogins. The field is absent in some editions, and the query also fails without access to PermissionSetAssignment. Whether these users have MFA enforced is therefore unestablished, so SBS-AUTH-004 is unevaluated rather than failed.`,
58
- remediation: 'Grant the audit user read access to PermissionSetAssignment and re-run. If the permission does not exist in this edition, verify MFA for external users manually in Setup, and through the identity provider where portal logins are federated.',
74
+ detail: `This org has ${allPortalUsers.length} active external/portal user(s), but who holds PermissionsForceTwoFactor could not be read. Whether these users have MFA enforced is therefore unestablished, so SBS-AUTH-004 is unevaluated rather than failed. The org said: ${err instanceof Error ? err.message : String(err)}`,
75
+ remediation: 'Check the error above. If it is an access error, confirm the audit user can read PermissionSetAssignment (View Setup and Configuration) and re-run; otherwise verify MFA for external users manually in Setup, and through the identity provider where portal logins are federated.',
59
76
  },
60
77
  ],
61
78
  };
@@ -24,19 +24,34 @@ export class MfaMethodStrengthCheck {
24
24
  const findings = [];
25
25
  const baseUrl = ctx.orgInfo.instanceUrl;
26
26
  const setupUrl = `${baseUrl}/lightning/setup/SetupOneIdEntityManagement/home`;
27
- const registrations = ctx.cache.mfaRegistrations ?? [];
28
- if (registrations.length === 0) {
27
+ const cached = ctx.cache.mfaRegistrations;
28
+ // Unset means registration data was never gathered; an empty list means nobody has registered,
29
+ // which mfa-registration reports. Only the first is unknown.
30
+ if (cached === undefined) {
29
31
  findings.push({
30
32
  id: 'mfa-no-data',
31
33
  category: this.category,
32
34
  riskLevel: 'INFO',
33
35
  inconclusive: true,
34
36
  title: 'No MFA registration data available: MfaRegistrationCheck must run first',
35
- detail: 'The mfaRegistrations cache is empty. Either MfaRegistrationCheck did not run, or TwoFactorInfo was not accessible. MFA method strength analysis cannot be performed without this data.',
37
+ detail: 'MFA registration data was not gathered: either MfaRegistrationCheck did not run, or TwoFactorInfo could not be read. MFA method strength analysis cannot be performed without this data.',
36
38
  remediation: 'Ensure MfaRegistrationCheck runs before this check. Grant "Manage Multi-Factor Authentication in API" permission to the audit user.',
37
39
  });
38
40
  return { findings };
39
41
  }
42
+ const registrations = cached;
43
+ if (registrations.length === 0) {
44
+ findings.push({
45
+ id: 'mfa-method-strength-none-registered',
46
+ category: this.category,
47
+ riskLevel: 'INFO',
48
+ passed: true,
49
+ title: 'No registered MFA methods to grade',
50
+ detail: 'No active internal user has a registered MFA method, so there is no method strength to assess. Missing registration itself is reported by the MFA registration check.',
51
+ remediation: 'None for method strength. Address MFA registration coverage first.',
52
+ });
53
+ return { findings };
54
+ }
40
55
  let phishingResistantCount = 0;
41
56
  let strongCount = 0;
42
57
  let weakOnlyCount = 0;