@cclabsnz/sf-audit 1.8.2 → 1.10.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 (53) hide show
  1. package/CHANGELOG.md +221 -0
  2. package/README.md +144 -756
  3. package/lib/chains/CapabilityRegistry.d.ts +6 -2
  4. package/lib/chains/CapabilityRegistry.js +48 -2
  5. package/lib/chains/namedChains.js +140 -7
  6. package/lib/checks/impl/AgentChannelExposureCheck.js +52 -10
  7. package/lib/checks/impl/ApexCrudFLSCheck.js +3 -3
  8. package/lib/checks/impl/ApexRestEndpointCheck.js +0 -3
  9. package/lib/checks/impl/CustomLabelsCredentialCheck.js +1 -1
  10. package/lib/checks/impl/DataClassificationCheck.js +15 -1
  11. package/lib/checks/impl/FailedLoginCheck.js +16 -1
  12. package/lib/checks/impl/FieldLevelSecurityCheck.js +29 -16
  13. package/lib/checks/impl/GuestUserVisibilityCheck.d.ts +35 -0
  14. package/lib/checks/impl/GuestUserVisibilityCheck.js +168 -0
  15. package/lib/checks/impl/HardcodedCredentialsCheck.js +0 -1
  16. package/lib/checks/impl/HealthCheckCheck.js +1 -3
  17. package/lib/checks/impl/IntegrationLeastPrivilegeCheck.d.ts +42 -0
  18. package/lib/checks/impl/IntegrationLeastPrivilegeCheck.js +467 -0
  19. package/lib/checks/impl/IntegrationUsersCheck.js +48 -52
  20. package/lib/checks/impl/InternalUserMfaCheck.js +0 -1
  21. package/lib/checks/impl/IpRestrictionsCheck.js +39 -5
  22. package/lib/checks/impl/PublicGroupSharingCheck.js +21 -2
  23. package/lib/checks/impl/ScheduledApexCheck.js +0 -1
  24. package/lib/checks/impl/SoapLoginApiAuthCheck.d.ts +10 -0
  25. package/lib/checks/impl/SoapLoginApiAuthCheck.js +151 -0
  26. package/lib/checks/impl/SsoEnforcementCheck.js +0 -1
  27. package/lib/checks/impl/TrustedUrlHygieneCheck.js +3 -1
  28. package/lib/checks/registry.js +4 -0
  29. package/lib/checks/support/integrationAccounts.d.ts +35 -0
  30. package/lib/checks/support/integrationAccounts.js +209 -0
  31. package/lib/commands/audit/preflight.d.ts +13 -0
  32. package/lib/commands/audit/preflight.js +56 -0
  33. package/lib/commands/audit/security.d.ts +16 -3
  34. package/lib/commands/audit/security.js +40 -10
  35. package/lib/compliance/catalogs/gdpr.d.ts +3 -0
  36. package/lib/compliance/catalogs/gdpr.js +54 -0
  37. package/lib/compliance/catalogs/hipaa.d.ts +3 -0
  38. package/lib/compliance/catalogs/hipaa.js +97 -0
  39. package/lib/compliance/catalogs/index.js +4 -0
  40. package/lib/compliance/mapping.js +111 -36
  41. package/lib/findings/CheckMeta.js +2 -0
  42. package/lib/findings/digest.d.ts +50 -0
  43. package/lib/findings/digest.js +56 -0
  44. package/lib/findings/exitCode.d.ts +28 -0
  45. package/lib/findings/exitCode.js +46 -0
  46. package/lib/findings/loadScoringConfig.js +5 -5
  47. package/lib/preflight/permissionMap.d.ts +47 -0
  48. package/lib/preflight/permissionMap.js +84 -0
  49. package/lib/preflight/readPermissions.d.ts +11 -0
  50. package/lib/preflight/readPermissions.js +20 -0
  51. package/lib/renderers/HtmlRenderer.js +1 -1
  52. package/messages/audit.security.md +6 -0
  53. package/package.json +5 -3
@@ -23,7 +23,11 @@ export class IpRestrictionsCheck {
23
23
  const adminUsers = await ctx.soql.queryAll(`SELECT Id, ProfileId, Profile.Name, Username FROM User
24
24
  WHERE IsActive = true AND Profile.PermissionsModifyAllData = true`);
25
25
  // 2. Profile IP ranges — try SOQL first, fallback to Tooling
26
+ // "Unreadable" and "none configured" are different facts and must not be conflated: an
27
+ // empty result would make every admin look unrestricted, asserting a finding the data
28
+ // cannot support.
26
29
  let ipRanges = [];
30
+ let rangesUnavailable = false;
27
31
  try {
28
32
  ipRanges = await ctx.soql.queryAll('SELECT ProfileId, StartAddress, EndAddress FROM ProfileLoginIpRange');
29
33
  }
@@ -32,8 +36,7 @@ export class IpRestrictionsCheck {
32
36
  ipRanges = await ctx.tooling.query('SELECT ProfileId, StartAddress, EndAddress FROM ProfileLoginIpRange');
33
37
  }
34
38
  catch {
35
- // No IP ranges configured or not accessible — treat as empty
36
- ipRanges = [];
39
+ rangesUnavailable = true;
37
40
  }
38
41
  }
