@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,4 +1,7 @@
1
1
  const MAX_OBJECTS = 25; // cap describe calls
2
+ // FieldDefinition must be filtered by entity ("a filter on a reified column is required"), so the
3
+ // scan covers these key standard objects, the same set data-classification checks.
4
+ const SCANNED_OBJECTS = ['Account', 'Contact', 'Lead', 'Opportunity', 'Case', 'Contract', 'User', 'Individual'];
2
5
  /**
3
6
  * Cross-references data classification against ACTUAL field encryption. `data-
4
7
  * classification` confirms Shield is licensed and that fields are classified;
@@ -18,20 +21,23 @@ export class EncryptionCoverageCheck {
18
21
  // 1. Sensitive fields = those with a ComplianceGroup (PII/PCI/HIPAA/GDPR/...).
19
22
  let classified;
20
23
  try {
21
- classified = await ctx.tooling.query(`SELECT EntityDefinition.QualifiedApiName obj, QualifiedApiName field
22
- FROM FieldDefinition WHERE ComplianceGroup != null`);
24
+ classified = await ctx.tooling.query(`SELECT EntityDefinition.QualifiedApiName, QualifiedApiName
25
+ FROM FieldDefinition
26
+ WHERE EntityDefinition.QualifiedApiName IN (${SCANNED_OBJECTS.map((o) => `'${o}'`).join(', ')})
27
+ AND ComplianceGroup != null`);
23
28
  }
24
- catch {
25
- findings.push(this.inconclusive('Classified fields could not be queried (Tooling API access needed)'));
29
+ catch (err) {
30
+ findings.push(this.inconclusive('Classified fields could not be queried', `The Tooling API FieldDefinition query failed: ${err instanceof Error ? err.message : String(err)}`));
26
31
  return { findings };
27
32
  }
28
33
  const fieldsByObj = new Map();
29
34
  for (const c of classified) {
30
- if (!c.obj || !c.field)
35
+ const obj = c.EntityDefinition?.QualifiedApiName;
36
+ if (!obj || !c.QualifiedApiName)
31
37
  continue;
32
- const set = fieldsByObj.get(c.obj) ?? new Set();
33
- set.add(c.field);
34
- fieldsByObj.set(c.obj, set);
38
+ const set = fieldsByObj.get(obj) ?? new Set();
39
+ set.add(c.QualifiedApiName);
40
+ fieldsByObj.set(obj, set);
35
41
  }
36
42
  if (fieldsByObj.size === 0) {
37
43
  findings.push({
@@ -39,8 +45,8 @@ export class EncryptionCoverageCheck {
39
45
  category: this.category,
40
46
  riskLevel: 'LOW',
41
47
  passed: true,
42
- title: 'No fields are classified as sensitive',
43
- detail: 'No fields carry a ComplianceGroup (data classification), so encryption coverage cannot be assessed against a sensitivity baseline. Classification is the prerequisite — see the data-classification check.',
48
+ title: 'No fields are classified as sensitive on the key standard objects',
49
+ detail: `No fields on ${SCANNED_OBJECTS.join(', ')} carry a ComplianceGroup (data classification), so encryption coverage cannot be assessed against a sensitivity baseline. Custom objects are not scanned. Classification is the prerequisite — see the data-classification check.`,
44
50
  remediation: 'Classify PII/PHI fields (Setup → Data Classification) first, then encrypt the sensitive ones with Shield Platform Encryption.',
45
51
  });
46
52
  return { findings };
@@ -66,7 +72,7 @@ export class EncryptionCoverageCheck {
66
72
  }
67
73
  }
68
74
  if (!describedAny) {
69
- findings.push(this.inconclusive('Object describes were not accessible, so field encryption could not be confirmed'));
75
+ findings.push(this.inconclusive('Object describes were not accessible, so field encryption could not be confirmed', 'The audit user could not describe the classified objects, so per-field encryption is unknown.'));
70
76
  return { findings };
71
77
  }
72
78
  if (unencrypted.length > 0) {
@@ -87,21 +93,21 @@ export class EncryptionCoverageCheck {
87
93
  riskLevel: 'LOW',
88
94
  passed: true,
89
95
  title: 'All classified sensitive fields checked are encrypted at rest',
90
- detail: `Every classified field found across ${Math.min(fieldsByObj.size, MAX_OBJECTS)} object(s) is encrypted with Shield Platform Encryption.`,
96
+ detail: `Every classified field found across ${Math.min(fieldsByObj.size, MAX_OBJECTS)} object(s) is encrypted with Shield Platform Encryption. Scanned: ${SCANNED_OBJECTS.join(', ')}; custom objects are not scanned.`,
91
97
  remediation: 'Keep encryption policy in sync as new sensitive fields are added and classified.',
92
98
  });
93
99
  }
94
100
  return { findings };
95
101
  }
96
- inconclusive(what) {
102
+ inconclusive(what, detail) {
97
103
  return {
98
104
  id: 'encryption-coverage-inconclusive',
99
105
  category: this.category,
100
106
  riskLevel: 'INFO',
101
107
  inconclusive: true,
102
108
  title: `${what}`,
103
- detail: 'The audit user could not gather the classification/describe data needed to assess encryption coverage.',
104
- remediation: 'Grant the audit user Tooling API access and object describe (View Setup and Configuration), then re-run.',
109
+ detail: `${detail} Encryption coverage is unassessed, not clean.`,
110
+ remediation: 'Check the error above. If it is an access error, confirm the audit user has API Enabled and View Setup and Configuration, then re-run.',
105
111
  };
106
112
  }
107
113
  }
@@ -1,3 +1,17 @@
1
+ // Organization has no MyDomain field. Every org's My Domain is the subdomain of its instance URL
2
+ // (<name>.my.salesforce.com, or a sandbox/develop/scratch variant); a legacy instance host such as
3
+ // na1.salesforce.com means no My Domain.
4
+ const MY_DOMAIN_HOST = /^(.+?)\.(?:(?:sandbox|develop|scratch|trailblaze)\.)?my\.(?:salesforce\.com|salesforce\.mil|sfcrmproducts\.cn)$/i;
5
+ function myDomainOf(instanceUrl) {
6
+ let host = instanceUrl;
7
+ try {
8
+ host = new URL(instanceUrl).hostname;
9
+ }
10
+ catch {
11
+ // keep the raw string
12
+ }
13
+ return MY_DOMAIN_HOST.exec(host)?.[1] ?? null;
14
+ }
1
15
  // Enhanced Domains changes the URL format for Salesforce org pages, Experience Cloud sites,
2
16
  // Visualforce pages, and Lightning apps. The new format uses org-specific subdomains
3
17
  // that prevent cross-org cookie and credential leakage.
@@ -33,7 +47,7 @@ export class EnhancedDomainsCheck {
33
47
  const findings = [];
34
48
  const baseUrl = ctx.orgInfo.instanceUrl;
35
49
  const domainSetupUrl = `${baseUrl}/lightning/setup/MyDomain/home`;
36
- const orgResult = await ctx.soql.query(`SELECT MyDomain, IsSandbox, InstanceName FROM Organization LIMIT 1`);
50
+ const orgResult = await ctx.soql.query(`SELECT IsSandbox, InstanceName FROM Organization LIMIT 1`);
37
51
  const org = orgResult.records[0];
38
52
  if (!org) {
39
53
  findings.push({
@@ -47,7 +61,8 @@ export class EnhancedDomainsCheck {
47
61
  });
48
62
  return { findings };
49
63
  }
50
- const { MyDomain: myDomain, IsSandbox: isSandbox } = org;
64
+ const { IsSandbox: isSandbox } = org;
65
+ const myDomain = myDomainOf(baseUrl);
51
66
  const instanceUrl = baseUrl;
52
67
  const instanceHost = hostnameOf(instanceUrl);
53
68
  // Check if Enhanced Domains is active based on the instance URL format
@@ -6,5 +6,7 @@ export declare class EscalationPermsCheck implements SecurityCheck {
6
6
  readonly category = "Permissions";
7
7
  readonly description = "Flags users holding lateral-movement/persistence permissions (Manage Internal Users, Assign Permission Sets, Modify Metadata, Manage Auth Providers, etc.)";
8
8
  run(ctx: AuditContext): Promise<CheckResult>;
9
+ /** Active, unfrozen users holding Modify All Data, View All Data and Manage Users across their assignments. */
10
+ private superAdminIds;
9
11
  }
