@cclabsnz/sf-audit 1.8.1 → 1.9.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 (77) hide show
  1. package/CHANGELOG.md +199 -0
  2. package/README.md +138 -758
  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/AgentActionSurfaceCheck.d.ts +1 -1
  7. package/lib/checks/impl/AgentChannelExposureCheck.d.ts +1 -1
  8. package/lib/checks/impl/AgentChannelExposureCheck.js +52 -10
  9. package/lib/checks/impl/AgentInventoryCheck.d.ts +1 -1
  10. package/lib/checks/impl/AgentMonitoringCoverageCheck.d.ts +1 -1
  11. package/lib/checks/impl/AgentUserPrivilegeCheck.d.ts +1 -1
  12. package/lib/checks/impl/ApexCrudFLSCheck.d.ts +1 -1
  13. package/lib/checks/impl/ApexCrudFLSCheck.js +3 -3
  14. package/lib/checks/impl/ApexLoggingCheck.d.ts +1 -1
  15. package/lib/checks/impl/ApexRestEndpointCheck.d.ts +1 -1
  16. package/lib/checks/impl/ApexRestEndpointCheck.js +0 -3
  17. package/lib/checks/impl/ApexSharingCheck.d.ts +1 -1
  18. package/lib/checks/impl/CodeSecurityCheck.d.ts +1 -1
  19. package/lib/checks/impl/ConnectedAppInactivityCheck.d.ts +1 -1
  20. package/lib/checks/impl/ConnectedAppsCheck.d.ts +1 -1
  21. package/lib/checks/impl/CspTrustedSitesCheck.d.ts +1 -1
  22. package/lib/checks/impl/CustomLabelsCredentialCheck.js +1 -1
  23. package/lib/checks/impl/DataClassificationCheck.js +15 -1
  24. package/lib/checks/impl/DeploymentIdentityCheck.d.ts +1 -1
  25. package/lib/checks/impl/EventMonitoringCheck.d.ts +1 -1
  26. package/lib/checks/impl/FailedLoginCheck.js +16 -1
  27. package/lib/checks/impl/FieldLevelSecurityCheck.js +29 -16
  28. package/lib/checks/impl/GuestExecutableApexCheck.d.ts +1 -1
  29. package/lib/checks/impl/GuestTrafficAnomalyCheck.d.ts +1 -1
  30. package/lib/checks/impl/GuestUserAccessCheck.d.ts +1 -1
  31. package/lib/checks/impl/GuestUserVisibilityCheck.d.ts +35 -0
  32. package/lib/checks/impl/GuestUserVisibilityCheck.js +168 -0
  33. package/lib/checks/impl/HardcodedCredentialsCheck.d.ts +2 -2
  34. package/lib/checks/impl/HardcodedCredentialsCheck.js +0 -1
  35. package/lib/checks/impl/HealthCheckCheck.d.ts +1 -1
  36. package/lib/checks/impl/HealthCheckCheck.js +1 -3
  37. package/lib/checks/impl/IntegrationLeastPrivilegeCheck.d.ts +42 -0
  38. package/lib/checks/impl/IntegrationLeastPrivilegeCheck.js +467 -0
  39. package/lib/checks/impl/IntegrationUsersCheck.js +48 -52
  40. package/lib/checks/impl/InternalUserMfaCheck.js +0 -1
  41. package/lib/checks/impl/IpRestrictionsCheck.js +39 -5
  42. package/lib/checks/impl/MfaMethodStrengthCheck.d.ts +1 -1
  43. package/lib/checks/impl/MfaRegistrationCheck.d.ts +1 -1
  44. package/lib/checks/impl/NamedCredentialsCheck.d.ts +1 -1
  45. package/lib/checks/impl/PrivilegedAccessCheck.d.ts +1 -1
  46. package/lib/checks/impl/PublicGroupSharingCheck.d.ts +1 -1
  47. package/lib/checks/impl/PublicGroupSharingCheck.js +21 -2
  48. package/lib/checks/impl/RemoteSitesCheck.d.ts +1 -1
  49. package/lib/checks/impl/ScheduledApexCheck.d.ts +1 -1
  50. package/lib/checks/impl/ScheduledApexCheck.js +0 -1
  51. package/lib/checks/impl/SeparationOfDutiesCheck.d.ts +1 -1
  52. package/lib/checks/impl/SessionHardeningCheck.d.ts +1 -1
  53. package/lib/checks/impl/SiemIntegrationCheck.d.ts +1 -1
  54. package/lib/checks/impl/SoapLoginApiAuthCheck.d.ts +10 -0
  55. package/lib/checks/impl/SoapLoginApiAuthCheck.js +151 -0
  56. package/lib/checks/impl/SsoEnforcementCheck.js +0 -1
  57. package/lib/checks/impl/TrustedUrlHygieneCheck.d.ts +1 -1
  58. package/lib/checks/impl/TrustedUrlHygieneCheck.js +3 -1
  59. package/lib/checks/impl/VisualforceXssCheck.d.ts +1 -1
  60. package/lib/checks/registry.js +4 -0
  61. package/lib/checks/support/integrationAccounts.d.ts +35 -0
  62. package/lib/checks/support/integrationAccounts.js +209 -0
  63. package/lib/commands/audit/security.d.ts +12 -1
  64. package/lib/commands/audit/security.js +32 -9
  65. package/lib/compliance/catalogs/gdpr.d.ts +3 -0
  66. package/lib/compliance/catalogs/gdpr.js +54 -0
  67. package/lib/compliance/catalogs/hipaa.d.ts +3 -0
  68. package/lib/compliance/catalogs/hipaa.js +97 -0
  69. package/lib/compliance/catalogs/index.js +4 -0
  70. package/lib/compliance/mapping.js +111 -36
  71. package/lib/findings/CheckMeta.js +2 -0
  72. package/lib/findings/exitCode.d.ts +28 -0
  73. package/lib/findings/exitCode.js +46 -0
  74. package/lib/findings/loadScoringConfig.js +5 -5
  75. package/lib/renderers/HtmlRenderer.js +1 -1
  76. package/messages/audit.security.md +6 -0
  77. package/package.json +16 -11
