@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,4 @@
1
+ import { hasField } from '../support/schema.js';
1
2
  export class ApiClientPermissionCheck {
2
3
  id = 'api-client-permission';
3
4
  name = 'Use Any API Client Permission';
@@ -7,7 +8,22 @@ export class ApiClientPermissionCheck {
7
8
  const findings = [];
8
9
  const baseUrl = ctx.orgInfo.instanceUrl;
9
10
  try {
10
- // Single query — PermissionsUseAnyApiClient may not exist in orgs without API Access Control
11
+ // PermissionsUseAnyApiClient is absent from orgs without API Access Control (and from
12
+ // some releases altogether). Describe first: filtering on an absent field is rejected.
13
+ // Absence is unassessed, not a pass: the bypass may exist under a name this check does not read.
14
+ if (!(await hasField(ctx, 'PermissionSet', 'PermissionsUseAnyApiClient'))) {
15
+ findings.push({
16
+ id: 'api-client-permission-not-available',
17
+ category: this.category,
18
+ riskLevel: 'INFO',
19
+ inconclusive: true,
20
+ notAssessed: true,
21
+ title: '"Use Any API Client" holders could not be read: the permission field is not in this org',
22
+ detail: 'This org has no PermissionSet.PermissionsUseAnyApiClient field, which is usual when API Access Control is not available. Who can bypass API client restrictions is therefore unestablished, and SBS-ACS-006 is unevaluated rather than satisfied.',
23
+ remediation: 'If API Access Control is enabled, review who holds "Use Any API Client" in Setup → Permission Sets.',
24
+ });
25
+ return { findings };
26
+ }
11
27
  const result = await ctx.soql.query(`SELECT Assignee.Id, Assignee.Username, Assignee.Profile.Name,
12
28
  PermissionSet.Name, PermissionSet.IsOwnedByProfile
13
29
  FROM PermissionSetAssignment
@@ -42,15 +58,15 @@ export class ApiClientPermissionCheck {
42
58
  })),
43
59
  });
44
60
  }
45
- catch {
61
+ catch (err) {
46
62
  findings.push({
47
63
  id: 'api-client-permission-inconclusive',
48
64
  category: this.category,
49
65
  riskLevel: 'INFO',
50
66
  inconclusive: true,
51
- title: '"Use Any API Client" permission check could not run: field may not exist in this org edition',
52
- detail: 'SBS-ACS-006 requires documented justification for the "Use Any API Client" permission. This field is part of the API Access Control feature and may not be available in all Salesforce editions.',
53
- remediation: 'Verify in Setup → Permission Sets whether "Use Any API Client" is available and review assignments if so.',
67
+ title: '"Use Any API Client" holders could not be read',
68
+ detail: `SBS-ACS-006 requires documented justification for the "Use Any API Client" permission. Who holds it could not be read, so this is unassessed. The org said: ${err instanceof Error ? err.message : String(err)}`,
69
+ remediation: 'Check the error above. If it is an access error, confirm the audit user can read PermissionSetAssignment (View Setup and Configuration); otherwise review assignments in Setup → Permission Sets.',
54
70
  });
55
71
  }
56
72
  return { findings };
@@ -1,3 +1,4 @@
1
+ import { hasField } from '../support/schema.js';
1
2
  export class AuditTrailCheck {
2
3
  id = 'audit-trail';
3
4
  name = 'Audit Trail';
@@ -70,6 +71,22 @@ export class AuditTrailCheck {
70
71
  // SBS-MON-002: flag users who can delete Event Monitoring data (erasing the audit trail).
71
72
  // PermissionsManageEventLogFiles grants the "Delete Event Monitoring Data" capability.
72
73
  try {
74
+ // The permission field exists only in orgs licensed for Event Monitoring. Describe first:
75
+ // filtering on an absent field is rejected outright. Absence is reported as unassessed,
76
+ // not as a pass: this audit has not confirmed the delete capability has no other API name.
77
+ if (!(await hasField(ctx, 'PermissionSet', 'PermissionsManageEventLogFiles'))) {
78
+ findings.push({
79
+ id: 'event-log-delete-permission-not-available',
80
+ category: this.category,
81
+ riskLevel: 'INFO',
82
+ inconclusive: true,
83
+ notAssessed: true,
84
+ title: 'Who can delete Event Monitoring data could not be read: the permission is not in this org',
85
+ detail: 'This org has no PermissionSet.PermissionsManageEventLogFiles field, which is usual when Event Monitoring is not licensed. Who can delete event monitoring data is therefore unestablished from permissions, and SBS-MON-002 is unevaluated rather than satisfied.',
86
+ remediation: 'If the org licenses Event Monitoring, review who holds "Manage Event Log Files" or "Delete Event Monitoring Data" in Setup → Permission Sets.',
87
+ });
88
+ return { findings };
89
+ }
73
90
  const eventLogDeleteResult = await ctx.soql.query(`SELECT Assignee.Id, Assignee.Username, Assignee.Profile.Name,
74
91
  PermissionSet.Name, PermissionSet.IsOwnedByProfile
75
92
  FROM PermissionSetAssignment
@@ -93,20 +110,18 @@ export class AuditTrailCheck {
93
110
  });
94
111
  }
95
112
  }
96
- catch {
97
- // PermissionsManageEventLogFiles does not exist in orgs without Event Monitoring, so this
98
- // query legitimately fails. Skipping silently was wrong: with no finding emitted, a reader
99
- // cannot tell "nobody can delete event logs" from "we were unable to find out", and only
100
- // the first of those is a pass. Declared inconclusive so it is scored as INFO, carries no
101
- // penalty, and is still shown.
113
+ catch (err) {
114
+ // Skipping silently was wrong: with no finding emitted, a reader cannot tell "nobody can
115
+ // delete event logs" from "we were unable to find out", and only the first of those is a
116
+ // pass. Declared inconclusive so it is scored as INFO, carries no penalty, and is still shown.
102
117
  findings.push({
103
118
  id: 'event-log-delete-permission-inconclusive',
104
119
  category: this.category,
105
120
  riskLevel: 'INFO',
106
121
  inconclusive: true,
107
122
  title: 'Manage Event Log Files assignments could not be queried',
108
- detail: 'PermissionSetAssignment could not be filtered on PermissionsManageEventLogFiles. The field is absent in orgs without Event Monitoring, and the query also fails without access to PermissionSetAssignment, so who can delete event monitoring data is unestablished. SBS-MON-002 is unevaluated rather than satisfied.',
109
- remediation: 'If the org has Event Monitoring, grant the audit user read access to PermissionSetAssignment and re-run. Otherwise there are no EventLogFile records to protect and no action is needed.',
123
+ detail: `Who holds "Manage Event Log Files" could not be read, so who can delete event monitoring data is unestablished. SBS-MON-002 is unevaluated rather than satisfied. The org said: ${err instanceof Error ? err.message : String(err)}`,
124
+ remediation: 'Check the error above. If it is an access error, confirm the audit user can read PermissionSetAssignment (View Setup and Configuration), then re-run.',
110
125
  });
111
126
  }
112
127
  return { findings };
@@ -65,7 +65,8 @@ export class CertificateExpiryCheck {
65
65
  findings.push({
66
66
  id: 'certificate-expiring-critical',
67
67
  category: this.category,
68
- riskLevel: 'CRITICAL',
68
+ // An expiring certificate is an outage risk, not a data exposure: HIGH, however urgent.
69
+ riskLevel: 'HIGH',
69
70
  title: `${critical.length} certificate(s) expire within 30 days`,
70
71
  detail: 'Expired certificates break all integrations, SSO logins, and JWT-based authentication that depend on them. Certificates expiring within 30 days require immediate replacement to avoid service disruption.',
71
72
  remediation: 'Renew or replace expiring certificates immediately. Update all integrations and connected apps that reference these certificates. Test authentication flows after replacement.',
@@ -1,3 +1,14 @@
1
+ // OAuth scopes and the refresh-token policy live only in the Metadata API definition: the Tooling
2
+ // ConnectedApplication object has no Metadata column. Each app is read by name, up to this many.
3
+ const MAX_METADATA_READS = 100;
4
+ /** The Metadata API returns a single scope as a string, several as an array. */
5
+ function normalise(meta) {
6
+ const scopes = meta.oauthConfig?.scopes;
7
+ if (meta.oauthConfig && typeof scopes === 'string') {
8
+ return { ...meta, oauthConfig: { ...meta.oauthConfig, scopes: [scopes] } };
9
+ }
10
+ return meta;
11
+ }
1
12
  // Scopes that grant effectively unlimited access as the authorising user.
2
13
  const OVERLY_BROAD_SCOPES = new Set(['Full', 'full']);
3
14
  // Refresh token policy values that indicate no expiry.
@@ -16,22 +27,67 @@ export class ConnectedAppScopeCheck {
16
27
  async run(ctx) {
17
28
  const findings = [];
18
29
  const setupUrl = `${ctx.orgInfo.instanceUrl}/lightning/setup/ConnectedApplication/home`;
19
- let apps = [];
30
+ let rows = [];
20
31
  try {
21
- apps = await ctx.tooling.query('SELECT Id, Name, Metadata FROM ConnectedApplication');
32
+ rows = await ctx.tooling.query('SELECT Id, Name, DeveloperName FROM ConnectedApplication');
22
33
  }
23
- catch {
34
+ catch (err) {
24
35
  findings.push({
25
36
  id: 'connected-app-scope-inconclusive',
26
37
  category: this.category,
27
38
  riskLevel: 'INFO',
28
39
  inconclusive: true,
29
40
  title: 'Connected app OAuth scope check could not be completed',
30
- detail: 'ConnectedApplication Metadata was not accessible via Tooling API. This may indicate a permissions issue on the audit user.',
31
- remediation: 'Grant the audit user the "Customize Application" permission to enable Tooling API access to connected app metadata.',
41
+ detail: `Connected apps could not be listed via the Tooling API: ${err instanceof Error ? err.message : String(err)}`,
42
+ remediation: 'Grant the audit user View Setup and Configuration, then re-run. Meanwhile review OAuth scopes in Setup → App Manager.',
32
43
  });
33
44
  return { findings };
34
45
  }
46
+ if (rows.length > 0 && !ctx.metadata) {
47
+ findings.push({
48
+ id: 'connected-app-scope-inconclusive',
49
+ category: this.category,
50
+ riskLevel: 'INFO',
51
+ inconclusive: true,
52
+ title: 'Connected app OAuth scope check could not be completed',
53
+ detail: `${rows.length} connected app(s) exist, but their OAuth scopes and refresh-token policies are only in the Metadata API, which this run cannot read.`,
54
+ remediation: 'Review OAuth scopes and refresh-token policies in Setup → App Manager.',
55
+ });
56
+ return { findings };
57
+ }
58
+ const apps = [];
59
+ const unread = [];
60
+ for (const [i, row] of rows.entries()) {
61
+ let meta = null;
62
+ if (i < MAX_METADATA_READS) {
63
+ try {
64
+ meta = await ctx.metadata.read('ConnectedApp', row.DeveloperName);
65
+ }
66
+ catch {
67
+ meta = null;
68
+ }
69
+ }
70
+ if (meta)
71
+ apps.push({ Id: row.Id, Name: row.Name, Metadata: normalise(meta) });
72
+ else
73
+ unread.push(row);
74
+ }
75
+ // An app whose definition could not be read is unassessed, never counted as scoped.
76
+ if (unread.length > 0) {
77
+ findings.push({
78
+ id: 'connected-app-scope-unread',
79
+ category: this.category,
80
+ riskLevel: 'INFO',
81
+ inconclusive: true,
82
+ title: `OAuth settings of ${unread.length} connected app(s) could not be read`,
83
+ detail: 'Their Metadata API definitions were not returned (a managed-package app is read under its namespace, and reads stop after ' +
84
+ `${MAX_METADATA_READS} apps). Their scopes and refresh-token policies are unassessed, not clean.`,
85
+ remediation: 'Review these apps\' OAuth scopes and refresh-token policies in Setup → App Manager.',
86
+ affectedItems: unread.map((app) => ({ label: app.Name, url: setupUrl })),
87
+ });
88
+ if (apps.length === 0)
89
+ return { findings };
90
+ }
35
91
  if (apps.length === 0) {
36
92
  findings.push({
37
93
  id: 'connected-app-scope-none',
@@ -1,3 +1,8 @@
1
+ /** Minutes, or null when the app sets no timeout of its own. */
2
+ function timeoutMinutes(app) {
3
+ const n = app.SessionTimeout === null || app.SessionTimeout === '' ? NaN : Number(app.SessionTimeout);
4
+ return Number.isFinite(n) && n > 0 ? n : null;
5
+ }
1
6
  /**
2
7
  * External Client Apps are absent from orgs that predate them, where the query answers with
3
8
  * INVALID_TYPE. That, and only that, means "none"; any other failure is reported as inconclusive.
@@ -17,7 +22,8 @@ export class ConnectedAppsCheck {
17
22
  const findings = [];
18
23
  const baseUrl = ctx.orgInfo.instanceUrl;
19
24
  // Single query fetches both access-control and session-timeout fields — no N+1 calls needed.
20
- const connectedApps = await ctx.soql.queryAll(`SELECT Id, Name, OptionsAllowAdminApprovedUsersOnly, SessionTimeout
25
+ // SessionTimeout is served only by the Tooling API; the standard API rejects the column.
26
+ const connectedApps = await ctx.tooling.query(`SELECT Id, Name, OptionsAllowAdminApprovedUsersOnly, SessionTimeout
21
27
  FROM ConnectedApplication`);
22
28
  const count = connectedApps.length;
23
29
  // External Client Apps are the successor to connected apps. Their policies (permitted users,
@@ -76,7 +82,10 @@ export class ConnectedAppsCheck {
76
82
  // SBS-DEP-006: access token (session) timeout must be ≤ 15 minutes for CLI/integration apps.
77
83
  // SessionTimeout = 0 means the app inherits the org-level session timeout (often 2–8 hours),
78
84
  // which exceeds the 15-minute SBS requirement. Flag null/0 and values > 15 minutes.
79
- const longSessionApps = connectedApps.filter((app) => app.SessionTimeout === null || app.SessionTimeout === 0 || app.SessionTimeout > 15);
85
+ const longSessionApps = connectedApps.filter((app) => {
86
+ const minutes = timeoutMinutes(app);
87
+ return minutes === null || minutes > 15;
88
+ });
80
89
  if (longSessionApps.length > 0) {
81
90
  findings.push({
82
91
  id: 'connected-apps-long-session-timeout',
@@ -88,9 +97,9 @@ export class ConnectedAppsCheck {
88
97
  affectedItems: longSessionApps.map((app) => ({
89
98
  label: app.Name,
90
99
  url: `${baseUrl}/${app.Id}`,
91
- note: app.SessionTimeout === null || app.SessionTimeout === 0
100
+ note: timeoutMinutes(app) === null
92
101
  ? 'No explicit timeout: inherits org default (likely > 15 min)'
93
- : `Session timeout: ${app.SessionTimeout} min, reduce to ≤ 15`,
102
+ : `Session timeout: ${timeoutMinutes(app)} min, reduce to ≤ 15`,
94
103
  })),
95
104
  });
96
105
  }
@@ -1,3 +1,7 @@
1
+ /** Live links read per run. A full page means more exist, so the result is partial. */
2
+ const LINK_LIMIT = 500;
3
+ /** A link expires only when PreferencesExpires is set; ExpiryDate alone is not enforced. */
4
+ const expires = (r) => r.PreferencesExpires && Boolean(r.ExpiryDate);
1
5
  // Links older than this with no expiry date are considered stale (SBS-FILE-003)
2
6
  const STALE_DAYS = 90;
3
7
  export class ContentLinksCheck {
@@ -11,25 +15,45 @@ export class ContentLinksCheck {
11
15
  // Single query — fetches all data needed for FILE-001 (no expiry),
12
16
  // FILE-002 (no password), and FILE-003 (stale links).
13
17
  let records;
18
+ let truncated = false;
14
19
  try {
15
- records = await ctx.soql.queryAll(`SELECT Id, Name, ContentDocumentId, ExpiryDate, PasswordEnabled, CreatedDate
20
+ // Every ContentDistribution is a public link (there is no IsPublic field). Links already past
21
+ // their expiry no longer serve the file, so they are excluded in the query, before the LIMIT:
22
+ // filtering after it could fill the page with dead links and hide live ones.
23
+ const now = Date.now();
24
+ const nowLiteral = new Date(now).toISOString().replace(/\.\d{3}Z$/, 'Z');
25
+ const all = await ctx.soql.queryAll(`SELECT Id, Name, ContentDocumentId, ExpiryDate, PreferencesExpires, PreferencesPasswordRequired, CreatedDate
16
26
  FROM ContentDistribution
17
- WHERE IsPublic = true
27
+ WHERE (PreferencesExpires = false OR ExpiryDate = null OR ExpiryDate > ${nowLiteral})
18
28
  ORDER BY CreatedDate ASC
19
- LIMIT 500`);
29
+ LIMIT ${LINK_LIMIT}`);
30
+ truncated = all.length >= LINK_LIMIT;
31
+ records = all.filter((r) => !(expires(r) && new Date(r.ExpiryDate).getTime() < now));
20
32
  }
21
- catch {
33
+ catch (err) {
22
34
  findings.push({
23
35
  id: 'content-links-inaccessible',
24
36
  category: this.category,
25
37
  riskLevel: 'INFO',
26
38
  inconclusive: true,
27
39
  title: 'Content distribution links could not be queried',
28
- detail: 'SBS-FILE-001/002/003 require review of public content distribution links. ContentDistribution was not accessible with the current user permissions.',
40
+ detail: `SBS-FILE-001/002/003 require review of public content distribution links. The ContentDistribution query failed: ${err instanceof Error ? err.message : String(err)}`,
29
41
  remediation: 'Grant the audit user read access to ContentDistribution records to enable this check.',
30
42
  });
31
43
  return { findings };
32
44
  }
45
+ if (truncated) {
46
+ // MN-051: links past the page were not read, so a clean result here proves nothing about them.
47
+ findings.push({
48
+ id: 'content-links-partial',
49
+ category: this.category,
50
+ riskLevel: 'INFO',
51
+ inconclusive: true,
52
+ title: `Only the oldest ${LINK_LIMIT} live public content links were reviewed`,
53
+ detail: `The org has more than ${LINK_LIMIT} live public content distribution links. Findings below cover the oldest ${LINK_LIMIT}; newer links were not reviewed, so their absence from a finding is not a pass.`,
54
+ remediation: 'Review public links in Setup or with a report on Content Deliveries, and expire or delete the ones no longer needed.',
55
+ });
56
+ }
33
57
  if (records.length === 0) {
34
58
  findings.push({
35
59
  id: 'content-links-none',
@@ -43,9 +67,9 @@ export class ContentLinksCheck {
43
67
  return { findings };
44
68
  }
45
69
  const staleThreshold = new Date(Date.now() - STALE_DAYS * 86_400_000);
46
- const noExpiry = records.filter((r) => !r.ExpiryDate);
47
- const noPassword = records.filter((r) => !r.PasswordEnabled);
48
- const stale = records.filter((r) => !r.ExpiryDate && new Date(r.CreatedDate) < staleThreshold);
70
+ const noExpiry = records.filter((r) => !expires(r));
71
+ const noPassword = records.filter((r) => !r.PreferencesPasswordRequired);
72
+ const stale = records.filter((r) => !expires(r) && new Date(r.CreatedDate) < staleThreshold);
49
73
  let hasPositiveFinding = false;
50
74
  // SBS-FILE-001: all public content links must have an expiry date
51
75
  if (noExpiry.length > 0) {
@@ -98,7 +122,7 @@ export class ContentLinksCheck {
98
122
  })),
99
123
  });
100
124
  }
101
- if (!hasPositiveFinding) {
125
+ if (!hasPositiveFinding && !truncated) {
102
126
  findings.push({
103
127
  id: 'content-links-ok',
104
128
  category: this.category,
@@ -8,7 +8,8 @@ export class CorsAllowlistCheck {
8
8
  const setupUrl = `${ctx.orgInfo.instanceUrl}/lightning/setup/CorsWhitelistEntries/home`;
9
9
  let rows;
10
10
  try {
11
- rows = await ctx.tooling.query('SELECT Id, UrlPattern FROM CorsWhitelistEntry');
11
+ // CorsWhitelistEntry is served by the standard API; the Tooling API does not support it.
12
+ rows = await ctx.soql.queryAll('SELECT Id, UrlPattern FROM CorsWhitelistEntry');
12
13
  }
13
14
  catch (err) {
14
15
  const msg = err instanceof Error ? err.message : String(err);
@@ -18,7 +19,7 @@ export class CorsAllowlistCheck {
18
19
  riskLevel: 'INFO',
19
20
  inconclusive: true,
20
21
  title: 'CORS allowlist could not be read',
21
- detail: `The CorsWhitelistEntry Tooling query was not accessible: ${msg}`,
22
+ detail: `The CorsWhitelistEntry query failed: ${msg}`,
22
23
  remediation: 'Grant the audit user "View Setup and Configuration", then re-run the audit.',
23
24
  });
24
25
  return { findings };
@@ -11,23 +11,25 @@ export class DataClassificationCheck {
11
11
  const findings = [];
12
12
  const baseUrl = ctx.orgInfo.instanceUrl;
13
13
  const objectList = CLASSIFICATION_OBJECTS.map((o) => `'${o}'`).join(', ');
14
- // Q1 (Tooling API): count fields with a ComplianceGroup set per key object.
14
+ // Q1 (Tooling API): fields with a ComplianceGroup set on each key object, counted here.
15
15
  // Salesforce Data Classification sets ComplianceGroup on FieldDefinition to mark fields
16
16
  // as PII, PCI, HIPAA, GDPR, etc. Objects with zero classified fields are uncovered.
17
- let classifiedMap = new Map();
18
- let classificationQueryFailed = false;
17
+ // FieldDefinition supports no aggregates (its Id is not aggregatable), so no COUNT/GROUP BY.
18
+ const classifiedMap = new Map();
19
+ let classificationError;
19
20
  try {
20
- const classResult = await ctx.tooling.query(`SELECT EntityDefinition.QualifiedApiName objectName, COUNT(Id) classifiedCount
21
+ const classResult = await ctx.tooling.query(`SELECT EntityDefinition.QualifiedApiName, QualifiedApiName
21
22
  FROM FieldDefinition
22
23
  WHERE EntityDefinition.QualifiedApiName IN (${objectList})
23
- AND ComplianceGroup != null
24
- GROUP BY EntityDefinition.QualifiedApiName`);
24
+ AND ComplianceGroup != null`);
25
25
  for (const r of classResult) {
26
- classifiedMap.set(r.objectName, r.classifiedCount ?? 0);
26
+ const obj = r.EntityDefinition?.QualifiedApiName;
27
+ if (obj)
28
+ classifiedMap.set(obj, (classifiedMap.get(obj) ?? 0) + 1);
27
29
  }
28
30
  }
29
- catch {
30
- classificationQueryFailed = true;
31
+ catch (err) {
32
+ classificationError = err instanceof Error ? err.message : String(err);
31
33
  }
32
34
  // Q2 (SOQL): check for Shield Platform Encryption keys.
33
35
  // EncryptionKey records indicate Shield is licensed and active.
@@ -45,15 +47,15 @@ export class DataClassificationCheck {
45
47
  encryptionQueryFailed = true;
46
48
  }
47
49
  // SBS-DATA-001/002: data classification coverage
48
- if (classificationQueryFailed) {
50
+ if (classificationError !== undefined) {
49
51
  findings.push({
50
52
  id: 'data-classification-inconclusive',
51
53
  category: this.category,
52
54
  riskLevel: 'INFO',
53
55
  inconclusive: true,
54
- title: 'Data classification status could not be determined: Tooling API access needed',
55
- detail: 'SBS-DATA-001 requires all data fields to be classified by sensitivity. SBS-DATA-002 requires PII fields to be explicitly identified. The Tooling API FieldDefinition query was not accessible with the current user permissions.',
56
- remediation: 'Enable Tooling API access for the audit user, or manually review data classification in Setup → Data Management → Data Classification for Account, Contact, Lead, Opportunity, Case, Contract, and User.',
56
+ title: 'Data classification status could not be determined',
57
+ detail: `SBS-DATA-001 requires all data fields to be classified by sensitivity. SBS-DATA-002 requires PII fields to be explicitly identified. The Tooling API FieldDefinition query failed, so classification is unassessed, not absent: ${classificationError}`,
58
+ remediation: 'Check the error above. If it is an access error, confirm the audit user has API Enabled and View Setup and Configuration; otherwise review data classification manually in Setup → Data Management → Data Classification for Account, Contact, Lead, Opportunity, Case, Contract, and User.',
57
59
  });
58
60
  }
59
61
  else {
@@ -10,22 +10,22 @@ export class DebugLogAccessCheck {
10
10
  const setupUrl = `${baseUrl}/lightning/setup/ApexDebugLog/home`;
11
11
  let traces = [];
12
12
  try {
13
- const result = await ctx.soql.query(`SELECT Id, TracedEntityId, LogType, ExpirationDate,
13
+ // TraceFlag is served by the Tooling API only.
14
+ traces = await ctx.tooling.query(`SELECT Id, TracedEntityId, LogType, ExpirationDate,
14
15
  DebugLevel.DeveloperName, DebugLevel.ApexCode
15
16
  FROM TraceFlag
16
17
  WHERE ExpirationDate >= TODAY
17
18
  ORDER BY ExpirationDate ASC
18
19
  LIMIT 200`);
19
- traces = result.records;
20
20
  }
21
- catch {
21
+ catch (err) {
22
22
  findings.push({
23
23
  id: 'debug-log-inaccessible',
24
24
  category: this.category,
25
25
  riskLevel: 'INFO',
26
26
  inconclusive: true,
27
27
  title: 'TraceFlag records could not be retrieved: active debug traces cannot be verified',
28
- detail: 'The TraceFlag object was not accessible. This may indicate the audit user lacks API access or the required permission to manage debug logs.',
28
+ detail: `The TraceFlag query failed: ${err instanceof Error ? err.message : String(err)}. If the org denied access, the audit user may lack "View Setup and Configuration".`,
29
29
  remediation: 'Grant "Manage Users" or "View All Data" permission to the audit user, or review active debug traces manually in Setup → Debug Logs.',
30
30
  affectedItems: [{ label: 'Debug Log Setup', url: setupUrl }],
31
31
  });
@@ -9,7 +9,8 @@ export class DelegatedAdministrationGroupsCheck {
9
9
  const setupUrl = `${baseUrl}/lightning/setup/DelegateGroups/home`;
10
10
  let groups = [];
11
11
  try {
12
- groups = await ctx.soql.queryAll('SELECT Id, DeveloperName FROM DelegateGroup');
12
+ // DelegateGroup and DelegateGroupMember are served by the Tooling API only.
13
+ groups = await ctx.tooling.query('SELECT Id, DeveloperName FROM DelegateGroup');
13
14
  }
14
15
  catch (err) {
15
16
  // This object exists in every org, so a failure is lack of access, never an absent feature.
@@ -38,7 +39,7 @@ export class DelegatedAdministrationGroupsCheck {
38
39
  }
39
40
  // Query members of delegated admin groups
40
41
  let members = [];
41
- members = await ctx.soql.queryAll('SELECT Id, DelegateGroupId, UserOrGroupId FROM DelegateGroupMember');
42
+ members = await ctx.tooling.query('SELECT Id, DelegateGroupId, UserOrGroupId FROM DelegateGroupMember');
42
43
  // Collect user names if members exist
43
44
  const userIds = members
44
45
  .map((m) => m.UserOrGroupId)
@@ -1,3 +1,8 @@
1
+ import { hasField } from '../support/schema.js';
2
+ // "Is Single Sign-On Enabled". Salesforce adds this permission field only to orgs where it has
3
+ // enabled delegated authentication; without the field no profile can route sign-in through a
4
+ // delegated gateway.
5
+ const SSO_PERMISSION = 'PermissionsIsSsoEnabled';
1
6
  export class DelegatedAuthenticationExposureCheck {
2
7
  id = 'delegated-authentication-exposure';
3
8
  name = 'Delegated Authentication Exposure';
@@ -25,7 +30,9 @@ export class DelegatedAuthenticationExposureCheck {
25
30
  }
26
31
  }
27
32
  const isDelegatedAuthEnabled = delegatedAuth === true;
28
- const profiles = await ctx.soql.queryAll('SELECT Id, Name, PermissionsIsSingleSignOnEnabled FROM Profile WHERE PermissionsIsSingleSignOnEnabled = true');
33
+ const profiles = (await hasField(ctx, 'Profile', SSO_PERMISSION))
34
+ ? await ctx.soql.queryAll(`SELECT Id, Name, ${SSO_PERMISSION} FROM Profile WHERE ${SSO_PERMISSION} = true`)
35
+ : [];
29
36
  const adminProfilesWithDelegatedAuth = profiles.filter((p) => p.Name.toLowerCase().includes('admin') || p.Name === 'System Administrator');
30
37
  if (isDelegatedAuthEnabled) {
31
38
  // Check 1: Insecure Gateway URL (non-https or cleartext)
@@ -6,6 +6,9 @@ const CI_CD_APP_PATTERNS = [
6
6
  /flosum/i, /ownbackup/i, /metazoa/i, /pipeline/i, /deploy/i,
7
7
  ];
8
8
  const ADMIN_PROFILE_RE = /admin|system administrator/i;
9
+ // SetupAuditTrail.Section cannot be filtered in SOQL; these are matched in code.
10
+ const DEPLOY_SECTIONS = new Set(['Change Sets', 'Developer Tools', 'Packages', 'Metadata']);
11
+ const MAX_TRAIL_ROWS = 10000;
9
12
  export class DeploymentIdentityCheck {
10
13
  id = 'deployment-identity';
11
14
  name = 'Deployment Identity';
@@ -40,29 +43,50 @@ export class DeploymentIdentityCheck {
40
43
  // Signal 2 (1 query): SetupAuditTrail entries in deploy-related sections over 90 days.
41
44
  // This reveals how many distinct users are performing deployment operations and whether
42
45
  // those users are individual admins rather than a designated deployment identity.
46
+ // SetupAuditTrail.Section cannot be filtered in SOQL: the trail is read (bounded) and the
47
+ // deploy sections are matched here. Up to 300 matches are analysed, as before.
43
48
  let deployRecords;
49
+ // True when the trail or the deploy matches were cut off, so deployers may be missing.
50
+ let truncated = false;
44
51
  try {
45
- deployRecords = await ctx.soql.queryAll(`SELECT CreatedDate, CreatedBy.Id, CreatedBy.Username, CreatedBy.Profile.Name,
52
+ const trail = await ctx.soql.queryAll(`SELECT CreatedDate, CreatedBy.Id, CreatedBy.Username, CreatedBy.Profile.Name,
46
53
  Section, Action, Display
47
54
  FROM SetupAuditTrail
48
55
  WHERE CreatedDate > LAST_N_DAYS:90
49
- AND Section IN ('Change Sets', 'Developer Tools', 'Packages', 'Metadata')
50
56
  ORDER BY CreatedDate DESC
51
- LIMIT 300`);
57
+ LIMIT ${MAX_TRAIL_ROWS}`);
58
+ const matches = trail.filter((r) => DEPLOY_SECTIONS.has(r.Section));
59
+ truncated = trail.length >= MAX_TRAIL_ROWS || matches.length > 300;
60
+ deployRecords = matches.slice(0, 300);
52
61
  }
53
- catch {
62
+ catch (err) {
54
63
  findings.push({
55
64
  id: 'deployment-audit-trail-inaccessible',
56
65
  category: this.category,
57
66
  riskLevel: 'MEDIUM',
58
67
  inconclusive: true,
59
68
  title: 'Deployment audit trail could not be read: SBS-DEP-003 unverified',
60
- detail: 'SetupAuditTrail was not accessible. Deployment activity from the past 90 days cannot be analyzed for unauthorized modifications. Without this data it is impossible to determine whether deployments are performed by a single designated identity.',
69
+ detail: `The SetupAuditTrail query failed (${err instanceof Error ? err.message : String(err)}). Deployment activity from the past 90 days cannot be analyzed for unauthorized modifications. Without this data it is impossible to determine whether deployments are performed by a single designated identity.`,
61
70
  remediation: 'Grant "View Setup and Configuration" permission to the audit user to enable audit trail analysis.',
62
71
  });
63
72
  return { findings };
64
73
  }
74
+ // MN-051: with the trail cut off, "nobody deployed" and "one identity deployed" are unproven.
75
+ const partialFinding = () => ({
76
+ id: 'deployment-identity-partial',
77
+ category: this.category,
78
+ riskLevel: 'INFO',
79
+ inconclusive: true,
80
+ title: `Deployment identity only partly assessed: the 90-day audit trail exceeds what was read`,
81
+ detail: `The 90-day Setup Audit Trail holds more than ${MAX_TRAIL_ROWS} entries (or more than 300 deployment entries), so only the most recent were analysed. Older deployers in the window may be missing, so a single-identity or no-activity result is not established.`,
82
+ remediation: 'Review deployment activity in Setup → View Setup Audit Trail, or export the full trail for review.',
83
+ affectedItems: [{ label: 'Setup Audit Trail', url: auditUrl }],
84
+ });
65
85
  if (deployRecords.length === 0 && ciCdApps.length === 0) {
86
+ if (truncated) {
87
+ findings.push(partialFinding());
88
+ return { findings };
89
+ }
66
90
  findings.push({
67
91
  id: 'deployment-no-activity',
68
92
  category: this.category,
@@ -109,6 +133,9 @@ export class DeploymentIdentityCheck {
109
133
  })),
110
134
  });
111
135
  }
136
+ else if (uniqueDeployers.length === 1 && truncated) {
137
+ findings.push(partialFinding());
138
+ }
112
139
  else if (uniqueDeployers.length === 1) {
113
140
  const d = uniqueDeployers[0];
114
141
  findings.push({
@@ -4,7 +4,7 @@ export declare class EmailSecurityCheck implements SecurityCheck {
4
4
  readonly id = "email-security";
5
5
  readonly name = "Email Security & Spoofing";
6
6
  readonly category = "External Connectivity";
7
- readonly description = "Flags inbound email services that accept mail from any sender or run Apex without authentication, and org-wide send-as addresses available to every profile";
7
+ readonly description = "Flags inbound email services that accept mail from any sender or run Apex without authentication";
8
8
  run(ctx: AuditContext): Promise<CheckResult>;
9
9
  }
10
10
  //# sourceMappingURL=EmailSecurityCheck.d.ts.map
@@ -22,45 +22,25 @@ export class EmailSecurityCheck {
22
22
  id = 'email-security';
23
23
  name = 'Email Security & Spoofing';
24
24
  category = 'External Connectivity';
25
- description = 'Flags inbound email services that accept mail from any sender or run Apex without authentication, and org-wide send-as addresses available to every profile';
25
+ description = 'Flags inbound email services that accept mail from any sender or run Apex without authentication';
26
26
  async run(ctx) {
27
27
  const findings = [];
28
28
  const baseUrl = ctx.orgInfo.instanceUrl;
29
- const owaUrl = `${baseUrl}/lightning/setup/OrgWideEmailAddresses/home`;
30
29
  const svcUrl = `${baseUrl}/lightning/setup/EmailToApex/home`;
31
- // 1. Org-wide email addresses available to all profiles — any user can send "as" them.
32
- const owa = await tryQuery(() => ctx.soql.queryAll('SELECT Id, Address, DisplayName, IsAllowAllProfiles FROM OrgWideEmailAddress'), findings, this.category, 'email-security-owa-inaccessible', 'Org-wide email addresses');
33
- if (owa) {
34
- const allProfiles = owa.filter((r) => r.IsAllowAllProfiles);
35
- if (allProfiles.length > 0) {
36
- findings.push({
37
- id: 'email-security-owa-all-profiles',
38
- category: this.category,
39
- riskLevel: 'MEDIUM',
40
- title: `${allProfiles.length} org-wide email address(es) are available to all profiles`,
41
- detail: 'An org-wide email address available to all profiles lets any user send email that appears to come from that address. This enables internal impersonation (e.g. spoofing a finance or executive sender) in phishing campaigns originating from inside the org.',
42
- remediation: 'Restrict each org-wide email address to the specific profiles that legitimately need to send as it, rather than allowing all profiles.',
43
- affectedItems: allProfiles.map((r) => ({
44
- label: r.Address,
45
- url: owaUrl,
46
- note: `${r.DisplayName || 'no display name'}: restrict to specific profiles`,
47
- })),
48
- });
49
- }
50
- else if (owa.length > 0) {
51
- findings.push({
52
- id: 'email-security-owa-ok',
53
- category: this.category,
54
- riskLevel: 'LOW',
55
- passed: true,
56
- title: `${owa.length} org-wide email address(es) are scoped to specific profiles`,
57
- detail: 'No org-wide email address is exposed to all profiles, limiting send-as impersonation.',
58
- remediation: 'Continue to scope org-wide addresses to the profiles that need them.',
59
- });
60
- }
61
- }
62
- // 2. Inbound email services (Email-to-Apex) — internet-reachable Apex triggers.
30
+ // Org-wide send-as addresses are reported once, by org-wide-email-spoofing.
31
+ // Inbound email services (Email-to-Apex) — internet-reachable Apex triggers.
63
32
  const services = await tryQuery(() => ctx.soql.queryAll('SELECT Id, FunctionName, IsActive, IsAuthenticationRequired FROM EmailServicesFunction WHERE IsActive = true'), findings, this.category, 'email-security-services-inaccessible', 'Inbound email services');
33
+ if (services && services.length === 0) {
34
+ findings.push({
35
+ id: 'email-security-services-none',
36
+ category: this.category,
37
+ riskLevel: 'LOW',
38
+ passed: true,
39
+ title: 'No active inbound email services',
40
+ detail: 'No inbound email service is active, so no Apex runs on receipt of email.',
41
+ remediation: 'If one is added, require authentication and restrict accepted senders.',
42
+ });
43
+ }
64
44
  if (services && services.length > 0) {
65
45
  const unauthenticated = services.filter((s) => !s.IsAuthenticationRequired);
66
46
  if (unauthenticated.length > 0) {