10
12
  //# sourceMappingURL=EscalationPermsCheck.d.ts.map
@@ -1,10 +1,14 @@
1
+ import { presentFields } from '../support/schema.js';
2
+ // Hygiene, not escalation: they weaken a credential or widen visibility, but give no way to grant
3
+ // oneself more access. Reported apart so they never stand in for an escalation path. RULE-077.
4
+ const HYGIENE = new Set(['Password Never Expires', 'View All Users']);
1
5
  const PERMS = [
2
6
  ['PermissionsManageInternalUsers', 'Manage Internal Users'],
3
7
  ['PermissionsAssignPermissionSets', 'Assign Permission Sets'],
4
8
  ['PermissionsModifyMetadata', 'Modify Metadata'],
5
9
  ['PermissionsManageAuthProviders', 'Manage Auth. Providers'],
6
10
  ['PermissionsManageConnectedApps', 'Manage Connected Apps'],
7
- ['PermissionsManageSession', 'Manage Session Permission Set Activations'],
11
+ ['PermissionsManageSessionPermissionSets', 'Manage Session Permission Set Activations'],
8
12
  ['PermissionsPasswordNeverExpires', 'Password Never Expires'],
9
13
  ['PermissionsViewAllUsers', 'View All Users'],
10
14
  ];