@@ -0,0 +1,467 @@
1
+ import { resolveIntegrationAccounts, truncationDisclosure, } from '../support/integrationAccounts.js';
2
+ import { PERM_BY_KEY } from '../permCatalog.js';
3
+ /**
4
+ * What an integration account holds that it does not need.
5
+ *
6
+ * The org already knows what these accounts are granted; nothing until now asked whether any of it
7
+ * is exercised. An integration account is the worst place for standing privilege: no interactive
8
+ * user to notice, long-lived credentials by design, and frequently outside MFA and IP restrictions
9
+ * because those break server-to-server callers.
10
+ *
11
+ * Findings are split by attacker-capability class rather than lumped under one id, because
12
+ * CAPABILITY_REGISTRY is keyed on finding id — Author Apex (code-exec, priv-esc) and Password Never
13
+ * Expires cannot share an id without the chain model losing the distinction.
14
+ *
15
+ * Field source discipline (controller ruling R12): every field name below is sourced from
16
+ * `permCatalog.ts` — this repo's canonical, live-org-verified vocabulary of PermissionSet.Permissions*
17
+ * fields — except `PermissionsDataExport`, which is not in the catalog but is verified by its live
18
+ * use in `DataExportAccessCheck.ts`. One invalid field name fails the whole PermissionSetAssignment
19
+ * query with INVALID_FIELD, which would leave this check permanently inconclusive, so nothing here
20
+ * is invented.
21
+ *
22
+ * Scope discipline (controller ruling R13): the three classes below are exactly Escalation (Author
23
+ * Apex, Customize Application, Manage Users, Assign Permission Sets), Data (Data Export, View All
24
+ * Users), and Hygiene (Password Never Expires). The catalog holds further escalation-grade
25
+ * permissions (Modify Metadata, Manage Internal Users, Manage Auth. Providers, Manage Connected
26
+ * Apps) that are deliberately NOT included here — widening this check mid-plan is scope creep,
27
+ * logged as a follow-up rather than done inline.
28
+ *
29
+ * Modify All Data and View All Data are deliberately absent: `integration-users` already grades
30
+ * them against SBS-ACS-008, and a second id would double-count in both the score and the chains.
31
+ *
32
+ * Limit, disclosed on every finding: this check runs inside `audit security`, which has SOQL but no
33
+ * EventLogFile bodies. A Read grant an integration never exercises is not observable here.
34
+ *
35
+ * Second limit, disclosed on every write-evidence finding: this is the first check in the plugin
36
+ * that queries record data rather than configuration. It aggregates ownership only — the queries
37
+ * return owner ids and counts, never a field value — and it runs as the audit user with sharing
38
+ * enforced, so it is conclusive only when that user holds View All Data. See
39
+ * WRITE_VISIBILITY_CAVEAT and `recordVisibility`, and PERMISSIONS.md, which states the same thing
40
+ * to the org owner.
41
+ */
42
+ /** Permission API name → label, sourced from permCatalog.ts's DangerousPerm entries. */
43
+ const ESCALATION_PERMS = {
44
+ [PERM_BY_KEY.AuthorApex.field]: PERM_BY_KEY.AuthorApex.label,
45
+ [PERM_BY_KEY.CustomizeApplication.field]: PERM_BY_KEY.CustomizeApplication.label,
46
+ [PERM_BY_KEY.ManageUsers.field]: PERM_BY_KEY.ManageUsers.label,
47
+ [PERM_BY_KEY.AssignPermissionSets.field]: PERM_BY_KEY.AssignPermissionSets.label,
48
+ };
49
+ const DATA_PERMS = {
50
+ // Not in permCatalog.ts; verified live by DataExportAccessCheck.ts's own PermissionSetAssignment
51
+ // query, which already selects this exact field name.
52
+ PermissionsDataExport: 'Data Export',
53
+ [PERM_BY_KEY.ViewAllUsers.field]: PERM_BY_KEY.ViewAllUsers.label,
54
+ };
55
+ const HYGIENE_PERMS = {
56
+ [PERM_BY_KEY.PasswordNeverExpires.field]: PERM_BY_KEY.PasswordNeverExpires.label,
57
+ };
58
+ const ALL_PERMS = { ...ESCALATION_PERMS, ...DATA_PERMS, ...HYGIENE_PERMS };
59
+ const READ_BLIND_SPOT = 'This check sees permission grants, not read traffic: a Read grant an integration never exercises is not observable from SOQL. Run "sf audit apps" for read-side evidence.';
60
+ /**
61
+ * The write probe's own limit, disclosed wherever write evidence is reported.
62
+ *
63
+ * The record-count aggregate runs as the audit user with sharing enforced. An audit user with
64
+ * object Read but no visibility of the records — restrictive org-wide defaults and no sharing rule,
65
+ * which is exactly what a least-privilege audit account looks like — gets a successful query and
66
+ * zero rows back, which is indistinguishable from "the integration never wrote here". Reporting
67
+ * that as an unused grant would be a false accusation against a working integration, so the probe
68
+ * runs only when the audit user is known to see all records.
69
+ */
70
+ const WRITE_VISIBILITY_CAVEAT = 'Write evidence is bounded by what the audit user can see: the record-count aggregate runs with sharing enforced, so records hidden from the audit user are indistinguishable from records that were never written. View All Data (or Modify All Data) on the audit user is required for this probe to be conclusive; without it every object is listed as unprobed rather than reported as unused.';
71
+ const DORMANT_DAYS = 90;
72
+ /** Two aggregates per object, so 30 objects. Anything dropped is named in the finding. */
73
+ const PROBE_QUERY_BUDGET = 60;
74
+ const OBJECT_CAP = PROBE_QUERY_BUDGET / 2;
75
+ export class IntegrationLeastPrivilegeCheck {
76
+ id = 'integration-least-privilege';
77
+ name = 'Integration Account Least Privilege';
78
+ category = 'Permissions';
79
+ description = 'Reports permissions held by integration and service accounts that the account is not using — escalation-grade permissions, bulk-data permissions, and standing-credential settings';
80
+ async run(ctx) {
81
+ const findings = [];
82
+ const permSetUrl = `${ctx.orgInfo.instanceUrl}/lightning/setup/PermSets/home`;
83
+ const resolved = await resolveIntegrationAccounts(ctx);
84
+ if (resolved.unavailable) {
85
+ findings.push(this.inconclusive('integration-least-privilege-inaccessible', 'Integration accounts could not be enumerated'));
86
+ return { findings };
87
+ }
88
+ if (resolved.accounts.length === 0) {
89
+ findings.push({
90
+ id: 'integration-least-privilege-none',
91
+ category: this.category,
92
+ riskLevel: 'LOW',
93
+ passed: true,
94
+ title: 'No integration or service accounts found',
95
+ detail:
96
+ // The enumeration lists what was actually matched against. connected-app run-as is not
97
+ // implemented (the resolver reports it as degraded on every run), so naming it here would
98
+ // tell the reader a signal was evaluated and found nothing when it was never gathered —
99
+ // on the finding most likely to be read as "you have no integration accounts".
100
+ 'No active account matched an integration signal (Salesforce Integration licence, scheduled-job owner, never logged in, API-only logins, or a service-account username pattern), so there is no non-human identity holding surplus permissions.' +
101
+ this.degradedNote(resolved.degraded) +
102
+ truncationDisclosure(resolved.truncated),
103
+ remediation: 'As integration accounts are created, grant them a dedicated permission set scoped to the objects and operations they actually use, rather than a broad profile.',
104
+ });
105
+ return { findings };
106
+ }
107
+ const byId = new Map(resolved.accounts.map((a) => [a.id, a]));
108
+ const idList = resolved.accounts.map((a) => `'${a.id}'`).join(',');
109
+ const permFields = Object.keys(ALL_PERMS).map((p) => `PermissionSet.${p}`).join(', ');
110
+ let psa;
111
+ try {
112
+ psa = await ctx.soql.queryAll(`SELECT AssigneeId, PermissionSetId, PermissionSet.Name, PermissionSet.IsOwnedByProfile, ${permFields}
113
+ FROM PermissionSetAssignment WHERE AssigneeId IN (${idList})`);
114
+ }
115
+ catch {
116
+ findings.push(this.inconclusive('integration-least-privilege-permissions-inaccessible', 'Integration account permissions could not be queried'));
117
+ return { findings };
118
+ }
119
+ const grants = [];
120
+ for (const row of psa) {
121
+ const ps = row.PermissionSet;
122
+ const account = byId.get(row.AssigneeId);
123
+ if (!ps || !account)
124
+ continue;
125
+ const viaProfile = ps.IsOwnedByProfile === true;
126
+ // A profile-owned permission set's Name is Salesforce's autogenerated internal string
127
+ // (id-shaped, e.g. "X00e5w000001AbCd"), not the profile's label — naming it in a finding
128
+ // would tell the reader nothing. The account's own profileName (from Profile.Name, already
129
+ // carried on every resolved IntegrationAccount) is the human-readable name and needs no new
130
+ // field. Mirrors the same fix applied to psMeta below for grantPathNote.
131
+ const grantName = viaProfile ? (account.profileName ?? ps.Name) : ps.Name;
132
+ for (const [permission, label] of Object.entries(ALL_PERMS)) {
133
+ if (ps[permission] === true) {
134
+ grants.push({ account, permission, label, viaProfile, grantName });
135
+ }
136
+ }
137
+ }
138
+ const truncationNote = truncationDisclosure(resolved.truncated);
139
+ this.emit(findings, grants, ESCALATION_PERMS, permSetUrl, {
140
+ id: 'integration-least-privilege-escalation-permissions',
141
+ riskLevel: 'CRITICAL',
142
+ title: 'escalation-grade permission(s)',
143
+ detail: 'These permissions let the holder change how the org runs, not merely read from it. Author Apex and Customize Application deploy code and metadata that execute in system context; Manage Users and Assign Permission Sets let the holder grant itself anything it does not already have. On an account with long-lived credentials and no interactive user to notice, each is a standing path to org control.',
144
+ remediation: 'Remove these from the integration account\'s profile and permission sets. An integration that genuinely deploys metadata should do so through a dedicated deployment identity with a change-managed credential, not through the account that runs its day-to-day traffic.',
145
+ // Scoped to this class deliberately. Every permission above is exercisable over the API, so
146
+ // the note is about who is exercising it, not whether it can be exercised — and it would be
147
+ // meaningless attached to Password Never Expires or Data Export.
148
+ apiOnlyNote: ' At least one of these accounts has no interactive login in the last 90 days, so no person is exercising the permissions that account holds through the UI. That is not evidence they are unused: each is reachable over the API — Author Apex through Metadata API deploys and anonymous Apex, Customize Application through metadata deploys, Manage Users and Assign Permission Sets through User and PermissionSetAssignment writes. Unless the integration itself deploys metadata or administers users, these grants are surplus to what its traffic needs.',
149
+ suffix: truncationNote,
150
+ });
151
+ this.emit(findings, grants, DATA_PERMS, permSetUrl, {
152
+ id: 'integration-least-privilege-data-permissions',
153
+ riskLevel: 'HIGH',
154
+ title: 'bulk-data or directory permission(s)',
155
+ detail: 'Data Export and View All Users reach past the object permissions an integration is scoped to: a full data export or the complete staff roster. An integration that moves specific records needs neither.',
156
+ remediation: 'Remove these and grant object- and field-level access scoped to the records the integration actually moves.',
157
+ suffix: truncationNote,
158
+ });
159
+ this.emit(findings, grants, HYGIENE_PERMS, permSetUrl, {
160
+ id: 'integration-least-privilege-hygiene',
161
+ riskLevel: 'MEDIUM',
162
+ title: 'standing-credential setting(s)',
163
+ detail: 'Password Never Expires on a service account means a credential that was correct in 2019 is still valid today, and that a rotation policy which appears to cover the org does not cover this account.',
164
+ remediation: 'Rotate the credential and move the integration to a certificate-based or OAuth JWT flow, where expiry is managed rather than disabled.',
165
+ suffix: truncationNote,
166
+ });
167
+ // Dormancy is sourced from User.LastLoginDate, gathered by the candidate query above (which
168
+ // has already succeeded by this point — resolveIntegrationAccounts returns early with
169
+ // unavailable: true otherwise). It does not depend on the separate LoginHistory query that
170
+ // feeds the api-only-login signal, so a degraded api-only-login signal does not affect this.
171
+ const cutoff = Date.now() - DORMANT_DAYS * 86_400_000;
172
+ const grantedIds = new Set(grants.map((g) => g.account.id));
173
+ // Guard on lastLoginDate !== null: an account that has never logged in is not evidence of
174
+ // dormancy — there is no "stopped being used" to observe. integration-users already reports
175
+ // never-logged-in accounts as undocumented identities.
176
+ const dormant = resolved.accounts.filter((a) => grantedIds.has(a.id) && a.lastLoginDate !== null && new Date(a.lastLoginDate).getTime() < cutoff);
177
+ if (dormant.length > 0) {
178
+ const dormantIds = new Set(dormant.map((a) => a.id));
179
+ const withEscalation = grants.some((g) => g.permission in ESCALATION_PERMS && dormantIds.has(g.account.id));
180
+ findings.push({
181
+ id: 'integration-least-privilege-dormant',
182
+ category: this.category,
183
+ riskLevel: withEscalation ? 'HIGH' : 'MEDIUM',
184
+ title: `${dormant.length} integration account(s) hold permissions but have not logged in for ${DORMANT_DAYS} days`,
185
+ detail: `An account that has not authenticated in ${DORMANT_DAYS} days is not exercising any permission it holds, so every grant on it is surplus by definition. The credential remains valid, which is what makes a dormant privileged service account attractive to an attacker: nobody is watching an account nobody expects to be active, so use of it is unlikely to be noticed. ${READ_BLIND_SPOT}${truncationNote}`,
186
+ remediation: 'Confirm with the owning team whether the integration is retired. If it is, deactivate the account rather than merely stripping permissions. If it is seasonal, record that on the account so the next reviewer does not have to rediscover it.',
187
+ affectedItems: dormant.slice(0, 30).map((a) => ({
188
+ label: a.username,
189
+ url: `${ctx.orgInfo.instanceUrl}/${a.id}`,
190
+ note: `last login ${a.lastLoginDate.split('T')[0]} | classified by: ${a.signals.join(', ')}`,
191
+ })),
192
+ });
193
+ }
194
+ let objPerms = null;
195
+ // Tracks the ObjectPermissions query specifically failing (as opposed to succeeding with zero
196
+ // rows), so that a failure here can also gate `-ok` below — write-evidence gathering that never
197
+ // ran must not read as a clean bill any more than an unprobed object does.
198
+ let objPermsUnavailable = false;
199
+ const psIds = [...new Set(psa.map((p) => p.PermissionSetId))];
200
+ try {
201
+ if (psIds.length > 0) {
202
+ objPerms = await ctx.soql.queryAll(`SELECT ParentId, SobjectType, PermissionsCreate, PermissionsEdit, PermissionsDelete
203
+ FROM ObjectPermissions
204
+ WHERE ParentId IN (${psIds.map((i) => `'${i}'`).join(',')})
205
+ AND (PermissionsCreate = true OR PermissionsEdit = true OR PermissionsDelete = true)`);
206
+ }
207
+ }
208
+ catch {
209
+ objPerms = null; // Suppressed, not passed: ObjectPermissions failing must not read as a clean bill.
210
+ objPermsUnavailable = true;
211
+ findings.push({
212
+ id: 'integration-least-privilege-object-permissions-inaccessible',
213
+ category: this.category,
214
+ riskLevel: 'INFO',
215
+ inconclusive: true,
216
+ title: 'Object-level permissions could not be queried (insufficient access)',
217
+ detail: 'The ObjectPermissions query failed, so the Create, Edit and Delete grants held by these integration accounts could not be read. No statement can be made about write grants they hold and do not use. This does not affect the escalation-grade, bulk-data, hygiene or dormancy findings above, which are drawn from separate queries and still stand.',
218
+ remediation: 'Grant the audit user View Setup and Configuration and re-run.',
219
+ });
220
+ }
221
+ if (objPerms && objPerms.length > 0) {
222
+ // Widest over-grants first: rank by how many integration accounts hold write on the object.
223
+ const accountsPerObject = new Map();
224
+ const psToAccounts = new Map();
225
+ for (const p of psa) {
226
+ const list = psToAccounts.get(p.PermissionSetId) ?? [];
227
+ list.push(p.AssigneeId);
228
+ psToAccounts.set(p.PermissionSetId, list);
229
+ }
230
+ for (const op of objPerms) {
231
+ const set = accountsPerObject.get(op.SobjectType) ?? new Set();
232
+ for (const a of psToAccounts.get(op.ParentId) ?? [])
233
+ set.add(a);
234
+ accountsPerObject.set(op.SobjectType, set);
235
+ }
236
+ const psMeta = new Map();
237
+ for (const p of psa) {
238
+ if (p.PermissionSet) {
239
+ const viaProfile = p.PermissionSet.IsOwnedByProfile === true;
240
+ // A profile-owned permission set's Name is Salesforce's autogenerated internal string
241
+ // (id-shaped, e.g. "X00e5w000001AbCd"), not the profile's label — naming it would tell
242
+ // the reader nothing. The assignee's own profileName (from Profile.Name, already carried
243
+ // on every resolved IntegrationAccount) is the human-readable name and needs no new field.
244
+ const name = viaProfile ? (byId.get(p.AssigneeId)?.profileName ?? p.PermissionSet.Name) : p.PermissionSet.Name;
245
+ psMeta.set(p.PermissionSetId, { name, viaProfile });
246
+ }
247
+ }
248
+ const ordered = [...accountsPerObject.keys()].sort((a, b) => {
249
+ const d = (accountsPerObject.get(b)?.size ?? 0) - (accountsPerObject.get(a)?.size ?? 0);
250
+ return d !== 0 ? d : a.localeCompare(b);
251
+ });
252
+ // The probe is only meaningful if the audit user can see every record; see
253
+ // WRITE_VISIBILITY_CAVEAT. When it cannot (or when that cannot be established), no object is
254
+ // probed at all — the whole set goes to the unprobed list and the finding degrades to the
255
+ // inconclusive shape rather than accusing a working integration of an unused grant.
256
+ const visibility = await this.recordVisibility(ctx);
257
+ const conclusive = visibility === 'sees-all-records';
258
+ const probed = conclusive ? ordered.slice(0, OBJECT_CAP) : [];
259
+ const skipped = conclusive ? ordered.slice(OBJECT_CAP) : [];
260
+ const blind = conclusive ? [] : [...ordered];
261
+ const unused = [];
262
+ const probeFailures = [];
263
+ for (const object of probed) {
264
+ const wrote = await this.hasEverWritten(ctx, object, idList);
265
+ if (wrote === null)
266
+ probeFailures.push(object);
267
+ else if (!wrote)
268
+ unused.push(object);
269
+ }
270
+ // Probe failures first: they are the objects where something went wrong on this run, and the
271
+ // list is capped for display. Ordering them behind budget-skipped objects pushed them out of
272
+ // sight while still counting them in the title.
273
+ const unprobed = [
274
+ ...probeFailures.map((o) => ({ object: o, note: 'not probed — the record-count query failed; no conclusion drawn' })),
275
+ ...blind.map((o) => ({
276
+ object: o,
277
+ note: visibility === 'no-view-all-data'
278
+ ? 'not probed — audit user lacks View All Data, so absence of records proves nothing'
279
+ : 'not probed — the audit user\'s record visibility could not be established',
280
+ })),
281
+ ...skipped.map((o) => ({ object: o, note: `not probed — beyond this run's ${OBJECT_CAP}-object probe budget` })),
282
+ ];
283
+ if (unused.length > 0 || unprobed.length > 0) {
284
+ // Only needed to qualify the grant path on objects actually reported as unused.
285
+ const sharedWith = unused.length > 0 ? await this.assigneesOutsideSet(ctx, psIds, idList) : new Map();
286
+ const capNote = skipped.length > 0
287
+ ? ` ${skipped.length} object(s) were not probed for budget: the check probes at most ${OBJECT_CAP} objects per run, ordered by how many integration accounts hold write on them.`
288
+ : '';
289
+ const failureNote = probeFailures.length > 0
290
+ ? ` ${probeFailures.length} object(s) were not probed because the record-count query failed against them.`
291
+ : '';
292
+ const blindNote = blind.length > 0
293
+ ? visibility === 'no-view-all-data'
294
+ ? ` ${blind.length} object(s) were not probed because the audit user does not hold View All Data or Modify All Data: without it the record-count query is bounded by sharing and cannot distinguish "never written" from "not visible to this audit user".`
295
+ : ` ${blind.length} object(s) were not probed because the audit user's own record visibility could not be established on this run, so no absence of records could be read as evidence.`
296
+ : '';
297
+ // Controller ruling R5: an unused count of zero with only unprobed objects is not a
298
+ // conclusion — it must not read as a graded finding about objects the check never queried.
299
+ const inconclusiveOnly = unused.length === 0 && unprobed.length > 0;
300
+ findings.push({
301
+ id: 'integration-least-privilege-unused-write-objects',
302
+ category: this.category,
303
+ riskLevel: inconclusiveOnly ? 'INFO' : 'MEDIUM',
304
+ inconclusive: inconclusiveOnly || undefined,
305
+ title: inconclusiveOnly
306
+ ? `${unprobed.length} object(s) with an integration write grant could not be checked for write evidence`
307
+ : `${unused.length} object(s) carry an integration write grant with no record ever written`,
308
+ detail: `For each object an integration account is granted Create, Edit or Delete on, the check looks for any record in the org attributed to that account by CreatedById or LastModifiedById. An object with no such record has a write grant the account has never exercised. Attribution is not perfect — a record the account wrote and someone else later edited no longer attributes to it — so treat this as strong evidence rather than proof. ${WRITE_VISIBILITY_CAVEAT}${failureNote}${blindNote}${capNote} ${READ_BLIND_SPOT}`,
309
+ remediation: 'Narrow Create, Edit and Delete on the listed objects at the grant named on each item. Check that grant before editing it: where the item says the profile or permission set is also assigned outside this integration set, removing the object permission there removes it for every one of those users — move the integration onto a dedicated permission set and narrow that instead. Where an object is genuinely written rarely, record that on the permission set so the next review does not re-raise it.',
310
+ affectedItems: [
311
+ ...unused.slice(0, 30).map((o) => ({
312
+ label: o,
313
+ url: permSetUrl,
314
+ note: `write granted, never written | granted ${this.grantPathNote(o, objPerms, psMeta, sharedWith)}`,
315
+ })),
316
+ ...unprobed.slice(0, 10).map((u) => ({ label: u.object, url: permSetUrl, note: u.note })),
317
+ ],
318
+ });
319
+ }
320
+ }
321
+ if (findings.length === 0 && !objPermsUnavailable) {
322
+ findings.push({
323
+ id: 'integration-least-privilege-ok',
324
+ category: this.category,
325
+ riskLevel: 'LOW',
326
+ passed: true,
327
+ title: `${resolved.accounts.length} integration account(s); no surplus permission found`,
328
+ detail: `No integration account holds an escalation-grade permission, a bulk-data permission or a standing-credential setting, none is dormant, and every probed object write grant has been exercised.${this.degradedNote(resolved.degraded)}${truncationDisclosure(resolved.truncated)} This result covers write grants and system permissions only. ${WRITE_VISIBILITY_CAVEAT} A Read grant an integration never exercises is not observable from SOQL, so this is not a statement that these accounts are at least privilege — run "sf audit apps" for read-side evidence from the RestApi event log.`,
329
+ remediation: 'Keep integration accounts on a dedicated permission set rather than a shared profile, and re-run after any integration is added or repurposed.',
330
+ });
331
+ }
332
+ return { findings };
333
+ }
334
+ /** The degraded-signal qualification, agreeing in number with what was actually degraded. */
335
+ degradedNote(degraded) {
336
+ if (degraded.length === 0)
337
+ return '';
338
+ const head = degraded.length === 1 ? 'One qualification' : `${degraded.length} qualifications`;
339
+ const noun = degraded.length === 1 ? 'signal' : 'signals';
340
+ const tail = degraded.length === 1 ? 'an account reachable only by it' : 'an account reachable only by one of them';
341
+ return ` ${head}: the following classification ${noun} could not be gathered on this run — ${degraded.join(', ')} — so ${tail} was not examined.`;
342
+ }
343
+ /**
344
+ * Whether the audit user itself can see every record in the org, which is what makes the write
345
+ * probe conclusive (see WRITE_VISIBILITY_CAVEAT).
346
+ *
347
+ * `AuditContext` carries the org, not the running user, and there is no SOQL expression for
348
+ * "the current user". The Connect API's `/chatter/users/me` is the one identity resource reachable
349
+ * through the existing read-only REST client; orgs with Chatter disabled, or any unexpected
350
+ * response, resolve as unknown. Every failure path returns a non-conclusive answer, so the worst
351
+ * outcome is that write evidence is reported as ungathered — never that it is reported as clean.
352
+ */
353
+ async recordVisibility(ctx) {
354
+ let me = null;
355
+ try {
356
+ me = await ctx.rest.get('/chatter/users/me');
357
+ }
358
+ catch {
359
+ return 'unknown';
360
+ }
361
+ const id = typeof me?.id === 'string' ? me.id : '';
362
+ // Validated as a User id before interpolation: an unexpected body must not reach a query.
363
+ if (!/^005[0-9A-Za-z]{12}([0-9A-Za-z]{3})?$/.test(id))
364
+ return 'unknown';
365
+ try {
366
+ const rows = await ctx.soql.queryAll(`SELECT PermissionSet.PermissionsViewAllData, PermissionSet.PermissionsModifyAllData
367
+ FROM PermissionSetAssignment WHERE AssigneeId = '${id}'`);
368
+ const seesAll = rows.some((r) => r.PermissionSet?.PermissionsViewAllData === true || r.PermissionSet?.PermissionsModifyAllData === true);
369
+ return seesAll ? 'sees-all-records' : 'no-view-all-data';
370
+ }
371
+ catch {
372
+ return 'unknown';
373
+ }
374
+ }
375
+ /**
376
+ * Assignees of each granting permission set that are NOT in the resolved integration set.
377
+ *
378
+ * A grant reached through a profile, or through an org-wide permission set, is held by everyone
379
+ * assigned to it. "Remove this object permission" is safe advice on a dedicated integration set
380
+ * and destructive on a shared one, so the finding has to say which it is. Null when the count
381
+ * could not be established — an unknown breadth is reported as unknown, not as exclusive.
382
+ */
383
+ async assigneesOutsideSet(ctx, psIds, idList) {
384
+ if (psIds.length === 0)
385
+ return new Map();
386
+ try {
387
+ const rows = await ctx.soql.queryAll(`SELECT PermissionSetId, COUNT(Id) c FROM PermissionSetAssignment
388
+ WHERE PermissionSetId IN (${psIds.map((i) => `'${i}'`).join(',')})
389
+ AND AssigneeId NOT IN (${idList})
390
+ GROUP BY PermissionSetId`);
391
+ return new Map(rows.map((r) => [r.PermissionSetId, Number(r.c) || 0]));
392
+ }
393
+ catch {
394
+ return null;
395
+ }
396
+ }
397
+ /** Names the profile or permission set that grants write on `object`, and how widely it is held. */
398
+ grantPathNote(object, objPerms, psMeta, sharedWith) {
399
+ const parents = [...new Set(objPerms.filter((p) => p.SobjectType === object).map((p) => p.ParentId))];
400
+ const named = parents.map((parentId) => {
401
+ const meta = psMeta.get(parentId);
402
+ if (!meta)
403
+ return `by an unidentified permission set (${parentId})`;
404
+ const kind = meta.viaProfile ? 'profile' : 'permission set';
405
+ if (sharedWith === null)
406
+ return `via ${kind} ${meta.name} (how widely it is assigned could not be established — check before editing)`;
407
+ const outside = sharedWith.get(parentId) ?? 0;
408
+ return outside > 0
409
+ ? `via ${kind} ${meta.name} (also assigned to ${outside} account(s) outside this integration set — removing it there removes it for all of them)`
410
+ : `via ${kind} ${meta.name}`;
411
+ });
412
+ if (named.length === 0)
413
+ return 'by a permission set this run could not identify';
414
+ const shown = named.slice(0, 3).join('; ');
415
+ return named.length > 3 ? `${shown}; and ${named.length - 3} more` : shown;
416
+ }
417
+ /**
418
+ * True if the account wrote any record of this object, false if none, null if unprobeable.
419
+ * Null must never be read as false — an object we could not query is not an unused grant.
420
+ */
421
+ async hasEverWritten(ctx, object, idList) {
422
+ for (const field of ['CreatedById', 'LastModifiedById']) {
423
+ try {
424
+ const rows = await ctx.soql.queryAll(`SELECT ${field}, COUNT(Id) c FROM ${object} WHERE ${field} IN (${idList}) GROUP BY ${field}`);
425
+ if (rows.length > 0)
426
+ return true;
427
+ }
428
+ catch {
429
+ return null;
430
+ }
431
+ }
432
+ return false;
433
+ }
434
+ /** Emits one finding for a permission class, or nothing when the class has no grants. */
435
+ emit(findings, grants, perms, url, shape) {
436
+ const matched = grants.filter((g) => g.permission in perms);
437
+ if (matched.length === 0)
438
+ return;
439
+ const apiOnly = matched.some((g) => g.account.signals.includes('api-only-login'));
440
+ const apiNote = apiOnly ? (shape.apiOnlyNote ?? '') : '';
441
+ findings.push({
442
+ id: shape.id,
443
+ category: this.category,
444
+ riskLevel: shape.riskLevel,
445
+ title: `${matched.length} ${shape.title} held by integration accounts`,
446
+ detail: `${shape.detail}${apiNote} ${READ_BLIND_SPOT}${shape.suffix ?? ''}`,
447
+ remediation: shape.remediation,
448
+ affectedItems: matched.slice(0, 30).map((g) => ({
449
+ label: `${g.account.username} — ${g.label}`,
450
+ url,
451
+ note: `${g.label} ${g.viaProfile ? `via profile ${g.grantName}` : `via permission set ${g.grantName}`} | classified by: ${g.account.signals.join(', ')}`,
452
+ })),
453
+ });
454
+ }
455
+ inconclusive(id, what) {
456
+ return {
457
+ id,
458
+ category: this.category,
459
+ riskLevel: 'INFO',
460
+ inconclusive: true,
461
+ title: `${what} (insufficient access)`,
462
+ detail: 'The audit user could not gather the data needed to evaluate integration account privilege.',
463
+ remediation: 'Grant the audit user View Setup and Configuration and re-run.',
464
+ };
465
+ }
466
+ }
467
+ //# sourceMappingURL=IntegrationLeastPrivilegeCheck.js.map
@@ -1,23 +1,16 @@
1
- // Username segments that strongly indicate a service/integration account
2
- const SERVICE_LIKE_CLAUSES = [
3
- "Username LIKE '%service%'",
4
- "Username LIKE '%integration%'",
5
- "Username LIKE '%.api@%'",
6
- "Username LIKE '%_api_%'",
7
- "Username LIKE '%.svc@%'",
8
- "Username LIKE '%_svc_%'",
9
- "Username LIKE '%batch%'",
10
- "Username LIKE '%automation%'",
11
- "Username LIKE '%system@%'",
12
- "Username LIKE '%scheduler%'",
13
- ];
14
- const ASSIGNEE_LIKE_CLAUSES = [
15
- "Assignee.Username LIKE '%service%'",
16
- "Assignee.Username LIKE '%integration%'",
17
- "Assignee.Username LIKE '%.api@%'",
18
- "Assignee.Username LIKE '%_api_%'",
19
- "Assignee.Username LIKE '%.svc@%'",
20
- ];
1
+ import { resolveIntegrationAccounts, truncationDisclosure } from '../support/integrationAccounts.js';
2
+ /**
3
+ * SBS-ACS-007 requires ALL non-human identities to be inventoried. A signal the resolver could
4
+ * not gather (e.g. connected-app-run-as, which is unconditionally degraded — see
5
+ * support/integrationAccounts.ts) means a whole class of accounts was never looked for, so a
6
+ * finding that lists or counts what was found must say so plainly rather than imply completeness.
7
+ */
8
+ function degradedDisclosure(degraded) {
9
+ if (degraded.length === 0)
10
+ return '';
11
+ const names = degraded.join(', ');
12
+ return ` This run could not gather the following signal(s): ${names}. Accounts identifiable only by ${names} are not represented here.`;
13
+ }
21
14
  export class IntegrationUsersCheck {
22
15
  id = 'integration-users';
23
16
  name = 'Integration / Service Account Inventory';
@@ -26,22 +19,24 @@ export class IntegrationUsersCheck {
26
19
  async run(ctx) {
27
20
  const findings = [];
28
21
  const baseUrl = ctx.orgInfo.instanceUrl;
29
- // Q1: Find candidate service accounts — users who have never logged in (and were created
30
- // more than 30 days ago, to exclude freshly provisioned human users) or whose username
31
- // matches common integration account naming patterns. These are likely non-human identities
32
- // requiring SBS-ACS-007 documentation.
33
- const serviceUsernameClause = SERVICE_LIKE_CLAUSES.join(' OR ');
34
- const candidates = await ctx.soql.queryAll(`SELECT Id, Username, Profile.Name, LastLoginDate
35
- FROM User
36
- WHERE IsActive = true
37
- AND UserType = 'Standard'
38
- AND (
39
- (LastLoginDate = null AND CreatedDate < LAST_N_DAYS:30)
40
- OR ${serviceUsernameClause}
41
- )
42
- AND Id NOT IN (SELECT UserId FROM UserLogin WHERE IsFrozen = true)
43
- ORDER BY LastLoginDate ASC NULLS FIRST
44
- LIMIT 200`);
22
+ // Q1: Resolve candidate integration/service accounts via the shared resolver (Task 2-4),
23
+ // which tags each account with the signal(s) that classified it — integration-license,
24
+ // never-logged-in, username-pattern, scheduled-job-owner, api-only-login — rather than this
25
+ // check keeping its own drifting copy of the username heuristic.
26
+ const resolved = await resolveIntegrationAccounts(ctx);
27
+ if (resolved.unavailable) {
28
+ findings.push({
29
+ id: 'integration-users-inaccessible',
30
+ category: this.category,
31
+ riskLevel: 'INFO',
32
+ inconclusive: true,
33
+ title: 'Integration accounts could not be enumerated (insufficient access)',
34
+ detail: 'The audit user could not query User records, so no statement can be made about non-human identities.',
35
+ remediation: 'Grant the audit user View Setup and Configuration and re-run.',
36
+ });
37
+ return { findings };
38
+ }
39
+ const candidates = resolved.accounts;
45
40
  if (candidates.length === 0) {
46
41
  findings.push({
47
42
  id: 'integration-users-none',
@@ -49,7 +44,9 @@ export class IntegrationUsersCheck {
49
44
  riskLevel: 'LOW',
50
45
  passed: true,
51
46
  title: 'No candidate non-human identities found: SBS-ACS-007',
52
- detail: 'SBS-ACS-007 requires all non-human identities to be inventoried and documented. No standard users matching common service account patterns (by username) or never-logged-in users were found.',
47
+ detail: 'SBS-ACS-007 requires all non-human identities to be inventoried and documented. No standard users matching common service account patterns (by username) or never-logged-in users were found.' +
48
+ degradedDisclosure(resolved.degraded) +
49
+ truncationDisclosure(resolved.truncated),
53
50
  remediation: 'As integration accounts are created, ensure they are documented with a named owner, stated purpose, and review date.',
54
51
  });
55
52
  return { findings };
@@ -60,28 +57,27 @@ export class IntegrationUsersCheck {
60
57
  category: this.category,
61
58
  riskLevel: 'INFO',
62
59
  title: `${candidates.length} candidate non-human identity/identities found: SBS-ACS-007`,
63
- detail: 'SBS-ACS-007 requires all non-human identities (integration accounts, service users, automation users) to be inventoried and documented with a named owner, stated purpose, and review date. These users were identified by never having a UI login (and being more than 30 days old) or matching common service-account username patterns.',
60
+ detail: 'SBS-ACS-007 requires all non-human identities (integration accounts, service users, automation users) to be inventoried and documented with a named owner, stated purpose, and review date. These users were identified by never having a UI login (and being more than 30 days old) or matching common service-account username patterns.' +
61
+ degradedDisclosure(resolved.degraded) +
62
+ truncationDisclosure(resolved.truncated),
64
63
  remediation: 'Verify that each listed user is a known, documented non-human identity. Any undocumented account should be reviewed and either documented or deactivated. Maintain a register of all integration identities with their owner and purpose.',
65
64
  affectedItems: candidates.map((u) => ({
66
- label: u.Username,
67
- url: `${baseUrl}/${u.Id}`,
68
- note: u.LastLoginDate
69
- ? `last login: ${new Date(u.LastLoginDate).toISOString().split('T')[0]} | profile: ${u.Profile.Name}`
70
- : `never logged in | profile: ${u.Profile.Name}`,
65
+ label: u.username,
66
+ url: `${baseUrl}/${u.id}`,
67
+ note: u.lastLoginDate
68
+ ? `last login: ${new Date(u.lastLoginDate).toISOString().split('T')[0]} | profile: ${u.profileName}`
69
+ : `never logged in | profile: ${u.profileName}`,
71
70
  })),
72
71
  });
73
- // Q2: Among service-account-looking users, find those with Modify All / View All Data.
74
- // SBS-ACS-008 requires non-human identities to hold only the minimum required permissions.
75
- const assigneeServiceClause = ASSIGNEE_LIKE_CLAUSES.join(' OR ');
72
+ // Q2: Among the resolved integration/service accounts, find those with Modify All / View All
73
+ // Data. SBS-ACS-008 requires non-human identities to hold only the minimum required
74
+ // permissions. Filters on the resolver's account ids rather than a username heuristic, so
75
+ // this can never be structurally unable to see an account the inventory above just listed.
76
+ const idList = candidates.map((c) => `'${c.id}'`).join(',');
76
77
  const broadResult = await ctx.soql.query(`SELECT Assignee.Id, Assignee.Username,
77
78
  PermissionSet.Name, PermissionSet.PermissionsModifyAllData, PermissionSet.PermissionsViewAllData
78
79
  FROM PermissionSetAssignment
79
- WHERE Assignee.IsActive = true
80
- AND Assignee.UserType = 'Standard'
81
- AND (
82
- Assignee.LastLoginDate = null
83
- OR ${assigneeServiceClause}
84
- )
80
+ WHERE Assignee.Id IN (${idList})
85
81
  AND (PermissionSet.PermissionsModifyAllData = true OR PermissionSet.PermissionsViewAllData = true)
86
82
  LIMIT 200`);
87
83
  const broadPermUsers = broadResult.records;
@@ -6,7 +6,6 @@ export class InternalUserMfaCheck {
6
6
  async run(ctx) {
7
7
  const findings = [];
8
8
  const baseUrl = ctx.orgInfo.instanceUrl;
9
- const setupUrl = `${baseUrl}/lightning/setup/EnhancedProfiles/home`;
10
9
  // queryAll to avoid LIMIT 500 truncation — PSA query below fetches all records,
11
10
  // so a truncated user list would produce false-pass results for the missing users.
12
11
  const users = await ctx.soql.queryAll(`SELECT Id, Username, Profile.Name, LastLoginDate