39
42
  // 3. Connected apps — single Tooling SOQL with Metadata field (same pattern as
@@ -44,6 +47,7 @@ export class IpRestrictionsCheck {
44
47
  // 'WhiteList'→ enforce the org-level IP whitelist (secure)
45
48
  const ipBypassingApps = [];
46
49
  const ipRelaxingApps = [];
50
+ let appsUnavailable = false;
47
51
  try {
48
52
  const connectedApps = await ctx.tooling.query('SELECT Id, Name, Metadata FROM ConnectedApplication');
49
53
  for (const app of connectedApps) {
@@ -57,13 +61,30 @@ export class IpRestrictionsCheck {
57
61
  }
58
62
  }
59
63
  catch {
60
- // Metadata field not accessible — skip connected app IP check
64
+ // Recorded so the result cannot be read as "no relaxed apps".
65
+ appsUnavailable = true;
61
66
  }
62
67
  // Determine which profile IDs have at least one IP range
63
68
  const profilesWithRanges = new Set(ipRanges.map((r) => r.ProfileId));
64
69
  // Admin users whose profile has no IP ranges
65
70
  const unrestrictedAdmins = adminUsers.filter((u) => !profilesWithRanges.has(u.ProfileId));
66
- if (unrestrictedAdmins.length > 0) {
71
+ if (rangesUnavailable && adminUsers.length > 0) {
72
+ findings.push({
73
+ id: 'ip-restrictions-ranges-unavailable',
74
+ category: this.category,
75
+ riskLevel: 'INFO',
76
+ inconclusive: true,
77
+ 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.',
80
+ affectedItems: adminUsers.map((u) => ({
81
+ label: u.Username,
82
+ url: `${baseUrl}/${u.Id}`,
83
+ note: `Profile: ${u.Profile.Name}: IP range configuration unknown`,
84
+ })),
85
+ });
86
+ }
87
+ if (!rangesUnavailable && unrestrictedAdmins.length > 0) {
67
88
  findings.push({
68
89
  id: 'admin-no-ip-restrictions',
69
90
  category: this.category,
@@ -78,6 +99,17 @@ export class IpRestrictionsCheck {
78
99
  remediation: 'Add IP login ranges to all admin profiles in Setup → Profiles → Login IP Ranges, or enable MFA as a compensating control.',
79
100
  });
80
101
  }
102
+ if (appsUnavailable) {
103
+ findings.push({
104
+ id: 'ip-restrictions-apps-unavailable',
105
+ category: this.category,
106
+ riskLevel: 'INFO',
107
+ inconclusive: true,
108
+ 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.',
111
+ });
112
+ }
81
113
  if (ipBypassingApps.length > 0) {
82
114
  findings.push({
83
115
  id: 'connected-apps-bypass-ip',
@@ -138,7 +170,9 @@ export class IpRestrictionsCheck {
138
170
  })),
139
171
  });
140
172
  }
141
- if (unrestrictedAdmins.length === 0 &&
173
+ if (!rangesUnavailable &&
174
+ !appsUnavailable &&
175
+ unrestrictedAdmins.length === 0 &&
142
176
  ipBypassingApps.length === 0 &&
143
177
  ipRelaxingApps.length === 0 &&
144
178
  broadRanges.length === 0) {
@@ -26,6 +26,10 @@ export class PublicGroupSharingCheck {
26
26
  const groupIdList = groups.map((g) => `'${g.Id}'`).join(', ');
27
27
  const groupNameMap = new Map(groups.map((g) => [g.Id, g.Name]));
28
28
  const exposures = [];
29
+ // Which share tables could not be read. An object may be absent from the org edition or
30
+ // simply not permitted; either way the check did not see it, and the conclusion has to say
31
+ // so rather than count silence as evidence of no sharing.
32
+ const unreadable = [];
29
33
  for (const shareTable of SHARE_TABLES) {
30
34
  try {
31
35
  const result = await ctx.soql.query(`SELECT UserOrGroupId, COUNT(Id) cnt
@@ -44,7 +48,7 @@ export class PublicGroupSharingCheck {
44
48
  }
45
49
  }
46
50
  catch {
47
- // Object may not exist or not be accessible — skip silently
51
+ unreadable.push(shareTable);
48
52
  }
49
53
  }
50
54
  if (exposures.length > 0) {
@@ -64,14 +68,29 @@ export class PublicGroupSharingCheck {
64
68
  remediation: 'Replace "All Internal Users" sharing rules with more targeted public groups or role-based sharing.',
65
69
  });
66
70
  }
71
+ else if (unreadable.length === SHARE_TABLES.length) {
72
+ // Nothing was readable, so "no exposure found" would be an assertion about data never seen.
73
+ findings.push({
74
+ id: 'public-group-sharing-inconclusive',
75
+ category: this.category,
76
+ riskLevel: 'INFO',
77
+ inconclusive: true,
78
+ title: 'Sharing to All Internal Users could not be evaluated',
79
+ detail: `None of the share tables (${SHARE_TABLES.join(', ')}) could be queried, so whether sharing rules target the "All Internal Users" group is unknown. ${groups.length} such group(s) exist in this org.`,
80
+ remediation: 'Grant the audit user read access to the share tables and re-run, or review sharing rules manually in Setup → Sharing Settings.',
81
+ });
82
+ }
67
83
  else {
84
+ const checked = SHARE_TABLES.filter((s) => !unreadable.includes(s));
68
85
  findings.push({
69
86
  id: 'public-group-sharing-none',
70
87
  category: this.category,
71
88
  riskLevel: 'LOW',
72
89
  passed: true,
73
90
  title: 'No records shared to All Internal Users groups via sharing rules',
74
- detail: 'No sharing rules were found targeting the "All Internal Users" group on key objects.',
91
+ detail: unreadable.length > 0
92
+ ? `No sharing rules targeting the "All Internal Users" group were found on ${checked.join(', ')}. ${unreadable.join(', ')} could not be queried and were not checked.`
93
+ : 'No sharing rules were found targeting the "All Internal Users" group on key objects.',
75
94
  remediation: 'Continue to avoid broad sharing rules. Periodically review sharing configuration as the org grows.',
76
95
  });
77
96
  }
@@ -8,7 +8,6 @@ export class ScheduledApexCheck {
8
8
  const findings = [];
9
9
  const baseUrl = ctx.orgInfo.instanceUrl;
10
10
  const apexJobsUrl = `${baseUrl}/lightning/setup/ScheduledJobs/home`;
11
- const apexClassesUrl = `${baseUrl}/lightning/setup/ApexClasses/home`;
12
11
  // Query all active scheduled/batch Apex jobs
13
12
  const jobs = await ctx.soql.queryAll(`
14
13
  SELECT Id, ApexClass.Name, JobType, Status, CreatedById
@@ -0,0 +1,10 @@
1
+ import type { AuditContext } from '@cclabsnz/sf-core';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class SoapLoginApiAuthCheck implements SecurityCheck {
4
+ readonly id = "soap-login-api-auth";
5
+ readonly name = "SOAP login() Use Any API Auth Readiness";
6
+ readonly category = "Permissions";
7
+ readonly description = "Flags accounts that authenticate via SOAP API login() but lack the \"Use Any API Auth\" permission that Winter '27 requires, and holders that no longer need it";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=SoapLoginApiAuthCheck.d.ts.map
@@ -0,0 +1,151 @@
1
+ /**
2
+ * Ninety days rather than thirty. SOAP callers are disproportionately the least routine
3
+ * things in an org: a quarterly reconciliation job, a backup tool, a device switched on
4
+ * for stocktake. A short window is exactly how those get missed.
5
+ */
6
+ const LOOKBACK_DAYS = 90;
7
+ /**
8
+ * Matched against ApiType first, which carries values such as "SOAP Partner" and
9
+ * "SOAP Enterprise", then Application as a fallback. The match is deliberately broad:
10
+ * the exact strings are not contractual and vary by how the client identifies itself.
11
+ */
12
+ function isSoapLogin(row) {
13
+ return /soap/i.test(row.ApiType ?? '') || /soap/i.test(row.Application ?? '');
14
+ }
15
+ export class SoapLoginApiAuthCheck {
16
+ id = 'soap-login-api-auth';
17
+ name = 'SOAP login() Use Any API Auth Readiness';
18
+ category = 'Permissions';
19
+ description = 'Flags accounts that authenticate via SOAP API login() but lack the "Use Any API Auth" permission that Winter \'27 requires, and holders that no longer need it';
20
+ async run(ctx) {
21
+ const findings = [];
22
+ const baseUrl = ctx.orgInfo.instanceUrl;
23
+ const permSetUrl = `${baseUrl}/lightning/setup/PermSets/home`;
24
+ // Q1: who is authenticating over SOAP.
25
+ // Application, Status and ApiType are groupable but NOT filterable on LoginHistory,
26
+ // so a WHERE clause naming them returns a parse error. Group, then filter in memory.
27
+ let soapRows = [];
28
+ try {
29
+ const result = await ctx.soql.query(`SELECT UserId, Application, ApiType, COUNT(Id) logins
30
+ FROM LoginHistory
31
+ WHERE LoginTime = LAST_N_DAYS:${LOOKBACK_DAYS}
32
+ GROUP BY UserId, Application, ApiType`);
33
+ soapRows = result.records.filter(isSoapLogin).filter((r) => r.UserId);
34
+ }
35
+ catch {
36
+ findings.push({
37
+ id: 'soap-login-api-auth-inconclusive-history',
38
+ category: this.category,
39
+ riskLevel: 'INFO',
40
+ inconclusive: true,
41
+ title: 'SOAP login() readiness could not be determined: LoginHistory was not readable',
42
+ detail: 'Winter \'27 requires the "Use Any API Auth" permission to authenticate with SOAP API login(). Determining exposure needs LoginHistory, which this audit user could not query. LoginHistory also retains only six months, so an integration that runs less often than that may not appear even when readable.',
43
+ remediation: 'Re-run with a user that can read LoginHistory, or review Setup → Identity → Login History manually, filtering for SOAP API types.',
44
+ });
45
+ return { findings };
46
+ }
47
+ // Q2: who already holds the permission. Querying PermissionSetAssignment covers both
48
+ // grant paths, because a profile's own permissions live on a PermissionSet with
49
+ // IsOwnedByProfile = true. Orgs on a release without the field will throw here.
50
+ let holders = [];
51
+ try {
52
+ const result = await ctx.soql.query(`SELECT Assignee.Id, Assignee.Username, Assignee.Profile.Name,
53
+ PermissionSet.Name, PermissionSet.IsOwnedByProfile
54
+ FROM PermissionSetAssignment
55
+ WHERE PermissionSet.PermissionsUseAnyApiAuth = true
56
+ AND Assignee.IsActive = true`);
57
+ holders = result.records;
58
+ }
59
+ catch {
60
+ findings.push({
61
+ id: 'soap-login-api-auth-inconclusive-field',
62
+ category: this.category,
63
+ riskLevel: 'INFO',
64
+ inconclusive: true,
65
+ title: '"Use Any API Auth" permission is not queryable in this org yet',
66
+ detail: 'The PermissionsUseAnyApiAuth field was not available. That is expected on orgs not yet upgraded to a release that carries it, and it means readiness for the Winter \'27 SOAP login() change cannot be assessed here. Note this permission is not the same as "Use Any API Client", which is covered separately by the api-client-permission check.',
67
+ remediation: `Re-run this audit after the org takes Winter '27, or check Setup → Permission Sets for "Use Any API Auth" directly: ${permSetUrl}`,
68
+ });
69
+ return { findings };
70
+ }
71
+ const holderIds = new Set(holders.map((h) => h.Assignee.Id));
72
+ if (soapRows.length === 0) {
73
+ findings.push({
74
+ id: 'soap-login-api-auth-ok-no-soap',
75
+ category: this.category,
76
+ riskLevel: 'LOW',
77
+ passed: true,
78
+ title: `No SOAP API login() authentication in the last ${LOOKBACK_DAYS} days`,
79
+ detail: `Winter '27 requires the "Use Any API Auth" permission to authenticate with SOAP API login(). No login in the last ${LOOKBACK_DAYS} days used a SOAP API type, so no account is exposed to that change on the evidence available. LoginHistory retains six months, so an integration that runs less frequently than this window would not appear.`,
80
+ remediation: 'No action needed. If you operate an integration that runs less often than quarterly, confirm its authentication method directly rather than relying on this window.',
81
+ });
82
+ return { findings };
83
+ }
84
+ // Resolve usernames for the SOAP callers. LoginHistory gives UserId only, and an
85
+ // aggregate query cannot traverse to User reliably.
86
+ const soapUserIds = [...new Set(soapRows.map((r) => r.UserId))];
87
+ const idList = soapUserIds.map((id) => `'${id}'`).join(',');
88
+ const userResult = await ctx.soql.query(`SELECT Id, Username, Profile.Name FROM User WHERE Id IN (${idList}) AND IsActive = true`);
89
+ const users = new Map(userResult.records.map((u) => [u.Id, u]));
90
+ // Login counts per user, summed across the Application/ApiType rows they appear in.
91
+ const loginCounts = new Map();
92
+ for (const row of soapRows) {
93
+ const id = row.UserId;
94
+ loginCounts.set(id, (loginCounts.get(id) ?? 0) + (row.logins ?? 0));
95
+ }
96
+ const atRisk = soapUserIds.filter((id) => users.has(id) && !holderIds.has(id));
97
+ if (atRisk.length === 0) {
98
+ findings.push({
99
+ id: 'soap-login-api-auth-ok-covered',
100
+ category: this.category,
101
+ riskLevel: 'LOW',
102
+ passed: true,
103
+ title: `All ${soapUserIds.length} SOAP login() account(s) already hold "Use Any API Auth"`,
104
+ detail: `Every active account that authenticated over SOAP in the last ${LOOKBACK_DAYS} days holds the permission Winter '27 requires, so the enforcement should not break these integrations.`,
105
+ remediation: 'Keep the grant scoped to these accounts. If a new integration is onboarded, assign the same permission set rather than widening a profile.',
106
+ });
107
+ }
108
+ else {
109
+ findings.push({
110
+ id: 'soap-login-api-auth-missing',
111
+ category: this.category,
112
+ riskLevel: 'HIGH',
113
+ title: `${atRisk.length} account(s) authenticate via SOAP login() without "Use Any API Auth": these break in Winter '27`,
114
+ detail: `Winter '27 enforces the "Assign Use Any API Auth Permission for SOAP login()" release update. Salesforce states that users without the permission "can no longer authenticate with SOAP API login() and will encounter an error". These accounts authenticated over SOAP in the last ${LOOKBACK_DAYS} days and do not hold the permission through any profile or permission set. The failure occurs at authentication, server to server, so there is no error in the Salesforce UI and no partial transaction to unpick. Whoever monitors the downstream system finds out first. Note this is a different permission from "Use Any API Client"; granting that one does not satisfy this requirement.`,
115
+ remediation: `Create a permission set enabling "Use Any API Auth" and assign it to exactly these accounts, rather than editing a profile, so the grant stays visible in one query and revocable without collateral. Name it for the reason it exists. Before granting, confirm each account still needs SOAP: an integration that can move to the REST API or to a modern OAuth flow is better migrated than permitted. ${permSetUrl}`,
116
+ affectedItems: atRisk.map((id) => {
117
+ const u = users.get(id);
118
+ return {
119
+ label: u.Username,
120
+ url: `${baseUrl}/${id}`,
121
+ note: `${loginCounts.get(id) ?? 0} SOAP login(s) in ${LOOKBACK_DAYS}d, profile: ${u.Profile?.Name ?? 'unknown'}`,
122
+ };
123
+ }),
124
+ });
125
+ }
126
+ // The security half. A permission granted to accounts that do not use SOAP is standing
127
+ // privilege with no purpose, and orgs remediating the breakage in a hurry tend to create
128
+ // exactly that by granting at profile level.
129
+ const unnecessary = holders.filter((h) => !soapUserIds.includes(h.Assignee.Id));
130
+ if (unnecessary.length > 0) {
131
+ const viaProfile = unnecessary.filter((h) => h.PermissionSet.IsOwnedByProfile);
132
+ findings.push({
133
+ id: 'soap-login-api-auth-unnecessary',
134
+ category: this.category,
135
+ riskLevel: viaProfile.length > 0 ? 'MEDIUM' : 'LOW',
136
+ title: `${unnecessary.length} account(s) hold "Use Any API Auth" without using SOAP login()`,
137
+ detail: `These active accounts hold the permission but did not authenticate over SOAP in the last ${LOOKBACK_DAYS} days, so the grant is not currently doing anything for them. ${viaProfile.length > 0
138
+ ? `${viaProfile.length} of them receive it through a profile, which means it applies to everyone sharing that profile now and in future rather than to a named account.`
139
+ : 'All of them receive it through an assigned permission set, which is the right mechanism even where the grant turns out to be unnecessary.'} Granting broadly is a common response to the Winter '27 change and it converts a breakage problem into a standing-privilege one.`,
140
+ remediation: 'Remove the permission from accounts that do not authenticate over SOAP. Where it is granted by a profile, move it to a permission set assigned to the specific integration accounts that need it. Check against a longer window than this audit uses before removing, since a quarterly job may sit outside it.',
141
+ affectedItems: unnecessary.map((h) => ({
142
+ label: h.Assignee.Username,
143
+ url: `${baseUrl}/${h.Assignee.Id}`,
144
+ note: `via: ${h.PermissionSet.IsOwnedByProfile ? `Profile (${h.Assignee.Profile?.Name ?? 'unknown'})` : h.PermissionSet.Name}`,
145
+ })),
146
+ });
147
+ }
148
+ return { findings };
149
+ }
150
+ }
151
+ //# sourceMappingURL=SoapLoginApiAuthCheck.js.map
@@ -6,7 +6,6 @@ export class SsoEnforcementCheck {
6
6
  async run(ctx) {
7
7
  const findings = [];
8
8
  const baseUrl = ctx.orgInfo.instanceUrl;
9
- const setupUrl = `${baseUrl}/lightning/setup/SingleSignOn/home`;
10
9
  try {
11
10
  // Single query: recent credential logins over the past 30 days.
12
11
  // Presence of 'Username-Password' logins is direct evidence that SBS-AUTH-001
@@ -178,7 +178,9 @@ async function resolveDomain(domain) {
178
178
  function withTimeout(p, ms) {
179
179
  return Promise.race([
180
180
  p,
181
- new Promise((_, reject) => setTimeout(() => reject(Object.assign(new Error('DNS timeout'), { code: 'ETIMEDOUT' })), ms).unref?.()),
181
+ new Promise((_, reject) => {
182
+ setTimeout(() => reject(Object.assign(new Error('DNS timeout'), { code: 'ETIMEDOUT' })), ms).unref?.();
183
+ }),
182
184
  ]);
183
185
  }
184
186
  // Map over items with a fixed worker pool, preserving input order in the result.
@@ -27,6 +27,7 @@ import { SsoEnforcementCheck } from './impl/SsoEnforcementCheck.js';
27
27
  import { MfaEnforcementCheck } from './impl/MfaEnforcementCheck.js';
28
28
  import { ApiClientPermissionCheck } from './impl/ApiClientPermissionCheck.js';
29
29
  import { IntegrationUsersCheck } from './impl/IntegrationUsersCheck.js';
30
+ import { IntegrationLeastPrivilegeCheck } from './impl/IntegrationLeastPrivilegeCheck.js';
30
31
  import { ContentLinksCheck } from './impl/ContentLinksCheck.js';
31
32
  import { FieldHistoryTrackingCheck } from './impl/FieldHistoryTrackingCheck.js';
32
33
  import { DataClassificationCheck } from './impl/DataClassificationCheck.js';
@@ -77,6 +78,7 @@ import { DataExportAccessCheck } from './impl/DataExportAccessCheck.js';
77
78
  import { ClassicSitesCheck } from './impl/ClassicSitesCheck.js';
78
79
  import { AuthProvidersCheck } from './impl/AuthProvidersCheck.js';
79
80
  import { GuestApiAccessCheck } from './impl/GuestApiAccessCheck.js';
81
+ import { GuestUserVisibilityCheck } from './impl/GuestUserVisibilityCheck.js';
80
82
  import { ExternalCredentialsCheck } from './impl/ExternalCredentialsCheck.js';
81
83
  import { LoginAnomalyCheck } from './impl/LoginAnomalyCheck.js';
82
84
  import { SessionHardeningCheck } from './impl/SessionHardeningCheck.js';
@@ -126,6 +128,7 @@ export const CHECKS = [
126
128
  new MfaEnforcementCheck(), // SBS-AUTH-004 (portal users)
127
129
  new ApiClientPermissionCheck(), // SBS-ACS-006
128
130
  new IntegrationUsersCheck(), // SBS-ACS-007/008/009
131
+ new IntegrationLeastPrivilegeCheck(), // permissions integration accounts hold and do not use
129
132
  new ContentLinksCheck(), // SBS-FILE-001/002/003
130
133
  new FieldHistoryTrackingCheck(), // SBS-DATA-004
131
134
  new DataClassificationCheck(), // SBS-DATA-001/002/003
@@ -161,6 +164,7 @@ export const CHECKS = [
161
164
  new ClassicSitesCheck(), // classic Visualforce Force.com Sites (unauth surface)
162
165
  new AuthProvidersCheck(), // external Auth Providers / SAML IdP federation review
163
166
  new GuestApiAccessCheck(), // guest users with API Enabled / Bulk API Hard Delete
167
+ new GuestUserVisibilityCheck(), // guests seeing other User records — View All Users / User external OWD / Read on User
164
168
  new ExternalCredentialsCheck(), // External Credential weak/no authentication
165
169
  new LoginAnomalyCheck(), // successful logins from many distinct IPs
166
170
  new SessionHardeningCheck(), // reads healthCheckRisks — clickjack/CSRF/session-lock/XSS
@@ -0,0 +1,35 @@
1
+ import type { AuditContext } from '@cclabsnz/sf-core';
2
+ export type IntegrationSignal = 'integration-license' | 'connected-app-run-as' | 'scheduled-job-owner' | 'never-logged-in' | 'api-only-login' | 'username-pattern';
3
+ export interface IntegrationAccount {
4
+ id: string;
5
+ username: string;
6
+ profileName: string;
7
+ lastLoginDate: string | null;
8
+ signals: IntegrationSignal[];
9
+ }
10
+ export interface ResolveResult {
11
+ accounts: IntegrationAccount[];
12
+ /** Signals that could not be gathered. Findings must disclose these. */
13
+ degraded: IntegrationSignal[];
14
+ /** True when the candidate query itself failed: callers go inconclusive. */
15
+ unavailable: boolean;
16
+ /**
17
+ * True when the candidate query returned exactly its row limit, so the org may hold further
18
+ * integration accounts this run never saw. Any finding that counts or lists accounts must
19
+ * disclose it: SBS-ACS-007 asks for *all* non-human identities, and a truncated list that
20
+ * reads as complete is the wrong answer to that control.
21
+ */
22
+ truncated: boolean;
23
+ }
24
+ /**
25
+ * Username segments that strongly indicate a service/integration account. Moved here from
26
+ * IntegrationUsersCheck so there is one definition rather than two that drift.
27
+ */
28
+ export declare const SERVICE_LIKE_CLAUSES: string[];
29
+ /**
30
+ * The sentence findings use to disclose a truncated account set. Defined here, next to the limit
31
+ * it describes, so the two checks cannot state different numbers.
32
+ */
33
+ export declare function truncationDisclosure(truncated: boolean): string;
34
+ export declare function resolveIntegrationAccounts(ctx: AuditContext): Promise<ResolveResult>;
35
+ //# sourceMappingURL=integrationAccounts.d.ts.map
@@ -0,0 +1,209 @@
1
+ /**
2
+ * Username segments that strongly indicate a service/integration account. Moved here from
3
+ * IntegrationUsersCheck so there is one definition rather than two that drift.
4
+ */
5
+ export const SERVICE_LIKE_CLAUSES = [
6
+ "Username LIKE '%service%'",
7
+ "Username LIKE '%integration%'",
8
+ "Username LIKE '%.api@%'",
9
+ "Username LIKE '%\\_api\\_%'",
10
+ "Username LIKE '%.svc@%'",
11
+ "Username LIKE '%\\_svc\\_%'",
12
+ "Username LIKE '%batch%'",
13
+ "Username LIKE '%automation%'",
14
+ "Username LIKE '%system@%'",
15
+ "Username LIKE '%scheduler%'",
16
+ ];
17
+ /** The same segments as a runtime matcher, for classifying rows the query returned. */
18
+ const SERVICE_LIKE_PATTERN = /service|integration|\.api@|_api_|\.svc@|_svc_|batch|automation|system@|scheduler/i;
19
+ /** Confirm against a live org before trusting — see the plan's live-org gate. */
20
+ const INTEGRATION_LICENSE = 'Salesforce Integration';
21
+ const NEVER_LOGGED_IN_MIN_AGE_DAYS = 30;
22
+ /** Row cap on the candidate query. Hitting it sets `truncated`, which callers must disclose. */
23
+ const CANDIDATE_LIMIT = 200;
24
+ /**
25
+ * The sentence findings use to disclose a truncated account set. Defined here, next to the limit
26
+ * it describes, so the two checks cannot state different numbers.
27
+ */
28
+ export function truncationDisclosure(truncated) {
29
+ if (!truncated)
30
+ return '';
31
+ return ` The candidate query returned its maximum of ${CANDIDATE_LIMIT} rows, so the account set is truncated: further integration or service accounts may exist in this org that this run never examined. Treat any count or list here as a floor rather than a complete inventory.`;
32
+ }
33
+ /**
34
+ * One resolve per audit run, per context.
35
+ *
36
+ * Both `integration-users` and `integration-least-privilege` need the same account set, and the
37
+ * resolver's slowest query is a 90-day `LoginHistory` aggregate — running it twice per audit buys
38
+ * nothing. Memoising on the context object rather than `AuditCache` keeps this free of the
39
+ * registry-ordering constraint that cache dependencies impose (see CheckEngine.validateCacheOrdering),
40
+ * which the design deliberately avoided, and the WeakMap lets the whole result go when the context does.
41
+ */
42
+ const inFlight = new WeakMap();
43
+ export function resolveIntegrationAccounts(ctx) {
44
+ const cached = inFlight.get(ctx);
45
+ if (cached)
46
+ return cached;
47
+ // A rejection must not be cached: the second caller would inherit a failure it never provoked
48
+ // and could never retry. resolve() catches its own query failures (returning `unavailable`),
49
+ // so this path is defensive rather than expected.
50
+ const pending = resolve(ctx).catch((err) => {
51
+ inFlight.delete(ctx);
52
+ throw err;
53
+ });
54
+ inFlight.set(ctx, pending);
55
+ return pending;
56
+ }
57
+ async function resolve(ctx) {
58
+ const degraded = [];
59
+ // connected-app-run-as is not implemented: confirming which object exposes a connected app's
60
+ // run-as user requires a live-org describe, and this project forbids running against a real
61
+ // org. Disclosing it unconditionally means every finding shows the gap instead of implying the
62
+ // signal was gathered and found nothing.
63
+ degraded.push('connected-app-run-as');
64
+ let rows;
65
+ try {
66
+ rows = await ctx.soql.queryAll(`SELECT Id, Username, Profile.Name, Profile.UserLicense.Name, LastLoginDate, CreatedDate
67
+ FROM User
68
+ WHERE IsActive = true
69
+ AND ( Profile.UserLicense.Name = '${INTEGRATION_LICENSE}'
70
+ OR (LastLoginDate = null AND CreatedDate < LAST_N_DAYS:${NEVER_LOGGED_IN_MIN_AGE_DAYS})
71
+ OR ${SERVICE_LIKE_CLAUSES.join(' OR ')} )
72
+ AND Id NOT IN (SELECT UserId FROM UserLogin WHERE IsFrozen = true)
73
+ ORDER BY LastLoginDate ASC NULLS FIRST
74
+ LIMIT ${CANDIDATE_LIMIT}`);
75
+ }
76
+ catch {
77
+ return { accounts: [], degraded, unavailable: true, truncated: false };
78
+ }
79
+ const truncated = rows.length >= CANDIDATE_LIMIT;
80
+ const byId = new Map();
81
+ for (const r of rows)
82
+ byId.set(r.Id, toAccount(r));
83
+ const jobOwnerIds = await resolveJobOwnerIds(ctx, degraded);
84
+ await mergePlatformSignal(ctx, byId, jobOwnerIds, 'scheduled-job-owner');
85
+ await mergeApiOnlySignal(ctx, byId, degraded);
86
+ // A returned account with no signal is one the resolver cannot explain; downstream findings
87
+ // name the signals as their justification. This filter must run after every signal merge above
88
+ // — an account reachable only through a platform signal (e.g. scheduled-job-owner) has no
89
+ // intrinsic signals and would be dropped if this ran before the merge, defeating the point of
90
+ // having the signal at all.
91
+ const accounts = [...byId.values()].filter((a) => a.signals.length > 0);
92
+ return { accounts, degraded, unavailable: false, truncated };
93
+ }
94
+ /**
95
+ * One row → account mapping, used by both the candidate loop and the platform-signal enrichment
96
+ * loop. Two copies of this is how the two paths would drift: an account pulled in by a platform
97
+ * signal must be described exactly as one the candidate query returned.
98
+ */
99
+ function toAccount(r) {
100
+ return {
101
+ id: r.Id,
102
+ username: r.Username,
103
+ profileName: r.Profile?.Name ?? 'unknown',
104
+ lastLoginDate: r.LastLoginDate,
105
+ signals: intrinsicSignals(r),
106
+ };
107
+ }
108
+ function intrinsicSignals(r) {
109
+ const signals = [];
110
+ if (r.Profile?.UserLicense?.Name === INTEGRATION_LICENSE)
111
+ signals.push('integration-license');
112
+ if (r.LastLoginDate === null)
113
+ signals.push('never-logged-in');
114
+ if (SERVICE_LIKE_PATTERN.test(r.Username))
115
+ signals.push('username-pattern');
116
+ return signals;
117
+ }
118
+ /** Owners of scheduled Apex. An account that only runs jobs matches no username pattern. */
119
+ async function resolveJobOwnerIds(ctx, degraded) {
120
+ try {
121
+ const jobs = await ctx.soql.queryAll(`SELECT CreatedById FROM AsyncApexJob
122
+ WHERE JobType = 'ScheduledApex' AND CreatedDate = LAST_N_DAYS:90
123
+ LIMIT 500`);
124
+ return [...new Set(jobs.map((j) => j.CreatedById).filter(Boolean))];
125
+ }
126
+ catch {
127
+ degraded.push('scheduled-job-owner');
128
+ return [];
129
+ }
130
+ }
131
+ /**
132
+ * Adds `signal` to accounts already resolved, and pulls in any id the candidate query missed.
133
+ * An account reachable only by a platform signal is exactly the one the heuristics cannot see,
134
+ * so dropping it here would defeat the point of having the signal.
135
+ */
136
+ async function mergePlatformSignal(ctx, byId, ids, signal) {
137
+ if (ids.length === 0)
138
+ return;
139
+ const missing = ids.filter((id) => !byId.has(id));
140
+ if (missing.length > 0) {
141
+ try {
142
+ const inList = missing.map((i) => `'${i}'`).join(',');
143
+ const extra = await ctx.soql.queryAll(`SELECT Id, Username, Profile.Name, Profile.UserLicense.Name, LastLoginDate, CreatedDate
144
+ FROM User WHERE IsActive = true AND Id IN (${inList})`);
145
+ for (const r of extra)
146
+ byId.set(r.Id, toAccount(r));
147
+ }
148
+ catch {
149
+ // The signal's ids are known but the users are unreadable: the accounts we do have stand.
150
+ }
151
+ }
152
+ for (const id of ids) {
153
+ const acct = byId.get(id);
154
+ if (acct && !acct.signals.includes(signal))
155
+ acct.signals.push(signal);
156
+ }
157
+ }
158
+ const LOGIN_LOOKBACK_DAYS = 90;
159
+ /**
160
+ * A login that arrived over an API rather than an interactive session.
161
+ *
162
+ * `Application` is a free-text client name, so the alternatives are word-bounded: an unanchored
163
+ * `api` matches the "api" inside a connected app called "Rapid7 Insight", which would stamp
164
+ * `api-only-login` on an interactive login and, through it, an aggravating note on a CRITICAL
165
+ * finding. `ApiType` is a controlled vocabulary ("SOAP Partner", "REST", "Bulk"), so substring
166
+ * matching there is safe and is what actually carries most API logins.
167
+ *
168
+ * The same LoginHistory Application/ApiType classification is used by `SoapLoginApiAuthCheck`'s
169
+ * `isSoapLogin`, which stays deliberately broad — it grades readiness for a release update, where
170
+ * over-matching costs a needless review, whereas over-matching here mislabels an account.
171
+ */
172
+ function isApiLogin(row) {
173
+ return /soap|rest|bulk|api/i.test(row.ApiType ?? '') ||
174
+ /\b(apis?|soap|bulk|data ?loader)\b/i.test(row.Application ?? '');
175
+ }
176
+ /**
177
+ * Flags an account whose logins over the window are all API/SOAP/Bulk and never interactive.
178
+ * Application and ApiType are groupable but not filterable on LoginHistory — a WHERE clause
179
+ * naming either returns a parse error — so the query groups by them and this filters in memory.
180
+ */
181
+ async function mergeApiOnlySignal(ctx, byId, degraded) {
182
+ let rows;
183
+ try {
184
+ rows = await ctx.soql.queryAll(`SELECT UserId, Application, ApiType, COUNT(Id) logins
185
+ FROM LoginHistory
186
+ WHERE LoginTime = LAST_N_DAYS:${LOGIN_LOOKBACK_DAYS}
187
+ GROUP BY UserId, Application, ApiType`);
188
+ }
189
+ catch {
190
+ degraded.push('api-only-login');
191
+ return;
192
+ }
193
+ const apiOnly = new Map();
194
+ for (const row of rows) {
195
+ if (!row.UserId || !byId.has(row.UserId))
196
+ continue;
197
+ const soFar = apiOnly.get(row.UserId);
198
+ const thisRowIsApi = isApiLogin(row);
199
+ apiOnly.set(row.UserId, soFar === false ? false : thisRowIsApi);
200
+ }
201
+ for (const [id, only] of apiOnly) {
202
+ if (!only)
203
+ continue;
204
+ const acct = byId.get(id);
205
+ if (acct && !acct.signals.includes('api-only-login'))
206
+ acct.signals.push('api-only-login');
207
+ }
208
+ }
209
+ //# sourceMappingURL=integrationAccounts.js.map
@@ -0,0 +1,13 @@
1
+ import { SfCommand } from '@salesforce/sf-plugins-core';
2
+ import { type PreflightResult } from '../../preflight/permissionMap.js';
3
+ export default class AuditPreflightCommand extends SfCommand<PreflightResult> {
4
+ static summary: string;
5
+ static description: string;
6
+ static examples: string[];
7
+ static flags: {
8
+ 'target-org': import("@oclif/core/interfaces").OptionFlag<import("@salesforce/core").Org, import("@oclif/core/interfaces").CustomOptions>;
9
+ };
10
+ run(): Promise<PreflightResult>;
11
+ private printPreflight;
12
+ }
13
+ //# sourceMappingURL=preflight.d.ts.map