@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
@@ -6,8 +6,12 @@ export interface CapabilityEntry {
6
6
  }
7
7
  /**
8
8
  * The full attack model lives here: finding id → attacker capabilities it grants.
9
- * Keep this the single source of truth so the ~75 checks stay untouched.
10
- * Every key MUST correspond to a finding id some check can emit (see registry-integrity test).
9
+ * Keep this the single source of truth so the 88 checks stay untouched.
10
+ *
11
+ * Every key MUST correspond to a finding id some check can actually emit, and every id referenced
12
+ * by a named chain must be emittable too — a typo in either place fails silently (a key that
13
+ * matches nothing simply never grants, and a chain ingredient that matches nothing means the chain
14
+ * never fires). `test/unit/chains/registryIntegrity.test.ts` enforces both directions.
11
15
  */
12
16
  export declare const CAPABILITY_REGISTRY: Record<string, CapabilityEntry>;
13
17
  /** Resolve the effective capabilities for a finding (inline overrides registry; passed/inconclusive yield nothing). */
@@ -1,7 +1,11 @@
1
1
  /**
2
2
  * The full attack model lives here: finding id → attacker capabilities it grants.
3
- * Keep this the single source of truth so the ~75 checks stay untouched.
4
- * Every key MUST correspond to a finding id some check can emit (see registry-integrity test).
3
+ * Keep this the single source of truth so the 88 checks stay untouched.
4
+ *
5
+ * Every key MUST correspond to a finding id some check can actually emit, and every id referenced
6
+ * by a named chain must be emittable too — a typo in either place fails silently (a key that
7
+ * matches nothing simply never grants, and a chain ingredient that matches nothing means the chain
8
+ * never fires). `test/unit/chains/registryIntegrity.test.ts` enforces both directions.
5
9
  */