@@ -16,10 +20,15 @@ export class EscalationPermsCheck {
16
20
  async run(ctx) {
17
21
  const findings = [];
18
22
  const baseUrl = ctx.orgInfo.instanceUrl;
19
- const permFields = PERMS.map(([f]) => `PermissionSet.${f}`).join(', ');
20
- const permWhere = PERMS.map(([f]) => `PermissionSet.${f} = true`).join(' OR ');
21
23
  let rows;
24
+ // Manage Connected Apps and similar exist only in some orgs; one absent field fails the whole
25
+ // query. Select only those this org has: a permission it lacks cannot be held.
26
+ let perms = PERMS;
22
27
  try {
28
+ const present = new Set(await presentFields(ctx, 'PermissionSet', PERMS.map(([f]) => f)));
29
+ perms = PERMS.filter(([f]) => present.has(f));
30
+ const permFields = perms.map(([f]) => `PermissionSet.${f}`).join(', ');
31
+ const permWhere = perms.map(([f]) => `PermissionSet.${f} = true`).join(' OR ');
23
32
  rows = await ctx.soql.queryAll(`SELECT AssigneeId, Assignee.Username, ${permFields}
24
33
  FROM PermissionSetAssignment
25
34
  WHERE (${permWhere}) AND Assignee.IsActive = true`);
@@ -32,14 +41,29 @@ export class EscalationPermsCheck {
32
41
  riskLevel: 'INFO',
33
42
  inconclusive: true,
34
43
  title: 'Privilege-escalation permission check could not be completed',
35
- detail: `The PermissionSetAssignment query was not accessible: ${msg}`,
36
- remediation: 'Grant the audit user "View Setup and Configuration", then re-run the audit.',
44
+ detail: `Who holds escalation permissions could not be read, so this is unassessed. The org said: ${msg}`,
45
+ remediation: 'Check the error above. If it is an access error, confirm the audit user has "View Setup and Configuration", then re-run the audit.',
37
46
  });
38
47
  return { findings };
39
48
  }
49
+ // A super-admin (Modify All Data + View All Data + Manage Users) already has unrestricted control,
50
+ // rated by users-super-admin-combo. Escalation permissions matter on everyone else. RULE-077.
51
+ let superAdmins = new Set();
52
+ try {
53
+ superAdmins = await this.superAdminIds(ctx);
54
+ }
55
+ catch {
56
+ // Without the super-admin list, keep every holder: over-reporting beats hiding a holder.
57
+ }
40
58
  const affected = [];
59
+ let leftOut = 0;
41
60
  for (const row of rows) {
42
- for (const [field, label] of PERMS) {
61
+ if (superAdmins.has(row.AssigneeId)) {
62
+ if (perms.some(([field]) => row.PermissionSet[field]))
63
+ leftOut++;
64
+ continue;
65
+ }
66
+ for (const [field, label] of perms) {
43
67
  if (row.PermissionSet[field]) {
44
68
  affected.push({ username: row.Assignee?.Username ?? row.AssigneeId, userId: row.AssigneeId, perm: label });
45
69
  }
@@ -51,27 +75,70 @@ export class EscalationPermsCheck {
51
75
  category: this.category,
52
76
  riskLevel: 'LOW',
53
77
  passed: true,
54
- title: 'No users hold privilege-escalation permissions',
55
- detail: 'No active users were found holding lateral-movement or persistence permissions.',
78
+ title: leftOut > 0 ? 'Only super-admins hold privilege-escalation permissions' : 'No users hold privilege-escalation permissions',
79
+ detail: leftOut > 0
80
+ ? 'Escalation permissions are held only by super-admins, who already have unrestricted control and are rated in the super-admin finding (users-super-admin-combo).'
81
+ : 'No active users were found holding lateral-movement or persistence permissions.',
56
82
  remediation: 'Continue to review escalation permissions periodically.',
57
83
  });
58
84
  return { findings };
59
85
  }
60
- findings.push({
61
- id: 'escalation-perms-found',
62
- category: this.category,
63
- riskLevel: 'HIGH',
64
- title: `${affected.length} escalation-permission grant(s) across active users`,
65
- detail: 'These permissions let a user create accounts, reset passwords, assign permission sets, modify metadata, ' +
66
- 'or register auth providers: the primitives an attacker uses for lateral movement and persistence after an initial foothold.',
67
- remediation: 'Remove these permissions from non-administrator profiles/permission sets and document who legitimately needs each one.',
68
- affectedItems: affected.map((a) => ({
69
- label: `${a.username}: ${a.perm}`,
70
- url: `${baseUrl}/${a.userId}`,
71
- note: 'Review and remove if not essential',
72
- })),
86
+ const leftOutNote = leftOut > 0
87
+ ? ` ${new Set(rows.filter((r) => superAdmins.has(r.AssigneeId)).map((r) => r.AssigneeId)).size} super-admin(s) also hold them and are rated in the super-admin finding instead.`
88
+ : '';
89
+ const item = (a) => ({
90
+ label: `${a.username}: ${a.perm}`,
91
+ url: `${baseUrl}/${a.userId}`,
92
+ note: 'Review and remove if not essential',
73
93
  });
94
+ const escalation = affected.filter((a) => !HYGIENE.has(a.perm));
95
+ const hygiene = affected.filter((a) => HYGIENE.has(a.perm));
96
+ if (escalation.length > 0) {
97
+ findings.push({
98
+ id: 'escalation-perms-found',
99
+ category: this.category,
100
+ riskLevel: 'HIGH',
101
+ title: `${escalation.length} escalation-permission grant(s) across active users`,
102
+ detail: 'These permissions let a user create accounts, reset passwords, assign permission sets, modify metadata, ' +
103
+ 'or register auth providers: the primitives an attacker uses for lateral movement and persistence after an initial foothold.' +
104
+ leftOutNote,
105
+ remediation: 'Remove these permissions from non-administrator profiles/permission sets and document who legitimately needs each one.',
106
+ affectedItems: escalation.map(item),
107
+ });
108
+ }
109
+ if (hygiene.length > 0) {
110
+ findings.push({
111
+ id: 'escalation-perms-hygiene',
112
+ category: this.category,
113
+ riskLevel: 'MEDIUM',
114
+ title: `${hygiene.length} grant(s) of Password Never Expires or View All Users to non-administrators`,
115
+ detail: 'Password Never Expires keeps a leaked password valid indefinitely; View All Users exposes the full user roster for targeting. ' +
116
+ 'Neither lets a user grant themselves more access.' +
117
+ leftOutNote,
118
+ remediation: 'Limit these to service accounts and administrators that need them, and document each.',
119
+ affectedItems: hygiene.map(item),
120
+ });
121
+ }
74
122
  return { findings };
75
123
  }
124
+ /** Active, unfrozen users holding Modify All Data, View All Data and Manage Users across their assignments. */
125
+ async superAdminIds(ctx) {
126
+ const rows = await ctx.soql.queryAll(`SELECT AssigneeId, PermissionSet.PermissionsModifyAllData, PermissionSet.PermissionsViewAllData, PermissionSet.PermissionsManageUsers
127
+ FROM PermissionSetAssignment
128
+ WHERE (PermissionSet.PermissionsModifyAllData = true OR PermissionSet.PermissionsViewAllData = true OR PermissionSet.PermissionsManageUsers = true)
129
+ AND Assignee.IsActive = true`);
130
+ const held = new Map();
131
+ for (const r of rows) {
132
+ const s = held.get(r.AssigneeId) ?? new Set();
133
+ if (r.PermissionSet.PermissionsModifyAllData)
134
+ s.add('mad');
135
+ if (r.PermissionSet.PermissionsViewAllData)
136
+ s.add('vad');
137
+ if (r.PermissionSet.PermissionsManageUsers)
138
+ s.add('mu');
139
+ held.set(r.AssigneeId, s);
140
+ }
141
+ return new Set([...held].filter(([, s]) => s.size === 3).map(([id]) => id));
142
+ }
76
143
  }
77
144
  //# sourceMappingURL=EscalationPermsCheck.js.map
@@ -1,3 +1,16 @@
1
+ /**
2
+ * Network has no guest-user field: each Experience site's guest user is on its Site record
3
+ * (SiteType ChatterNetwork, or ChatterNetworkPicasso for Experience Builder sites). Site carries
4
+ * no network id, so a Site belongs to a network when its label is the network's name, or its path
5
+ * prefix is the network's, the network's followed by "/s", or (LWR sites) followed by "vforcesite".
6
+ */
7
+ function siteBelongsTo(site, network) {
8
+ if (site.MasterLabel && site.MasterLabel === network.Name)
9
+ return true;
10
+ const net = network.UrlPathPrefix ?? '';
11
+ const sp = site.UrlPathPrefix ?? '';
12
+ return sp === net || sp === (net === '' ? 's' : `${net}/s`) || sp === `${net}vforcesite`;
13
+ }
1
14
  export class ExperienceCloudSiteCheck {
2
15
  id = 'experience-cloud-site';
3
16
  name = 'Experience Cloud Site Security';
@@ -9,18 +22,18 @@ export class ExperienceCloudSiteCheck {
9
22
  const setupUrl = `${baseUrl}/lightning/setup/SetupNetworks/home`;
10
23
  let networks;
11
24
  try {
12
- networks = await ctx.soql.queryAll(`SELECT Id, Name, Status, UrlPathPrefix, SelfRegProfileId, GuestUserId
25
+ networks = await ctx.soql.queryAll(`SELECT Id, Name, Status, UrlPathPrefix, SelfRegProfileId
13
26
  FROM Network
14
27
  WHERE Status = 'Live'`);
15
28
  }
16
- catch {
29
+ catch (err) {
17
30
  findings.push({
18
31
  id: 'experience-cloud-site-inaccessible',
19
32
  category: this.category,
20
33
  riskLevel: 'INFO',
21
34
  inconclusive: true,
22
35
  title: 'Experience Cloud site configuration could not be queried',
23
- detail: 'The Network SOQL query was not accessible. This may indicate the audit user lacks access to Experience Cloud configuration or no sites are provisioned.',
36
+ detail: `The Network query failed: ${err instanceof Error ? err.message : String(err)}. If no Experience Cloud licence is active, this check is not applicable.`,
24
37
  remediation: 'Grant "View Setup and Configuration" to the audit user and re-run. If no Experience Cloud licence is active, this check is not applicable.',
25
38
  });
26
39
  return { findings };
@@ -38,7 +51,45 @@ export class ExperienceCloudSiteCheck {
38
51
  return { findings };
39
52
  }
40
53
  const selfRegSites = networks.filter((n) => n.SelfRegProfileId !== null);
41
- const guestSites = networks.filter((n) => n.GuestUserId !== null);
54
+ let sites;
55
+ try {
56
+ sites = await ctx.soql.queryAll(`SELECT MasterLabel, UrlPathPrefix, GuestUserId, GuestUser.IsActive
57
+ FROM Site
58
+ WHERE SiteType IN ('ChatterNetwork', 'ChatterNetworkPicasso') AND Status = 'Active'`);
59
+ }
60
+ catch {
61
+ sites = null;
62
+ }
63
+ const guestSites = sites === null
64
+ ? []
65
+ : networks.filter((n) => sites.some((s) => s.GuestUserId !== null && s.GuestUser?.IsActive !== false && siteBelongsTo(s, n)));
66
+ // A live network whose Site record could not be found has unknown guest access, not none.
67
+ const unmatched = sites === null ? [] : networks.filter((n) => !sites.some((s) => siteBelongsTo(s, n)));
68
+ if (unmatched.length > 0) {
69
+ findings.push({
70
+ id: 'experience-cloud-site-guest-unknown',
71
+ category: this.category,
72
+ riskLevel: 'INFO',
73
+ inconclusive: true,
74
+ title: `Guest access could not be determined for ${unmatched.length} live Experience Cloud site(s)`,
75
+ detail: 'No active Site record could be matched to these live networks by name or path prefix, so whether they allow unauthenticated access is unknown, not absent.',
76
+ remediation: 'Review each site\'s guest user in Setup → Digital Experiences.',
77
+ affectedItems: unmatched.map((n) => ({ label: n.Name, url: setupUrl, note: `URL prefix: ${n.UrlPathPrefix ?? '(default)'}` })),
78
+ });
79
+ }
80
+ if (sites === null) {
81
+ // Without the Site records, guest access is unknown, not absent.
82
+ findings.push({
83
+ id: 'experience-cloud-site-guest-unknown',
84
+ category: this.category,
85
+ riskLevel: 'INFO',
86
+ inconclusive: true,
87
+ title: 'Guest access on live Experience Cloud sites could not be determined',
88
+ detail: 'The Site records that carry each Experience site\'s guest user could not be read, so whether these sites allow unauthenticated access is unknown.',
89
+ remediation: 'Review each site\'s guest user in Setup → Digital Experiences, or grant "View Setup and Configuration" and re-run.',
90
+ affectedItems: networks.map((n) => ({ label: n.Name, url: setupUrl })),
91
+ });
92
+ }
42
93
  if (selfRegSites.length > 0) {
43
94
  findings.push({
44
95
  id: 'experience-cloud-site-self-registration',
@@ -69,7 +120,7 @@ export class ExperienceCloudSiteCheck {
69
120
  })),
70
121
  });
71
122
  }
72
- if (selfRegSites.length === 0 && guestSites.length === 0) {
123
+ if (selfRegSites.length === 0 && guestSites.length === 0 && sites !== null && unmatched.length === 0) {
73
124
  findings.push({
74
125
  id: 'experience-cloud-site-ok',
75
126
  category: this.category,
@@ -1,8 +1,5 @@
1
1
  import { queryIfPresent } from '../support/missingObject.js';
2
- function isMissingPrmField(err) {
3
- const msg = err instanceof Error ? err.message : String(err);
4
- return /No such column 'IsPrmSuperUser'/i.test(msg);
5
- }
2
+ import { hasField } from '../support/schema.js';
6
3
  export class ExternalAccountHierarchyExposureCheck {
7
4
  id = 'external-account-hierarchy-exposure';
8
5
  name = 'External Account Hierarchy & Partner Super User Exposure';
@@ -13,17 +10,12 @@ export class ExternalAccountHierarchyExposureCheck {
13
10
  const baseUrl = ctx.orgInfo.instanceUrl;
14
11
  const usersUrl = `${baseUrl}/lightning/setup/ManageUsers/home`;
15
12
  // 1. Active users with Partner Super User access. User.IsPrmSuperUser only exists in orgs
16
- // with a partner (PRM) licence; there its absence means no super users. Any other error
17
- // propagates so the check reports inconclusive rather than clean.
18
- let superUsers;
19
- try {
20
- superUsers = await ctx.soql.queryAll('SELECT Id, Username, IsActive, IsPrmSuperUser FROM User WHERE IsPrmSuperUser = true AND IsActive = true');
21
- }
22
- catch (err) {
23
- if (!isMissingPrmField(err))
24
- throw err;
25
- superUsers = [];
26
- }
13
+ // with a partner (PRM) licence; without it no user can be a super user, so the field is
14
+ // described first rather than queried blind. Query errors propagate so the check reports
15
+ // inconclusive rather than clean.
16
+ const superUsers = (await hasField(ctx, 'User', 'IsPrmSuperUser'))
17
+ ? await ctx.soql.queryAll('SELECT Id, Username, IsActive, IsPrmSuperUser FROM User WHERE IsPrmSuperUser = true AND IsActive = true')
18
+ : [];
27
19
  if (superUsers.length > 0) {
28
20
  findings.push({
29
21
  id: 'external-account-hierarchy-super-users',
@@ -18,17 +18,20 @@ export class ExternalCredentialsCheck {
18
18
  const findings = [];
19
19
  const baseUrl = ctx.orgInfo.instanceUrl;
20
20
  let creds;
21
+ let error = '';
21
22
  try {
22
- creds = await ctx.soql.queryAll('SELECT Id, DeveloperName, AuthenticationProtocol FROM ExternalCredential');
23
+ // ExternalCredential is served by the Tooling API; the standard API does not support it.
24
+ creds = await ctx.tooling.query('SELECT Id, DeveloperName, AuthenticationProtocol FROM ExternalCredential');
23
25
  }
24
- catch {
26
+ catch (err) {
27
+ error = err instanceof Error ? err.message : String(err);
25
28
  findings.push({
26
29
  id: 'external-credentials-inconclusive',
27
30
  category: this.category,
28
31
  riskLevel: 'INFO',
29
32
  inconclusive: true,
30
33
  title: 'External Credentials could not be queried (insufficient access or unsupported)',
31
- detail: 'The ExternalCredential object was not accessible. This can mean the org has not migrated to External Credentials, or the audit user lacks access.',
34
+ detail: `The ExternalCredential Tooling query failed: ${error}`,
32
35
  remediation: 'Grant the audit user View Setup and Configuration and re-run. Also review Setup → Named Credentials → External Credentials manually.',
33
36
  });
34
37
  return { findings };
@@ -1,3 +1,9 @@
1
+ // LoginHistory has no IsSuccess field, and Status cannot be filtered (not in WHERE, not in
2
+ // HAVING). It can be grouped, so failures are counted by grouping on Status and dropping the
3
+ // 'Success' group in code.
4
+ const SUCCESS = 'Success';
5
+ // An aggregate query returns at most 2,000 groups and cannot be paged.
6
+ const MAX_GROUPS = 2000;
1
7
  // Thresholds for brute-force / credential stuffing detection (7-day window)
2
8
  const BRUTE_FORCE_PER_USER = 20; // >20 failures for one user = targeted attack
3
9
  const BULK_THRESHOLD_PER_USER = 50; // >50 = highly likely automated attack
@@ -14,17 +20,18 @@ export class FailedLoginCheck {
14
20
  // Query 1: total failed logins in last 7 days
15
21
  let totalFailures = 0;
16
22
  try {
17
- const countResult = await ctx.soql.query(`SELECT COUNT() FROM LoginHistory WHERE IsSuccess = false AND LoginTime > LAST_N_DAYS:7`);
18
- totalFailures = countResult.totalSize;
23
+ const byStatus = await ctx.soql.query(`SELECT Status, COUNT(Id) FROM LoginHistory WHERE LoginTime > LAST_N_DAYS:7 GROUP BY Status`);
24
+ totalFailures = byStatus.records.filter((r) => r.Status !== SUCCESS).reduce((n, r) => n + r.expr0, 0);
19
25
  }
20
- catch {
26
+ catch (err) {
21
27
  findings.push({
22
28
  id: 'failed-login-inaccessible',
23
29
  category: this.category,
24
30
  riskLevel: 'INFO',
25
31
  inconclusive: true,
26
32
  title: 'LoginHistory could not be queried: failed login analysis skipped',
27
- detail: 'The LoginHistory SOQL query was not accessible. This may indicate the audit user lacks "View All Users" or event monitoring access.',
33
+ detail: `The LoginHistory query failed: ${err instanceof Error ? err.message : String(err)}. ` +
34
+ 'If the org denied access, the audit user may lack "View All Users".',
28
35
  remediation: 'Grant "View All Users" to the audit user. For event-level access, enable Event Monitoring.',
29
36
  });
30
37
  return { findings };
@@ -45,13 +52,33 @@ export class FailedLoginCheck {
45
52
  let perUserCounts = [];
46
53
  let perUserUnavailable = false;
47
54
  try {
48
- const aggResult = await ctx.soql.query(`SELECT Username, COUNT(Id)
55
+ const aggResult = await ctx.soql.query(`SELECT UserId, Status, COUNT(Id)
49
56
  FROM LoginHistory
50
- WHERE IsSuccess = false AND LoginTime > LAST_N_DAYS:7
51
- GROUP BY Username
57
+ WHERE LoginTime > LAST_N_DAYS:7
58
+ GROUP BY UserId, Status
52
59
  ORDER BY COUNT(Id) DESC
53
- LIMIT 50`);
54
- perUserCounts = aggResult.records;
60
+ LIMIT ${MAX_GROUPS}`);
61
+ const failuresByUser = new Map();
62
+ for (const r of aggResult.records) {
63
+ if (r.Status === SUCCESS)
64
+ continue;
65
+ failuresByUser.set(r.UserId, (failuresByUser.get(r.UserId) ?? 0) + r.expr0);
66
+ }
67
+ const ranked = [...failuresByUser.entries()].sort((a, b) => b[1] - a[1]).slice(0, 50);
68
+ // LoginHistory has no Username field and no User relationship: resolve names separately.
69
+ const names = new Map();
70
+ if (ranked.length > 0) {
71
+ const inClause = ranked.map(([id]) => `'${id}'`).join(',');
72
+ const users = await ctx.soql.queryAll(`SELECT Id, Username FROM User WHERE Id IN (${inClause})`);
73
+ for (const u of users)
74
+ names.set(u.Id, u.Username);
75
+ }
76
+ perUserCounts = ranked.map(([id, n]) => ({ Username: names.get(id) ?? id, expr0: n }));
77
+ // Groups are ranked by size across every status, so a full page may have cut off smaller
78
+ // failure groups. Targets found stand; "no target" is then not a conclusion.
79
+ if (aggResult.records.length >= MAX_GROUPS && !perUserCounts.some((r) => r.expr0 >= BRUTE_FORCE_PER_USER)) {
80
+ perUserUnavailable = true;
81
+ }
55
82
  }
56
83
  catch {
57
84
  // Recorded: without the per-user breakdown, "no brute-force pattern" is not a
@@ -14,16 +14,18 @@ export class FieldHistoryTrackingCheck {
14
14
  const setupUrl = `${baseUrl}/lightning/setup/ObjectManager/home`;
15
15
  const objectList = SENSITIVE_OBJECTS.map((o) => `'${o}'`).join(', ');
16
16
  try {
17
- // Tooling API: count fields with history tracking enabled per sensitive object.
18
- // Objects with zero tracked fields will be absent from the result — those are violations.
19
- const results = await ctx.tooling.query(`SELECT EntityDefinition.QualifiedApiName objectName, COUNT(Id) trackedCount
17
+ // Tooling API: the tracked fields on each sensitive object, counted here. FieldDefinition
18
+ // supports no aggregates (its Id is not aggregatable), so COUNT/GROUP BY is rejected.
19
+ // Objects with zero tracked fields are absent from the result — those are violations.
20
+ const results = await ctx.tooling.query(`SELECT EntityDefinition.QualifiedApiName, QualifiedApiName
20
21
  FROM FieldDefinition
21
22
  WHERE EntityDefinition.QualifiedApiName IN (${objectList})
22
- AND IsFieldHistoryTracked = true
23
- GROUP BY EntityDefinition.QualifiedApiName`);
23
+ AND IsFieldHistoryTracked = true`);
24
24
  const trackedMap = new Map();
25
25
  for (const r of results) {
26
- trackedMap.set(r.objectName, r.trackedCount ?? 0);
26
+ const obj = r.EntityDefinition?.QualifiedApiName;
27
+ if (obj)
28
+ trackedMap.set(obj, (trackedMap.get(obj) ?? 0) + 1);
27
29
  }
28
30
  const withTracking = SENSITIVE_OBJECTS.filter((o) => (trackedMap.get(o) ?? 0) > 0);
29
31
  const withoutTracking = SENSITIVE_OBJECTS.filter((o) => (trackedMap.get(o) ?? 0) === 0);
@@ -42,8 +44,9 @@ export class FieldHistoryTrackingCheck {
42
44
  findings.push({
43
45
  id: 'field-history-tracking-missing',
44
46
  category: this.category,
45
- riskLevel: withoutTracking.length >= 3 ? 'HIGH' : 'MEDIUM',
46
- title: `${withoutTracking.length} sensitive object(s) have no field history tracking: SBS-DATA-004`,
47
+ // Missing history limits investigation; it exposes nothing. RULE-078.
48
+ riskLevel: withoutTracking.length >= 3 ? 'MEDIUM' : 'LOW',
49
+ title: `${withoutTracking.length} sensitive object(s) have no field history tracking (investigation gap): SBS-DATA-004`,
47
50
  detail: `SBS-DATA-004 requires field history tracking on sensitive objects to capture who changed what data and when, enabling post-incident investigation and audit evidence. The following objects have no tracked fields: ${withoutTracking.join(', ')}. ${withTracking.length > 0 ? `Objects already configured: ${withTracking.map((o) => `${o} (${trackedMap.get(o)} field(s))`).join(', ')}.` : ''}`,
48
51
  remediation: 'Enable field history tracking on each listed object in Setup → Object Manager → [Object] → Fields & Relationships → Set History Tracking. At minimum track key sensitive fields: email addresses, phone numbers, revenue fields, owner changes, and status changes.',
49
52
  affectedItems: withoutTracking.map((name) => ({
@@ -53,15 +56,15 @@ export class FieldHistoryTrackingCheck {
53
56
  })),
54
57
  });
55
58
  }
56
- catch {
59
+ catch (err) {
57
60
  findings.push({
58
61
  id: 'field-history-tracking-inconclusive',
59
62
  category: this.category,
60
63
  riskLevel: 'INFO',
61
64
  inconclusive: true,
62
65
  title: 'Field history tracking status could not be determined',
63
- detail: 'SBS-DATA-004 requires field history tracking on sensitive objects. The Tooling API FieldDefinition query was not accessible with the current user permissions.',
64
- remediation: 'Grant the audit user Tooling API access, or manually verify field history tracking in Setup → Object Manager for Account, Contact, Lead, Opportunity, Case, Contract, and User.',
66
+ detail: `SBS-DATA-004 requires field history tracking on sensitive objects. The Tooling API FieldDefinition query failed, so tracking is unassessed, not absent: ${err instanceof Error ? err.message : String(err)}`,
67
+ remediation: 'Check the error above. If it is an access error, confirm the audit user has API Enabled and View Setup and Configuration; otherwise verify field history tracking manually in Setup → Object Manager for Account, Contact, Lead, Opportunity, Case, Contract, and User.',
65
68
  });
66
69
  }
67
70
  return { findings };
@@ -17,8 +17,8 @@ export class FlowHttpCalloutCredentialBypassCheck {
17
17
  async run(ctx) {
18
18
  const findings = [];
19
19
  const baseUrl = ctx.orgInfo.instanceUrl;
20
- const externalServices = await queryIfPresent(() => ctx.tooling.query('SELECT Id, DeveloperName, MasterLabel, NamedCredentialId FROM ExternalServiceRegistration'));
21
- const uncredentialedServices = externalServices.filter((s) => !s.NamedCredentialId || s.NamedCredentialId.trim() === '');
20
+ const externalServices = await queryIfPresent(() => ctx.tooling.query('SELECT Id, DeveloperName, MasterLabel, NamedCredential, NamedCredentialReferenceId FROM ExternalServiceRegistration'));
21
+ const uncredentialedServices = externalServices.filter((s) => !(s.NamedCredential ?? '').trim() && !(s.NamedCredentialReferenceId ?? '').trim());
22
22
  // Credentials live in the flow definition (formulas, constants, text templates, action
23
23
  // inputs), which only Flow.Metadata carries. Every string in it is scanned.
24
24
  const repo = new FlowRepository(ctx.soql, ctx.tooling);