6
10
  export const CAPABILITY_REGISTRY = {
7
11
  // Guest / unauthenticated foothold
@@ -47,6 +51,13 @@ export const CAPABILITY_REGISTRY = {
47
51
  // Guest API/Bulk access — programmatic unauthenticated bulk read / destruction
48
52
  'guest-api-access-enabled': { grants: ['unauth-foothold', 'data-read-bulk'] },
49
53
  'guest-api-hard-delete': { grants: ['unauth-foothold', 'data-write'] },
54
+ // Guest enumeration of other USERS. The staff roster is the targeting asset behind credential
55
+ // stuffing and phishing at named admins, and both of the first two paths expose every User record
56
+ // on their own, so both are bulk reads. The object-level Read grant is not: it makes User
57
+ // queryable but still needs a sharing path before it returns anyone else's record.
58
+ 'guest-user-visibility-view-all-users': { grants: ['unauth-foothold', 'data-read-bulk'] },
59
+ 'guest-user-visibility-owd': { grants: ['unauth-foothold', 'data-read-bulk'] },
60
+ 'guest-user-visibility-object-read': { grants: ['unauth-foothold', 'data-read'] },
50
61
  // Classic Visualforce sites — a second unauthenticated foothold surface
51
62
  'classic-sites-active': { grants: ['unauth-foothold'] },
52
63
  // Mass data-export capability — a bulk-read sink for an authenticated actor
@@ -57,6 +68,41 @@ export const CAPABILITY_REGISTRY = {
57
68
  'login-access-policy-login-as-enabled': { grants: ['priv-esc', 'data-read-bulk'] },
58
69
  // External federation an attacker could ride in on
59
70
  'auth-providers-social': { grants: ['low-trust-authenticated'] },
71
+ // Toxic permission combinations held by one user. Capabilities follow each combo's own stated
72
+ // outcome — see COMBOS in SeparationOfDutiesCheck, where the ids are defined.
73
+ 'separation-of-duties-self-escalation': { grants: ['priv-esc', 'org-takeover'] },
74
+ 'separation-of-duties-identity-takeover': { grants: ['priv-esc', 'org-takeover'] },
75
+ 'separation-of-duties-grant-self-data': { grants: ['priv-esc', 'data-read-bulk'] },
76
+ 'separation-of-duties-code-and-data': { grants: ['code-exec', 'data-read-bulk', 'data-write'] },
77
+ 'separation-of-duties-external-exfil-channel': { grants: ['external-egress', 'data-read-bulk'] },
78
+ 'separation-of-duties-tamper-and-cover': { grants: ['data-write', 'data-read-bulk'] },
79
+ // Admin-equivalent users who are not on the System Administrator profile: the same reach as
80
+ // 'users-super-admin-combo', which is why it grants the same capability.
81
+ 'privileged-access-shadow-admins': { grants: ['org-takeover', 'priv-esc'] },
82
+ // Flows running in system context without sharing enforcement — the Flow analogue of
83
+ // 'portal-exposed-apex-without-sharing'. Screen flows need a user to drive them, so they do not
84
+ // grant the unattended write that an autolaunched flow does.
85
+ 'flows-autolaunched-without-sharing': { grants: ['code-exec', 'data-read', 'data-write'] },
86
+ 'flows-screen-without-sharing': { grants: ['code-exec', 'data-read'] },
87
+ // Sharing rules granting All Internal Users — bulk read for any authenticated employee. Internal
88
+ // by definition, so this grants no 'low-trust-authenticated' entry point of its own.
89
+ 'public-group-sharing-exposure': { grants: ['data-read-bulk'] },
90
+ // Report folders any authenticated user can view.
91
+ 'report-folder-access-public': { grants: ['data-read'] },
92
+ // "Secure guest user record access" not enforced: guest-owned records can defeat a Private OWD.
93
+ // The policy gap widens guest visibility rather than creating the surface itself, so it mirrors
94
+ // 'guest-user-sharing-exposure' rather than the confirmed bulk-read sinks.
95
+ 'guest-record-access-policy-not-enforced': { grants: ['unauth-foothold', 'data-read'] },
96
+ // Sensitive data present and readable — what every other capability is ultimately reaching for.
97
+ 'encryption-coverage-unencrypted-sensitive': { grants: ['data-read'] },
98
+ 'sandbox-data-masking-pii-present': { grants: ['data-read'] },
99
+ // Integration accounts holding permissions they do not use. Author Apex and Customize Application
100
+ // deploy code that runs in system context, and the user-management permissions let the holder
101
+ // grant itself the rest — the same reach as 'users-author-apex', on an account with long-lived
102
+ // credentials and nobody watching. The unused-grant and dormancy findings grant nothing: an
103
+ // unexercised permission is not a capability an attacker holds today.
104
+ 'integration-least-privilege-escalation-permissions': { grants: ['code-exec', 'priv-esc'] },
105
+ 'integration-least-privilege-data-permissions': { grants: ['data-read-bulk'] },
60
106
  };
61
107
  /** Resolve the effective capabilities for a finding (inline overrides registry; passed/inconclusive yield nothing). */
62
108
  export function capabilitiesFor(finding) {
@@ -1,3 +1,4 @@
1
+ import { capabilitiesFor } from './CapabilityRegistry.js';
1
2
  const has = (s, ...caps) => caps.every((c) => s.has(c));
2
3
  const hasAny = (s, ...caps) => caps.some((c) => s.has(c));
3
4
  const byIds = (active, ids) => active.filter((f) => ids.includes(f.id));
@@ -10,9 +11,17 @@ export const NAMED_CHAINS = [
10
11
  title: 'Unauthenticated bulk exfiltration',
11
12
  severity: 'CRITICAL',
12
13
  narrative: 'An unauthenticated guest foothold combines with guest-reachable code execution or public ' +
13
- 'external sharing to read business data in bulk without any login.',
14
+ 'external sharing to read business data in bulk without any login. In practice this is ' +
15
+ 'reached over the site\'s Aura endpoint (/s/sfsites/aura) with aura.token=null: ' +
16
+ 'RecordUiController/ACTION$executeGraphQL returns record data the guest user can see, and ' +
17
+ 'aura.ApexAction.execute invokes @AuraEnabled Apex — which, in a class that runs without ' +
18
+ 'sharing, skips record-level access control entirely and will accept arbitrary record ids. ' +
19
+ 'No credentials are involved at any point, so login-based controls (MFA, IP ranges, SSO) ' +
20
+ 'never engage.',
14
21
  remediation: 'Remove guest object/sharing access, ensure no guest-invokable Apex runs without sharing, ' +
15
- 'and set external OWD to Private. Grant portal access only via sharing sets.',
22
+ 'and set external OWD to Private. Grant portal access only via sharing sets. Because the ' +
23
+ 'requests never reach a login page, tightening authentication does not mitigate this — the ' +
24
+ 'object permissions, sharing model and Apex sharing declarations are the controls that apply.',
16
25
  match(present, active) {
17
26
  if (!has(present, 'unauth-foothold'))
18
27
  return null;
@@ -23,8 +32,13 @@ export const NAMED_CHAINS = [
23
32
  'guest-executable-apex-unprotected', 'guest-executable-apex-exposed',
24
33
  'guest-object-exposure-public-owd', 'guest-object-exposure-guest-owned',
25
34
  'guest-api-access-enabled', 'guest-api-hard-delete', 'classic-sites-active',
35
+ 'guest-user-visibility-view-all-users', 'guest-user-visibility-owd', 'guest-user-visibility-object-read',
26
36
  'portal-exposed-apex-without-sharing', 'sharing-model-external-read', 'sharing-model-external-write',
27
37
  'field-level-security-high', 'field-level-security-medium',
38
+ // The guardrail whose absence lets guest-owned records defeat a Private OWD, and the Flow
39
+ // analogue of portal-exposed Apex running without sharing.
40
+ 'guest-record-access-policy-not-enforced',
41
+ 'flows-autolaunched-without-sharing', 'flows-screen-without-sharing',
28
42
  ]);
29
43
  return steps.length >= 2 ? steps : null;
30
44
  },
@@ -35,14 +49,23 @@ export const NAMED_CHAINS = [
35
49
  severity: 'CRITICAL',
36
50
  narrative: 'Live EventLogFile evidence shows unauthenticated guests probing from anonymizer/hosting IPs or ' +
37
51
  'running GraphQL object-enumeration (totalCount) sweeps, AND the org exposes objects that are ' +
38
- 'bulk-readable by those same guests. This is not a theoretical exposure — it is reconnaissance ' +
39
- 'against a confirmed exfiltration surface, i.e. an incident likely already in progress.',
52
+ 'bulk-readable by those same guests. The sweeps arrive as AuraRequest/GraphQlQueryExecution ' +
53
+ 'events against /s/sfsites/aura — aura://RecordUiController/ACTION$executeGraphQL asking only ' +
54
+ 'for totalCount per object, which is how an attacker maps the readable surface before pulling ' +
55
+ 'from it. This is not a theoretical exposure — it is reconnaissance against a confirmed ' +
56
+ 'exfiltration surface, i.e. an incident likely already in progress.',
40
57
  remediation: 'Treat as an active incident: block the source IPs at the WAF/CDN, close the guest bulk-read surface ' +
41
58
  '(set external OWD to Private, strip guest object read, enforce "Secure guest user record access"), ' +
42
59
  'and preserve/forward the event logs before the short EventLogFile retention window closes.',
43
60
  match(_present, active) {
44
61
  const traffic = byIds(active, ['guest-traffic-anomaly-recon', 'guest-traffic-anomaly-anonymizer']);
45
- const exposure = byIds(active, ['guest-object-exposure-public-owd', 'guest-object-exposure-guest-owned']);
62
+ // A readable User roster counts as an exposed surface in its own right — recon against an org
63
+ // that leaks its staff list is the same incident. The object-level Read grant is excluded: on
64
+ // its own it is not a confirmed exposure, and this chain asserts one already in progress.
65
+ const exposure = byIds(active, [
66
+ 'guest-object-exposure-public-owd', 'guest-object-exposure-guest-owned',
67
+ 'guest-user-visibility-view-all-users', 'guest-user-visibility-owd',
68
+ ]);
46
69
  if (traffic.length === 0 || exposure.length === 0)
47
70
  return null;
48
71
  return [...traffic, ...exposure];
@@ -64,6 +87,14 @@ export const NAMED_CHAINS = [
64
87
  'sharing-model-external-read', 'sharing-model-external-write', 'guest-user-baseline',
65
88
  'escalation-perms-found', 'users-author-apex', 'users-super-admin-combo',
66
89
  'login-access-policy-delegated-admins', 'login-access-policy-login-as-enabled',
90
+ // Admin-equivalent users off the System Administrator profile, and the toxic combinations
91
+ // that let one user grant themselves access, are escalation steps in their own right.
92
+ 'privileged-access-shadow-admins',
93
+ 'separation-of-duties-self-escalation', 'separation-of-duties-identity-takeover',
94
+ 'separation-of-duties-grant-self-data',
95
+ // An integration account holding Author Apex, Customize Application or user-management
96
+ // permissions it does not use has the same escalation reach as users-author-apex above.
97
+ 'integration-least-privilege-escalation-permissions',
67
98
  ]);
68
99
  return steps.length >= 2 ? steps : null;
69
100
  },
@@ -82,6 +113,9 @@ export const NAMED_CHAINS = [
82
113
  'hardcoded-credentials-found', 'custom-labels-credential-value-match', 'custom-labels-credential-name-match',
83
114
  'debug-log-active-traces', 'cors-wildcard-origin', 'cors-broad-origin',
84
115
  'named-credentials-inventory', 'named-credentials-http-endpoint', 'remote-sites-inventory',
116
+ // A user who can stand up connected apps and bypass API access control has provisioned
117
+ // their own egress path.
118
+ 'separation-of-duties-external-exfil-channel',
85
119
  ]);
86
120
  return steps.length >= 2 ? steps : null;
87
121
  },
@@ -101,6 +135,8 @@ export const NAMED_CHAINS = [
101
135
  const sink = byIds(active, [
102
136
  'sharing-model-external-read', 'sharing-model-external-write',
103
137
  'field-level-security-high', 'field-level-security-medium', 'users-view-all-data',
138
+ 'public-group-sharing-exposure', 'report-folder-access-public',
139
+ 'encryption-coverage-unencrypted-sensitive',
104
140
  ]);
105
141
  return sink.length > 0 ? [...inj, ...sink] : null;
106
142
  },
@@ -112,7 +148,13 @@ export const NAMED_CHAINS = [
112
148
  narrative: 'A guest-reachable Agentforce channel lets an unauthenticated attacker send prompt-injection input to an ' +
113
149
  'agent that runs as an over-privileged user (Modify/View All Data or broad object write) and can drive ' +
114
150
  'write-capable actions. Public input, privileged identity, and state-changing actions are all present at ' +
115
- 'once, so a single injected prompt can read, alter, or destroy data across the agent\'s reach.',
151
+ 'once, so a single injected prompt can read, alter, or destroy data across the agent\'s reach. ' +
152
+ 'Note this does NOT ride the site\'s Aura endpoint: agent conversations go to the org\'s messaging host ' +
153
+ '(<subdomain>.my.salesforce-scrt.com) over the Messaging for In-App and Web API (/iamessage/api/v2/...). ' +
154
+ 'Guest reachability comes from that API\'s unauthenticated access-token flow, which needs only the org id ' +
155
+ 'and the Embedded Service deployment\'s API name (esDeveloperName) — both of which appear in the ' +
156
+ 'client-side bootstrap of any page hosting the widget. That flow is a supported configuration for public ' +
157
+ 'support chat; the risk here is not the channel existing, it is the channel reaching a privileged agent.',
116
158
  remediation: 'Break any one link: remove the guest/public binding, scope the agent run-as user to least privilege, ' +
117
159
  'or remove write-capable actions from the exposed agent (and add confirmation/guardrails where they must stay).',
118
160
  match(_present, active) {
@@ -147,6 +189,94 @@ export const NAMED_CHAINS = [
147
189
  return [...agents, ...staleUrl, ...noCapture];
148
190
  },
149
191
  },
192
+ {
193
+ id: 'sandbox-pii-exposure',
194
+ title: 'Unmasked production PII in a weakly-controlled sandbox',
195
+ severity: 'HIGH',
196
+ narrative: 'This sandbox holds populated PII fields — almost certainly a copy of production data that was ' +
197
+ 'never masked — and it is not held to production access standards. Sandboxes routinely carry ' +
198
+ 'more admins, weaker authentication and broader sharing than the org they were refreshed from, ' +
199
+ 'so the same records sit behind materially weaker controls. The data is real; only the ' +
200
+ 'protection is not.',
201
+ remediation: 'Run Salesforce Data Mask on the sandbox (or refresh without production data), and bring its ' +
202
+ 'authentication and sharing configuration up to production standard for as long as real data ' +
203
+ 'remains in it.',
204
+ match(_present, active) {
205
+ const pii = byIds(active, ['sandbox-data-masking-pii-present']);
206
+ if (pii.length === 0)
207
+ return null;
208
+ const weakControls = byIds(active, [
209
+ 'internal-user-mfa-gaps', 'trusted-ip-broad-ranges', 'mfa-portal-users-without-enforcement',
210
+ 'public-group-sharing-exposure', 'report-folder-access-public', 'standard-profiles-in-use',
211
+ 'privileged-access-shadow-admins', 'sharing-model-external-read', 'sharing-model-external-write',
212
+ 'guest-user-read-access', 'guest-user-write-access', 'guest-user-sharing-exposure',
213
+ ]);
214
+ return weakControls.length > 0 ? [...pii, ...weakControls] : null;
215
+ },
216
+ },
217
+ {
218
+ id: 'insider-bulk-exfil',
219
+ title: 'Insider bulk export without monitoring',
220
+ severity: 'HIGH',
221
+ narrative: 'Business data is readable in bulk by any authenticated internal user, at least one profile or ' +
222
+ 'permission set can export it en masse (Weekly Data Export, or API access combined with ' +
223
+ 'View/Modify All Data), and there is no monitoring that would record the export happening. ' +
224
+ 'Broad read plus bulk egress plus no audit trail is the insider-threat and post-credential-' +
225
+ 'compromise path — and the missing third element is what makes it unreconstructable afterwards.',
226
+ remediation: 'Narrow the broad internal sharing, restrict Weekly Data Export and Bulk API access to a named ' +
227
+ 'few, and enable Event Monitoring (plus forwarding to a SIEM) so bulk reads are recorded and ' +
228
+ 'alertable.',
229
+ match(_present, active) {
230
+ const broadRead = byIds(active, [
231
+ 'public-group-sharing-exposure', 'report-folder-access-public',
232
+ 'users-view-all-data', 'users-modify-all-data',
233
+ // An unused Data Export or View All Users grant on an integration account is the same
234
+ // bulk-read reach as the other members of this set.
235
+ 'integration-least-privilege-data-permissions',
236
+ ]);
237
+ const bulkEgress = byIds(active, [
238
+ 'data-export-weekly-export', 'data-export-bulk-api-viewall',
239
+ 'separation-of-duties-external-exfil-channel',
240
+ ]);
241
+ const blindSpot = byIds(active, [
242
+ 'event-monitoring-disabled', 'siem-integration-not-detected', 'event-monitoring-retention-short',
243
+ ]);
244
+ if (broadRead.length === 0 || bulkEgress.length === 0 || blindSpot.length === 0)
245
+ return null;
246
+ return [...broadRead, ...bulkEgress, ...blindSpot];
247
+ },
248
+ },
249
+ {
250
+ id: 'undetected-compromise',
251
+ title: 'Exploitable access with no detection coverage',
252
+ severity: 'MEDIUM',
253
+ narrative: 'The org already presents a real attacker capability — an unauthenticated foothold, a ' +
254
+ 'privilege-escalation path, or org takeover — and simultaneously lacks the controls that ' +
255
+ 'would notice it being used. Two or more of threat detection, Event Monitoring, a Transaction ' +
256
+ 'Security policy and SIEM forwarding are absent. This chain does not add exposure; it means ' +
257
+ 'the exposure already present would go unobserved, and an incident could not be reconstructed.',
258
+ remediation: 'Close the detection gap first: enable Event Monitoring with adequate retention, turn on threat ' +
259
+ 'detection event storage, add a Transaction Security policy, and forward events to a SIEM. Then ' +
260
+ 'remediate the underlying access findings.',
261
+ match(present, active) {
262
+ if (!hasAny(present, 'unauth-foothold', 'priv-esc', 'org-takeover'))
263
+ return null;
264
+ const blindSpots = byIds(active, [
265
+ 'threat-detection-inactive', 'threat-detection-guest-anomaly-missing',
266
+ 'event-monitoring-disabled', 'event-monitoring-retention-short',
267
+ 'transaction-security-policy-none', 'siem-integration-not-detected', 'siem-retention-gap',
268
+ ]);
269
+ // One missing control is a finding on its own; two or more is a systemic blind spot. Requiring
270
+ // two keeps this from firing on every org that has not bought Shield.
271
+ if (blindSpots.length < 2)
272
+ return null;
273
+ const exposure = active.filter((f) => {
274
+ const g = capabilitiesFor(f).grants;
275
+ return g.includes('unauth-foothold') || g.includes('priv-esc') || g.includes('org-takeover');
276
+ });
277
+ return exposure.length > 0 ? [...exposure.slice(0, 3), ...blindSpots] : null;
278
+ },
279
+ },
150
280
  {
151
281
  id: 'mfa-bypass-admin',
152
282
  title: 'MFA bypass to privileged compromise',
@@ -158,7 +288,10 @@ export const NAMED_CHAINS = [
158
288
  const weakness = byIds(active, [
159
289
  'trusted-ip-broad-ranges', 'internal-user-mfa-gaps', 'mfa-portal-users-without-enforcement',
160
290
  ]);
161
- const targets = byIds(active, ['users-modify-all-data', 'users-view-all-data', 'users-super-admin-combo']);
291
+ const targets = byIds(active, [
292
+ 'users-modify-all-data', 'users-view-all-data', 'users-super-admin-combo',
293
+ 'privileged-access-shadow-admins', 'separation-of-duties-self-escalation',
294
+ ]);
162
295
  return weakness.length > 0 && targets.length > 0 ? [...weakness, ...targets] : null;
163
296
  },
164
297
  },
@@ -1,3 +1,9 @@
1
+ // MessageType values that are reachable from a browser, and therefore candidate public
2
+ // surfaces. Verified against a live org's MessagingChannel describe (2026-08); the full
3
+ // picklist also covers Text, Phone, WhatsApp, Facebook, Line, WeChat, AppleBusinessChat,
4
+ // Rcs, Email, Voice/PstnVoice/SipVoice/WhatsAppVoice, Alexa, GoogleHome, Custom, Omega,
5
+ // InternalCopilot, MsCopilot and VoiceIntegrationPilot, none of which is a web endpoint.
6
+ const WEB_MESSAGE_TYPES = new Set(['EmbeddedMessaging', 'WebChat']);
1
7
  export class AgentChannelExposureCheck {
2
8
  id = 'agent-channel-exposure';
3
9
  name = 'Agentforce Channel Exposure';
@@ -47,6 +53,25 @@ export class AgentChannelExposureCheck {
47
53
  boundAgentDeveloperName: boundAgent ?? undefined,
48
54
  });
49
55
  }
56
+ // A web-type messaging channel is a browser-reachable surface: Embedded Messaging and
57
+ // Chat are served to the public web and, for guests, reached through the messaging API's
58
+ // unauthenticated access-token flow. Treat those as public channel candidates. We still
59
+ // cannot bind an agent to one (no queryable binding exists), so they land in the unmapped
60
+ // list and are reported as an unconfirmed mapping, never as an asserted exposure.
61
+ for (const m of messagingChannels) {
62
+ if (m.IsActive === false)
63
+ continue;
64
+ if (!m.MessageType || !WEB_MESSAGE_TYPES.has(m.MessageType))
65
+ continue;
66
+ publicChannels.push({
67
+ kind: 'messaging-channel-web',
68
+ id: m.Id,
69
+ label: m.MasterLabel ?? m.Id,
70
+ note: `Messaging channel of type ${m.MessageType}` +
71
+ `${m.PlatformType ? ` (${m.PlatformType})` : ''} — a web-reachable surface, ` +
72
+ `available to unauthenticated visitors via the messaging API's guest access-token flow`,
73
+ });
74
+ }
50
75
  // Resolve agent->channel bindings from Tooling deployment configs where the
51
76
  // platform exposes them. This is the only source that lets us assert exposure
52
77
  // as fact rather than inference.
@@ -101,6 +126,10 @@ export class AgentChannelExposureCheck {
101
126
  detail: `The Agentforce agent "${agent.label}" (${agent.developerName}) is bound to ${channel.note}. ` +
102
127
  `Unauthenticated visitors can send this agent input, so any prompt-injection payload reaches an agent ` +
103
128
  `that executes with the data access of its run-as user${agent.runAsUserId ? ` (${agent.runAsUserId})` : ''}. ` +
129
+ `Reachability does not depend on the site's Aura endpoint: conversations go to the org's messaging host ` +
130
+ `(<subdomain>.my.salesforce-scrt.com) via the Messaging for In-App and Web API, whose unauthenticated ` +
131
+ `access-token flow needs only the org id and this deployment's API name (the esDeveloperName), both of ` +
132
+ `which are present in the client-side bootstrap of any page that hosts the widget. ` +
104
133
  `This is the exact combination behind the ForcedLeak pattern: public input channel plus a privileged agent identity.`,
105
134
  remediation: 'Confirm this agent is intended to be publicly reachable. If so, tightly scope the run-as user (least privilege), review the agent action surface for write-capable actions, and ensure Event Monitoring / Transaction Security cover the agent. If not intended, remove the guest/public binding.',
106
135
  affectedItems: [
@@ -116,19 +145,25 @@ export class AgentChannelExposureCheck {
116
145
  // internal-only inventory value. Reported once, listing the internal channels.
117
146
  const publiclyExposedDevNames = new Set(mappedExposures.map((m) => m.agent.developerName));
118
147
  const internalAgents = activeAgents.filter((a) => !publiclyExposedDevNames.has(a.developerName));
119
- const internalChannels = messagingChannels.filter((m) => m.IsActive !== false);
148
+ // Web-type channels have already been promoted to publicChannels above, so anything left
149
+ // here is a non-web inbound surface (SMS, WhatsApp, Facebook, voice, email, ...).
150
+ const nonWebChannels = messagingChannels.filter((m) => m.IsActive !== false && !(m.MessageType && WEB_MESSAGE_TYPES.has(m.MessageType)));
120
151
  if (internalAgents.length > 0 && unmappedPublicChannels.length === 0) {
152
+ const types = [...new Set(nonWebChannels.map((m) => m.MessageType).filter(Boolean))];
121
153
  findings.push({
122
154
  id: 'agent-channel-exposure-internal',
123
155
  category: this.category,
124
156
  riskLevel: 'INFO',
125
- title: `${internalAgents.length} active agent(s) on internal-only channels`,
126
- detail: `${internalAgents.length} active agent(s) were not found on any guest-reachable Experience Cloud site or public embedded deployment. ` +
127
- (internalChannels.length > 0
128
- ? `${internalChannels.length} messaging channel(s) are configured (internal / authenticated inbound surfaces). `
129
- : 'No public web channels were discovered. ') +
130
- `Channel reachability in Salesforce is not always expressed in queryable metadata, so treat this as "no public exposure found" rather than a guarantee.`,
131
- remediation: 'Confirm these agents are only exposed on authenticated/internal channels. Re-check after any new Experience Cloud site or embedded deployment goes live.',
157
+ title: `${internalAgents.length} active agent(s) with no public channel binding confirmed`,
158
+ detail: `${internalAgents.length} active agent(s) were not found on any guest-reachable Experience Cloud site, public embedded deployment, or web-type messaging channel. ` +
159
+ (nonWebChannels.length > 0
160
+ ? `${nonWebChannels.length} non-web messaging channel(s) are active${types.length > 0 ? ` (${types.join(', ')})` : ''}. ` +
161
+ `These are inbound surfaces whose senders are external parties identified by phone number or account handle — not ` +
162
+ `Salesforce-authenticated users — but they are not browser-reachable endpoints, and no queryable binding ties an ` +
163
+ `agent to a messaging channel, so no exposure is asserted for them either way. `
164
+ : 'No web-reachable channels were discovered. ') +
165
+ `Channel reachability in Salesforce is not always expressed in queryable metadata, so treat this as "no public exposure found" rather than a guarantee, and not as evidence that these agents are internal-only.`,
166
+ remediation: 'Confirm in Setup → Messaging Settings whether any of these agents is deployed on a messaging channel. Any channel of type EmbeddedMessaging or WebChat is a public web surface and is reported separately; for the remaining channels, verify who can send to them and scope each agent\'s run-as user to least privilege regardless. Re-check after any new Experience Cloud site, embedded deployment, or messaging channel goes live.',
132
167
  affectedItems: internalAgents.map((a) => ({
133
168
  label: `${a.label} (${a.developerName})`,
134
169
  note: `active v${a.activeVersion ?? '?'}${a.runAsUserId ? ` | run-as: ${a.runAsUserId}` : ''}`,
@@ -179,10 +214,17 @@ export class AgentChannelExposureCheck {
179
214
  }
180
215
  async queryMessagingChannels(ctx) {
181
216
  try {
182
- return await ctx.soql.queryAll(`SELECT Id, MasterLabel, ChannelType, IsActive FROM MessagingChannel`);
217
+ return await ctx.soql.queryAll(`SELECT Id, MasterLabel, MessageType, PlatformType, IsActive FROM MessagingChannel`);
183
218
  }
184
219
  catch {
185
- return [];
220
+ // Fall back to the minimal projection so an org missing the type fields still yields an
221
+ // inventory count, rather than reporting no channels at all.
222
+ try {
223
+ return await ctx.soql.queryAll(`SELECT Id, MasterLabel, IsActive FROM MessagingChannel`);
224
+ }
225
+ catch {
226
+ return [];
227
+ }
186
228
  }
187
229
  }
188
230
  // Embedded Service deployment details (embedded chat / messaging for web). Query the
@@ -6,7 +6,6 @@ const HAS_FLS = /(?:\.isAccessible\(\)|\.isCreateable\(\)|\.isUpdateable\(\)|\.i
6
6
  // Classes that are exempt from CRUD/FLS enforcement by design:
7
7
  // batch, scheduled, and trigger handlers run in a system context
8
8
  const IS_BATCH_OR_SCHEDULED = /implements\s+(?:Database\.Batchable|Schedulable|Database\.StatefulBatch|Database\.AllowsCallouts)/i;
9
- const IS_TEST = /@IsTest\b/i;
10
9
  const WITHOUT_SHARING = /\bwithout\s+sharing\b/i;
11
10
  export class ApexCrudFLSCheck {
12
11
  id = 'apex-crud-fls';
@@ -32,8 +31,9 @@ export class ApexCrudFLSCheck {
32
31
  }
33
32
  const withoutSharingNoFls = [];
34
33
  const withDmlNoFls = [];
35
- // apexBodies is pre-filtered by HardcodedCredentialsCheck to exclude test classes;
36
- // IS_TEST guard here is redundant but kept for cache-miss safety
34
+ // apexBodies is pre-filtered by HardcodedCredentialsCheck, which excludes @IsTest classes
35
+ // before populating the cache. There is deliberately no second guard here: a cache miss
36
+ // yields an empty array, not unfiltered bodies, so there is nothing for one to catch.
37
37
  for (const { name, body } of apexBodies) {
38
38
  if (!body || IS_BATCH_OR_SCHEDULED.test(body))
39
39
  continue;
@@ -2,9 +2,6 @@ const REST_RESOURCE_RE = /@RestResource\s*\(\s*urlMapping\s*=/i;
2
2
  const WITHOUT_SHARING_RE = /\bwithout\s+sharing\b/i;
3
3
  const NO_SHARING_DECLARED_RE = /\b(with|without|inherited)\s+sharing\b/i;
4
4
  const IS_TEST_RE = /@IsTest\b/i;
5
- // Indicators that the endpoint performs some form of caller verification
6
- const AUTH_CHECK_RE = /(?:RestContext\.request\.headers\.get|UserInfo\.getUserId\(\)|UserInfo\.getOrganizationId\(\)|Auth\.AuthConfiguration|isPortalEnabled\(\)|getSessionId\(\))/i;
7
- const GUEST_VISIBLE_RE = /(@HttpGet|@HttpPost|@HttpPut|@HttpDelete|@HttpPatch)/i;
8
5
  export class ApexRestEndpointCheck {
9
6
  id = 'apex-rest-endpoint';
10
7
  name = 'Apex REST Endpoint Security';
@@ -56,7 +56,7 @@ export class CustomLabelsCredentialCheck {
56
56
  category: this.category,
57
57
  riskLevel: 'HIGH',
58
58
  title: `${nameMatches.length} Custom Label(s) have names suggesting credential storage`,
59
- detail: `Custom Labels with names like "ApiKey", "ClientSecret", or "AuthToken" strongly suggest they store sensitive credentials. This is a critical misconfiguration: Custom Labels are globally readable by every authenticated Salesforce user via the \`{!\$Label.X}\` merge field in Visualforce pages, Flows, and Apex. Any user who can query the Tooling API or view source markup containing the merge field can read the label value, including attacker accounts, compromised users, and over-permissioned portal users. Unlike Named Credentials or Protected Custom Metadata, Custom Labels have no access control.`,
59
+ detail: `Custom Labels with names like "ApiKey", "ClientSecret", or "AuthToken" strongly suggest they store sensitive credentials. This is a critical misconfiguration: Custom Labels are globally readable by every authenticated Salesforce user via the \`{!$Label.X}\` merge field in Visualforce pages, Flows, and Apex. Any user who can query the Tooling API or view source markup containing the merge field can read the label value, including attacker accounts, compromised users, and over-permissioned portal users. Unlike Named Credentials or Protected Custom Metadata, Custom Labels have no access control.`,
60
60
  remediation: 'Migrate these credentials to Named Credentials or Protected Custom Metadata (visibility: "Protected"). Named Credentials encrypt stored values and provide managed authentication. Protected Custom Metadata is only accessible from the managed package, not from arbitrary user queries.',
61
61
  affectedItems: nameMatches.map((l) => ({
62
62
  label: l.Name,
@@ -33,13 +33,16 @@ export class DataClassificationCheck {
33
33
  // EncryptionKey records indicate Shield is licensed and active.
34
34
  let encryptionEnabled = false;
35
35
  let encryptionKeyCount = 0;
36
+ let encryptionQueryFailed = false;
36
37
  try {
37
38
  const encResult = await ctx.soql.query('SELECT Id, DeveloperName FROM EncryptionKey LIMIT 10');
38
39
  encryptionKeyCount = encResult.records.length;
39
40
  encryptionEnabled = encryptionKeyCount > 0;
40
41
  }
41
42
  catch {
42
- // EncryptionKey inaccessible — Shield not licensed or no permission to read keys
43
+ // Unreadable is not the same as absent: an org may hold Shield keys the audit user
44
+ // cannot see, and "not detected" would assert something this query never established.
45
+ encryptionQueryFailed = true;
43
46
  }
44
47
  // SBS-DATA-001/002: data classification coverage
45
48
  if (classificationQueryFailed) {
@@ -96,6 +99,17 @@ export class DataClassificationCheck {
96
99
  remediation: 'Verify encryption is applied to all fields classified as sensitive or PII. Review the Encryption Statistics page in Setup → Security → Platform Encryption to confirm field-level coverage.',
97
100
  });
98
101
  }
102
+ else if (encryptionQueryFailed) {
103
+ findings.push({
104
+ id: 'data-encryption-inconclusive',
105
+ category: this.category,
106
+ riskLevel: 'INFO',
107
+ inconclusive: true,
108
+ title: 'Shield Platform Encryption status could not be determined: SBS-DATA-003',
109
+ detail: 'The EncryptionKey object was not readable, so whether Shield Platform Encryption is configured is unknown. This is distinct from Shield being absent: an org may hold encryption keys that the audit user cannot see.',
110
+ remediation: 'Grant the audit user read access to EncryptionKey and re-run, or confirm encryption coverage manually in Setup → Security → Platform Encryption.',
111
+ });
112
+ }
99
113
  else {
100
114
  findings.push({
101
115
  id: 'data-encryption-not-detected',
@@ -43,6 +43,7 @@ export class FailedLoginCheck {
43
43
  }
44
44
  // Query 2: per-user aggregation to detect targeted brute force
45
45
  let perUserCounts = [];
46
+ let perUserUnavailable = false;
46
47
  try {
47
48
  const aggResult = await ctx.soql.query(`SELECT Username, COUNT(Id)
48
49
  FROM LoginHistory
@@ -53,7 +54,9 @@ export class FailedLoginCheck {
53
54
  perUserCounts = aggResult.records;
54
55
  }
55
56
  catch {
56
- // Per-user breakdown unavailable — still emit org-level finding
57
+ // Recorded: without the per-user breakdown, "no brute-force pattern" is not a
58
+ // conclusion this check can reach, only a question it could not answer.
59
+ perUserUnavailable = true;
57
60
  }
58
61
  const bruteForceTargets = perUserCounts.filter((r) => r.expr0 >= BRUTE_FORCE_PER_USER);
59
62
  const heavyTargets = bruteForceTargets.filter((r) => r.expr0 >= BULK_THRESHOLD_PER_USER);
@@ -105,6 +108,18 @@ export class FailedLoginCheck {
105
108
  ],
106
109
  });
107
110
  }
111
+ else if (totalFailures > 0 && bruteForceTargets.length === 0 && perUserUnavailable) {
112
+ findings.push({
113
+ id: 'failed-login-per-user-unavailable',
114
+ category: this.category,
115
+ riskLevel: 'INFO',
116
+ inconclusive: true,
117
+ title: `${totalFailures} failed login(s) in 7 days, but the per-account breakdown could not be read`,
118
+ detail: `${totalFailures} failed login attempts were recorded org-wide in the last 7 days. The per-username aggregation was not available, so whether any single account is under a brute-force attack could not be determined. The total alone does not distinguish widespread user error from a concentrated attack on one account.`,
119
+ remediation: 'Grant the audit user access to aggregate LoginHistory queries and re-run, or review Login History grouped by username manually in Setup.',
120
+ affectedItems: [{ label: 'Org-wide login activity', url: setupUrl, note: `${totalFailures} failures in 7 days` }],
121
+ });
122
+ }
108
123
  else if (totalFailures > 0 && bruteForceTargets.length === 0) {
109
124
  findings.push({
110
125
  id: 'failed-login-low-volume',
@@ -46,6 +46,7 @@ export class FieldLevelSecurityCheck {
46
46
  // - An API name string like 'Account' (standard objects) — use directly
47
47
  const sfIdPattern = /^[A-Za-z0-9]{15,18}$/;
48
48
  const objectApiNameById = new Map();
49
+ let entityLookupFailed = false;
49
50
  const customObjectIds = [];
50
51
  for (const field of sensitiveFields) {
51
52
  const teo = field.TableEnumOrId;
@@ -65,7 +66,9 @@ export class FieldLevelSecurityCheck {
65
66
  }
66
67
  }
67
68
  catch {
68
- // If entity lookup fails, custom object field names will be unresolvable
69
+ // Recorded, not swallowed: without these names the fields cannot be analysed, and a
70
+ // silent failure here previously surfaced as a clean pass.
71
+ entityLookupFailed = true;
69
72
  }
70
73
  }
71
74
  // Build field API names: {ObjectApiName}.{DeveloperName}__c
@@ -76,15 +79,18 @@ export class FieldLevelSecurityCheck {
76
79
  fieldApiNames.push(`${objectApiName}.${field.DeveloperName}__c`);
77
80
  }
78
81
  }
82
+ const unresolvedCount = sensitiveFields.length - fieldApiNames.length;
79
83
  if (fieldApiNames.length === 0) {
80
84
  findings.push({
81
- id: 'field-level-security-ok',
85
+ id: 'field-level-security-unresolved',
82
86
  category: this.category,
83
- riskLevel: 'LOW',
84
- passed: true,
85
- title: 'Sensitive custom fields appear appropriately restricted',
86
- detail: 'No sensitive custom fields with excessive permission set access were found.',
87
- remediation: 'Continue to apply restrictive field-level security to any new sensitive fields.',
87
+ riskLevel: 'INFO',
88
+ inconclusive: true,
89
+ title: `Field-level security could not be evaluated for ${sensitiveFields.length} sensitive field(s)`,
90
+ detail: `${sensitiveFields.length} sensitive custom field(s) were found, but their object API names could not be resolved` +
91
+ `${entityLookupFailed ? ' because the EntityDefinition lookup was not accessible' : ''}. ` +
92
+ 'Field-level security was therefore not evaluated for any of them. This is an incomplete result, not a clean one.',
93
+ remediation: 'Grant the audit user access to the Tooling API EntityDefinition object and re-run, then review field-level security on the reported fields.',
88
94
  });
89
95
  return { findings };
90
96
  }
@@ -98,13 +104,15 @@ export class FieldLevelSecurityCheck {
98
104
  }
99
105
  catch {
100
106
  findings.push({
101
- id: 'field-level-security-ok',
107
+ id: 'field-level-security-inaccessible',
102
108
  category: this.category,
103
- riskLevel: 'LOW',
104
- passed: true,
105
- title: 'Sensitive custom fields appear appropriately restricted',
106
- detail: 'No sensitive custom fields with excessive permission set access were found.',
107
- remediation: 'Continue to apply restrictive field-level security to any new sensitive fields.',
109
+ riskLevel: 'INFO',
110
+ inconclusive: true,
111
+ title: `Field-level security could not be evaluated for ${fieldApiNames.length} sensitive field(s)`,
112
+ detail: 'The FieldPermissions query was not accessible, so how widely these sensitive fields are readable could not be determined. ' +
113
+ 'The fields themselves were found; only their exposure is unknown.',
114
+ remediation: 'Grant the audit user access to FieldPermissions and re-run. Until then, review field-level security manually for the fields listed.',
115
+ affectedItems: fieldApiNames.map((f) => ({ label: f })),
108
116
  });
109
117
  return { findings };
110
118
  }
@@ -151,9 +159,14 @@ export class FieldLevelSecurityCheck {
151
159
  id: 'field-level-security-ok',
152
160
  category: this.category,
153
161
  riskLevel: 'LOW',
154
- passed: true,
155
- title: 'Sensitive custom fields appear appropriately restricted',
156
- detail: 'No sensitive custom fields with excessive permission set access were found.',
162
+ // A pass only where the analysis actually covered everything found.
163
+ ...(unresolvedCount > 0 ? { inconclusive: true } : { passed: true }),
164
+ title: unresolvedCount > 0
165
+ ? `Sensitive custom fields appear restricted, but ${unresolvedCount} could not be evaluated`
166
+ : 'Sensitive custom fields appear appropriately restricted',
167
+ detail: unresolvedCount > 0
168
+ ? `No excessive permission-set access was found among the ${fieldApiNames.length} field(s) that could be evaluated, but ${unresolvedCount} sensitive field(s) could not be resolved to an object and were not checked.`
169
+ : 'No sensitive custom fields with excessive permission set access were found.',
157
170
  remediation: 'Continue to apply restrictive field-level security to any new sensitive fields.',
158
171
  });
159
172
  }