@cclabsnz/sf-audit 1.25.0 → 1.26.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.
package/CHANGELOG.md CHANGED
@@ -9,6 +9,90 @@ published note and carries the signed provenance attestation and CycloneDX SBOM
9
9
 
10
10
  ## [Unreleased]
11
11
 
12
+ ## [v1.26.0](https://github.com/cclabsnz/sf-audit-plugin/releases/tag/v1.26.0) — 2026-11-11
13
+
14
+ Four checks read fields or values Salesforce does not have, or matched by wording, so they could
15
+ not report what they were for. They now read what the platform writes, confirmed against a
16
+ Developer Edition org. Grades can move either way: orgs that allow the OAuth Username-Password
17
+ Flow get a new HIGH finding and may fall; orgs lose a false HIGH guest finding and most
18
+ connected-app inactivity noise, and custom settings matches drop from HIGH to MEDIUM or LOW.
19
+
20
+ ### Changed
21
+
22
+ - **The custom settings check looks at fields, not object names.** It flagged any custom object
23
+ named with "Setting", "Config" or "Credential" whose name or description contained a word such
24
+ as "key", at HIGH, so most of its hits were not secrets. It now reads the fields of actual custom
25
+ settings and custom metadata types, and reports plain-text fields whose own name says they hold
26
+ a secret: password, passphrase, secret, token, credential, bearer, or a qualified key such as API,
27
+ private, client or signing key. Bare "key", names that only describe a secret (`Token_Endpoint`,
28
+ `Secret_Name`), and a Named Credential's name are not reported, nor are encrypted, number and
29
+ checkbox fields. Record values are still never read.
30
+ - `custom-settings-credentials` is MEDIUM and covers the org's own fields.
31
+ - Managed-package fields are reported apart as `custom-settings-credentials-managed`, LOW. It
32
+ feeds no attack chain, since whether the field is readable depends on the type's visibility,
33
+ which is not read.
34
+ - Ordinary custom objects are no longer reported for their names. Secrets in Apex and custom
35
+ labels are still covered by `hardcoded-credentials` and `custom-labels-credential`.
36
+ - A failed read is now inconclusive rather than an error. If custom metadata types cannot be
37
+ listed, custom settings are still read and the finding says so.
38
+
39
+ ### Fixed
40
+
41
+ - **The OAuth Username-Password Flow check reads the setting Salesforce has.** It read
42
+ `isDeviceFlowEnabled` and `isPasswordFlowEnabled` from OAuth and OpenID Connect Settings, which
43
+ has neither field, so every run ended in "verify manually". It now reads `blockOAuthUnPwFlow`,
44
+ confirmed against a Developer Edition org, and reports `oauth-password-flow-enabled` when the
45
+ flow is not blocked. Orgs that allow the flow will see the finding, and it feeds the
46
+ credential-theft chain, so some grades may fall. When the setting cannot be read, the advisory
47
+ is now marked inconclusive, so the check no longer counts as assessed.
48
+ - **The Device Flow finding is removed.** Device Flow is switched on per connected app, and neither
49
+ OauthOidcSettings nor ConnectedApp metadata carries it, so `oauth-device-flow-enabled` could
50
+ never fire. A waiver on that id now matches nothing and can be deleted. The check is renamed
51
+ OAuth Username-Password Flow; its id is unchanged, so waivers on the check still apply.
52
+ - **Infinite refresh tokens are read from the refresh token policy only.** The connected-app scope
53
+ check also flagged `oauthConfig.refreshTokenValidityPeriod = -1`, which is not a ConnectedApp
54
+ metadata field. `oauthPolicy.refreshTokenPolicy = infinite` is how the Metadata API states a
55
+ token valid until revoked, and it already raised the finding. Results do not change.
56
+ - **Inactive connected apps are found by real OAuth logins.** The check counted LoginHistory rows
57
+ with `LoginType LIKE 'OAuth%'`, and no LoginType starts with "OAuth": an OAuth login is recorded
58
+ as `Remote Access 2.0` or `Remote Access Client`, with the flow in `LoginSubType`. The filter
59
+ matched nothing, so every connected app was reported as having no OAuth logins in 90 days. It
60
+ now reads either field, so apps that sign in count as active and orgs will see far fewer
61
+ `connected-app-inactive` items. An app that only exchanges refresh tokens may still read as
62
+ inactive: whether that writes a LoginHistory row is not established, and
63
+ `oauth-token-inventory` covers standing tokens.
64
+ - **The inactive connected app remedy no longer leads with deleting the app.** It asks the owner
65
+ first, then revokes tokens and blocks the app in Connected Apps OAuth Usage, which can be
66
+ reversed. A delete cannot be undone, loses the consumer key and secret, and connected app
67
+ creation is restricted from Spring '26. The finding now says inactive apps *may* still hold
68
+ credentials.
69
+ - **The schema guard judges LIKE on picklists.** A LIKE pattern that fits no value of a picklist
70
+ fails the guard, as an unknown `=` or `IN` value already did. The deep-path guard now drives the
71
+ inactivity check to its LoginHistory read.
72
+ - **Secure guest user record access is reported as the platform guarantee it is.** Salesforce has
73
+ enforced it in every org since Winter '21: from API 50.0 `SharingSettings.enableSecureGuestAccess`
74
+ is always true, and the Release Update that carried it is gone. The check looked for a Release
75
+ Update whose title or description mentioned "guest" and "record access", which could only find a
76
+ different guest update. Depending on that update's status it reported a false pass, a false HIGH
77
+ `guest-record-access-policy-not-enforced` (which also fed the unauthenticated chains), or a LOW
78
+ "verify manually". It now passes for orgs with guest users and points to
79
+ `guest-object-exposure` and `guest-user-access`, which read guest-owned and guest-shared records
80
+ directly. `guest-record-access-policy-not-enforced`, `-verify-manually` and
81
+ `-tooling-inaccessible` are removed; waivers on them match nothing and can be deleted.
82
+
83
+ ## [v1.25.1](https://github.com/cclabsnz/sf-audit-plugin/releases/tag/v1.25.1) — 2026-11-11
84
+
85
+ Documentation only. No change to checks, scores or reports.
86
+
87
+ ### Changed
88
+
89
+ - **The README shows the report on its first screen**: a screenshot of a sample technical report,
90
+ linked to the full [technical](https://www.softwareinsights.dev/samples/sf-audit/sample-report.html)
91
+ and [executive](https://www.softwareinsights.dev/samples/sf-audit/sample-executive-report.html)
92
+ samples, and the install and run commands. The npm page shows the README as it was at publish,
93
+ so this release carries it there. (#206)
94
+ - The incident evidence-bundle spec is agreed, with resume and the staging sweep deferred. (#210)
95
+
12
96
  ## [v1.25.0](https://github.com/cclabsnz/sf-audit-plugin/releases/tag/v1.25.0) — 2026-11-10
13
97
 
14
98
  The technical HTML report is redesigned. It now uses the executive report's white consulting look
@@ -309,7 +393,6 @@ mean what they say. Found by running the audit against a Developer Edition org a
309
393
  - `scripts/capture-schema.mjs` and a captured Developer Edition schema
310
394
  (`test/fixtures/schema/developer-edition.json`, standard fields only). A test runs every
311
395
  check against it and fails on any query the org would reject.
312
- ||||||| a23c86e
313
396
 
314
397
  ## [v1.17.0](https://github.com/cclabsnz/sf-audit-plugin/releases/tag/v1.17.0) — 2026-10-17
315
398
 
package/README.md CHANGED
@@ -5,26 +5,35 @@
5
5
  # @cclabsnz/sf-audit
6
6
 
7
7
  [![CI](https://github.com/cclabsnz/sf-audit-plugin/actions/workflows/ci.yml/badge.svg)](https://github.com/cclabsnz/sf-audit-plugin/actions/workflows/ci.yml)
8
- [![CodeQL](https://github.com/cclabsnz/sf-audit-plugin/actions/workflows/codeql.yml/badge.svg)](https://github.com/cclabsnz/sf-audit-plugin/actions/workflows/codeql.yml)
9
- [![Semgrep](https://github.com/cclabsnz/sf-audit-plugin/actions/workflows/semgrep.yml/badge.svg)](https://github.com/cclabsnz/sf-audit-plugin/actions/workflows/semgrep.yml)
10
- [![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/cclabsnz/sf-audit-plugin/badge)](https://securityscorecards.dev/viewer/?uri=github.com/cclabsnz/sf-audit-plugin)
11
- [![OpenSSF Best Practices](https://www.bestpractices.dev/projects/14149/badge)](https://www.bestpractices.dev/projects/14149)
12
8
  [![npm version](https://img.shields.io/npm/v/@cclabsnz/sf-audit)](https://www.npmjs.com/package/@cclabsnz/sf-audit)
13
- [![npm provenance](https://img.shields.io/badge/npm-signed%20provenance-brightgreen)](https://www.npmjs.com/package/@cclabsnz/sf-audit#provenance)
9
+ [![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/cclabsnz/sf-audit-plugin/badge)](https://securityscorecards.dev/viewer/?uri=github.com/cclabsnz/sf-audit-plugin)
14
10
  [![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
15
11
 
16
- A Salesforce CLI (`sf`) plugin that runs a complete, **read-only** security audit against any Salesforce org, risk-scores it with an A–F grade, and turns the result into a report your security team (or your client's) can act on.
12
+ A read-only security audit for any Salesforce org, run from the Salesforce CLI (`sf`): 109 checks, an
13
+ A–F grade, and a report your security team (or your client's) can act on.
14
+
15
+ <a href="https://www.softwareinsights.dev/samples/sf-audit/sample-report.html"><img src="https://www.softwareinsights.dev/samples/sf-audit/sample-report.png" width="720" alt="sf-audit HTML report for a fictional org: grade F at 77 out of 100 and why, 42 open findings by severity, and user, code, integration and governance metrics" /></a>
17
16
 
18
- - **109 read-only checks** across identity, access, data (including Data Cloud and Shield), code, integrations (including inbound email handlers and package install handlers), monitoring, and Agentforce / GenAI. Apex findings say which control a class bypasses: record sharing, or CRUD/FLS
19
- - **Attack-chain correlation:** links individual findings into named, multi-step attack scenarios — nineteen modelled chains, plus an emergent pass for combinations nobody has named yet (see [Attack chains](#attack-chains))
20
- - **Compliance mapping:** every finding mapped to **source-verified** controls across 10 frameworks: 8 general baseline frameworks (OWASP Top 10, OWASP LLM Top 10, SOC 2, ISO/IEC 27001:2022, Security Benchmark for Salesforce, NZ Privacy Act 2020, HISO 10029, NZISM) plus 2 specialized jurisdictional packs (HIPAA Security Rule, GDPR)
21
- - **Outputs:** a technical `html` / `md` / `json` report, or a branded, client-ready **executive report** (print-to-PDF) with priorities, remediation roadmap, and a compliance coverage matrix
22
- - **History & diff:** archives each run and shows security-posture drift over time (skipped by default on CI runners, so they keep no org data)
23
- - **CI-ready:** `--format sarif` for GitHub code scanning, `--fail-on` to gate a pipeline, and [accepted-risk waivers](#accepting-a-risk) that expire
24
- - **Free event baseline:** `sf audit events pull` captures the org's free daily `EventLogFile` logs to local disk before the 1-day retention window drops them — no Event Monitoring / Shield add-on needed
25
- - **Connected-app least-privilege:** `sf audit apps` reads the `RestApi`, `BulkApi2`, `GraphQlQueryExecution` and `AuraRequest` EventLogFiles to see which objects each connected app actually uses, compares that against what its run-as user is granted (permission sets and profile), and reports the over-grant per object and read/write bit — plus a suggested least-privilege permission set, which `--emit-permset <dir>` writes as local `.permissionset-meta.xml` files (never deployed)
26
- - **Guest User Anomaly investigation:** `sf audit incident collect` saves the guest user's evidence for each anomaly wave, and `sf audit incident report` analyses it offline into a cited verdict: who it was, whether content came back, and whether anyone logged in ([walkthrough](https://www.softwareinsights.dev/posts/salesforce-guest-user-anomaly-investigation-sf-audit-incident/))
27
- - Strictly read-only (SOQL/Tooling/REST GETs + Metadata API reads); see [PERMISSIONS.md](PERMISSIONS.md) for the least-privilege access it needs
17
+ *A sample report from a fictional org, produced by the real checks against synthetic data. Open the
18
+ full [technical report](https://www.softwareinsights.dev/samples/sf-audit/sample-report.html) or the
19
+ [executive report](https://www.softwareinsights.dev/samples/sf-audit/sample-executive-report.html).*
20
+
21
+ ```bash
22
+ sf plugins install @cclabsnz/sf-audit # warns that it is unsigned: answer y (see Installation)
23
+ sf audit security --target-org <orgAlias>
24
+ ```
25
+
26
+ That writes an HTML report to the current directory. **Safe to run against production:** it only
27
+ uses SOQL, Tooling/REST GETs and Metadata API reads, and a test fails the build if a write call
28
+ appears in the source ([PERMISSIONS.md](PERMISSIONS.md), [Trust & verification](#trust--verification)).
29
+
30
+ - **Checks:** identity, access, data, guest exposure, integrations, code, monitoring and Agentforce. See [What It Checks](#what-it-checks)
31
+ - **Attack chains:** findings linked into multi-step attack scenarios: nineteen named chains, plus a pass for combinations nobody has named yet
32
+ - **Compliance:** every finding mapped to 10 frameworks, including SOC 2, ISO/IEC 27001, OWASP, NZISM, HIPAA and GDPR
33
+ - **CI:** `--format sarif` for GitHub code scanning, `--fail-on` to gate a pipeline, and expiring [risk waivers](#accepting-a-risk)
34
+
35
+ The plugin also has commands to capture the free daily event logs, check connected apps for least
36
+ privilege, and investigate guest-user anomalies. See [Other commands](#other-commands).
28
37
 
29
38
  ## Installation
30
39
 
@@ -133,7 +142,9 @@ Every flag, more examples, and what the executive report contains:
133
142
  ## What It Checks
134
143
 
135
144
  **109 read-only checks** across ten domains. Every finding is risk-rated CRITICAL → INFO, mapped to
136
- compliance controls, and correlated into [attack chains](#attack-chains).
145
+ compliance controls, and correlated into [attack chains](#attack-chains). Coverage includes Data
146
+ Cloud and Shield, inbound email handlers and package install handlers, and Apex findings say which
147
+ control a class bypasses: record sharing, or CRUD/FLS.
137
148
 
138
149
  | Domain | Checks |
139
150
  |--------|-------:|
@@ -194,7 +205,7 @@ All nineteen with severities and trigger conditions: **[docs/ATTACK-CHAINS.md](d
194
205
 
195
206
  ## Scope & Liability
196
207
 
197
- **What this tool is.** A read-only, point-in-time configuration review. Every check uses standard Salesforce SOQL, Tooling, and REST **GET** queries only: the tool performs no DML, no metadata deployments, and never modifies the target org or its data. It runs under the permissions of the authenticated `sf` user; checks that the user cannot access are reported as *inconclusive* rather than passing silently.
208
+ **What this tool is.** A read-only, point-in-time configuration review. Every check uses standard Salesforce SOQL, Tooling, and REST **GET** queries and Metadata API reads only: the tool performs no DML, no metadata deployments, and never modifies the target org or its data. It runs under the permissions of the authenticated `sf` user; checks that the user cannot access are reported as *inconclusive* rather than passing silently.
198
209
 
199
210
  **What this tool is not.** It is **not** a penetration test, a dynamic/runtime security test, or a source-code audit of managed-package internals. It does not exploit vulnerabilities, attempt privilege escalation, or guarantee detection of every misconfiguration. The Health Score and A–F grade are **prioritisation aids**, not certifications, and do not represent compliance with, or accreditation under, any standard (OWASP, SOC 2, ISO 27001, HIPAA, GDPR, or otherwise). Compliance-framework tags indicate *relevance* to a control area only.
200
211
 
@@ -210,6 +221,11 @@ All nineteen with severities and trigger conditions: **[docs/ATTACK-CHAINS.md](d
210
221
  Because this tool authenticates against production orgs, "is it safe to run?" deserves a verifiable
211
222
  answer rather than a claim. Every guarantee below is something you can check yourself:
212
223
 
224
+ [![CodeQL](https://github.com/cclabsnz/sf-audit-plugin/actions/workflows/codeql.yml/badge.svg)](https://github.com/cclabsnz/sf-audit-plugin/actions/workflows/codeql.yml)
225
+ [![Semgrep](https://github.com/cclabsnz/sf-audit-plugin/actions/workflows/semgrep.yml/badge.svg)](https://github.com/cclabsnz/sf-audit-plugin/actions/workflows/semgrep.yml)
226
+ [![OpenSSF Best Practices](https://www.bestpractices.dev/projects/14149/badge)](https://www.bestpractices.dev/projects/14149)
227
+ [![npm provenance](https://img.shields.io/badge/npm-signed%20provenance-brightgreen)](https://www.npmjs.com/package/@cclabsnz/sf-audit#provenance)
228
+
213
229
  - **Read-only, enforced in CI** — a test statically fails the build if any write path appears in the source
214
230
  - **No network egress** — enforced the same way; reports are fully self-contained (fonts and Chart.js inlined)
215
231
  - **Signed provenance** — released from CI via npm trusted publishing (OIDC); `npm audit signatures` verifies the tarball against the public commit
@@ -287,7 +303,7 @@ Beyond the audit itself, the plugin ships five commands. Each is documented in
287
303
  | `sf audit events pull` | Capture the org's **free** daily `EventLogFile` logs to local disk before the ~1-day retention window drops them — no Event Monitoring / Shield add-on needed. Idempotent, safe to cron |
288
304
  | `sf audit timeline` | Reconstruct one actor's activity across every captured event type, entirely offline. Refuses to expand a shared identity or join on a blank field, and always reports capture coverage first |
289
305
  | `sf audit preflight` | Read the running user's effective permissions in one query and report which checks will produce a verdict and which will return inconclusive — **before** an audit is run |
290
- | `sf audit apps` | Read the API event logs to compare what each connected app actually *uses* against what its run-as user is *granted*, and suggest a least-privilege permission set. `--emit-permset <dir>` writes it as local `.permissionset-meta.xml` files for review; nothing is deployed |
306
+ | `sf audit apps` | Read the `RestApi`, `BulkApi2`, `GraphQlQueryExecution` and `AuraRequest` event logs to compare what each connected app actually *uses* against what its run-as user is *granted*, per object and read/write, and suggest a least-privilege permission set. `--emit-permset <dir>` writes it as local `.permissionset-meta.xml` files for review; nothing is deployed |
291
307
 
292
308
  To triage captured logs for abuse patterns, pair `events pull` with the companion CLI
293
309
  **[sfelf-triage](https://github.com/cclabsnz/sfelf-triage)**, which reads this plugin's
@@ -297,11 +313,12 @@ To triage captured logs for abuse patterns, pair `events pull` with the companio
297
313
 
298
314
  `sf audit incident collect --target-org <alias>` finds Guest User Anomaly waves and saves a
299
315
  guest-filtered evidence bundle to `~/.sf/incidents/`. `sf audit incident report --bundle <dir>`
300
- analyses it offline and writes an HTML/Markdown/JSON report with evidence CSVs. Pass
316
+ analyses it offline into a cited verdict (who it was, whether content came back, and whether anyone
317
+ logged in) as an HTML/Markdown/JSON report with evidence CSVs. Pass
301
318
  `--ip-ranges` with provider range files you have downloaded to classify hosting; the plugin
302
319
  never fetches them. Use `--redact` before sharing beyond the client's security team. Bundles in
303
320
  `~/.sf/incidents` hold guest-traffic rows and linked-user details unencrypted, so handle them as
304
- sensitive data.
321
+ sensitive data. A worked example: [investigating a Guest User Anomaly with sf-audit](https://www.softwareinsights.dev/posts/salesforce-guest-user-anomaly-investigation-sf-audit-incident/).
305
322
 
306
323
  ## Requirements
307
324
 
@@ -106,10 +106,6 @@ export const CAPABILITY_REGISTRY = {
106
106
  'public-group-sharing-exposure': { grants: ['data-read-bulk'] },
107
107
  // Report folders any authenticated user can view.
108
108
  'report-folder-access-public': { grants: ['data-read'] },
109
- // "Secure guest user record access" not enforced: guest-owned records can defeat a Private OWD.
110
- // The policy gap widens guest visibility rather than creating the surface itself, so it mirrors
111
- // 'guest-user-sharing-exposure' rather than the confirmed bulk-read sinks.
112
- 'guest-record-access-policy-not-enforced': { grants: ['unauth-foothold', 'data-read'] },
113
109
  // Sensitive data present and readable — what every other capability is ultimately reaching for.
114
110
  'encryption-coverage-unencrypted-sensitive': { grants: ['data-read'], techniques: { 'data-read': [] } },
115
111
  'sandbox-data-masking-pii-present': { grants: ['data-read'] },
@@ -120,9 +116,10 @@ export const CAPABILITY_REGISTRY = {
120
116
  // unexercised permission is not a capability an attacker holds today.
121
117
  'integration-least-privilege-escalation-permissions': { grants: ['code-exec', 'priv-esc'], techniques: { 'priv-esc': ['T1098'] } },
122
118
  'integration-least-privilege-data-permissions': { grants: ['data-read-bulk'] },
123
- // Credentials in custom settings — the third place secrets hide, after hardcoded literals and
124
- // custom labels, both of which already grant here. A protected custom setting is readable by any
125
- // Apex running in system context, so the reach is the same.
119
+ // Credentials in the org's own custom setting or custom metadata fields: the third place secrets
120
+ // hide, after hardcoded literals and custom labels, both of which already grant here. Managed
121
+ // package fields ('custom-settings-credentials-managed') grant nothing: their reach depends on the
122
+ // type's visibility, which is not read.
126
123
  'custom-settings-credentials': { grants: ['credential-theft'] },
127
124
  // Apex reachable over REST, and Apex that skips CRUD/FLS. The registry already models the portal
128
125
  // (`portal-exposed-apex-without-sharing`) and Flow (`flows-*-without-sharing`) variants of the
@@ -178,7 +175,6 @@ export const CAPABILITY_REGISTRY = {
178
175
  'platform-event-subscriber-escalation': { grants: ['priv-esc', 'data-write'], techniques: { 'priv-esc': ['T1546'] } },
179
176
  'flow-http-callout-hardcoded-secret': { grants: ['credential-theft', 'external-egress'] },
180
177
  'flow-http-callout-uncredentialed-endpoint': { grants: ['external-egress'] },
181
- 'oauth-device-flow-enabled': { grants: ['credential-theft'], techniques: { 'credential-theft': ['T1528'] } },
182
178
  'oauth-password-flow-enabled': { grants: ['credential-theft'], techniques: { 'credential-theft': ['T1110.003'] } },
183
179
  'delegated-authentication-admin-assigned': { grants: ['org-takeover'], techniques: { 'org-takeover': ['T1556.007'] } },
184
180
  'delegated-authentication-insecure-gateway': { grants: ['org-takeover'], techniques: { 'org-takeover': ['T1556.007'] } },
@@ -30,7 +30,6 @@ export const GUEST_EXPOSURE = [
30
30
  // Not 'guest-site-options-member-visibility': a site's member list is no foothold into org data,
31
31
  // and this list also gates the low-trust chains (LOW_TRUST_ENTRY).
32
32
  'guest-user-visibility-view-all-users',
33
- 'guest-record-access-policy-not-enforced',
34
33
  'inbound-email-handler-unauthenticated-execution',
35
34
  ];
36
35
  // Ways in for a low-trust principal: external users with public sharing, social sign-on,
@@ -61,8 +60,6 @@ export const UNAUTH_EXFIL_STEPS = [
61
60
  // @AuraEnabled class or any Flow, which a logged-in user may be the only one able to call. The
62
61
  // guest-side counterpart is 'guest-executable-apex-*', read from the guest profile's class access.
63
62
  'field-level-security-high', 'field-level-security-medium',
64
- // The guardrail whose absence lets guest-owned records defeat a Private OWD.
65
- 'guest-record-access-policy-not-enforced',
66
63
  // An open inbound email handler grants unauth-foothold, so it must appear whenever it
67
64
  // is what opened the gate.
68
65
  'inbound-email-handler-unauthenticated-execution',
@@ -78,9 +75,6 @@ export const UNAUTH_RECORD_REACH = [
78
75
  // Not 'guest-site-options-member-visibility': it shows a site's members, not business records.
79
76
  'guest-user-visibility-view-all-users',
80
77
  'guest-executable-apex-unprotected',
81
- // Secure guest record access is what makes the rest of this list necessary: with it off, legacy
82
- // sharing and guest ownership reach records directly.
83
- 'guest-record-access-policy-not-enforced',
84
78
  ];
85
79
  // What a guest-side step must grant for the visitor to reach data or run code.
86
80
  const UNAUTH_EXFIL_REACH = ['code-exec', 'data-read-bulk', 'data-write'];
@@ -107,7 +101,7 @@ export const TAKEOVER_ADMIN_EVIDENCE = [
107
101
  // Exposed secrets: every finding here that grants credential-theft.
108
102
  export const EXPOSED_SECRETS = [
109
103
  'hardcoded-credentials-found', 'custom-labels-credential-value-match', 'custom-labels-credential-name-match',
110
- 'flow-http-callout-hardcoded-secret', 'oauth-device-flow-enabled', 'oauth-password-flow-enabled',
104
+ 'flow-http-callout-hardcoded-secret', 'oauth-password-flow-enabled',
111
105
  'custom-settings-credentials',
112
106
  ];
113
107
  export const EGRESS_PATHS = [
@@ -333,7 +327,7 @@ export const NAMED_CHAINS = [
333
327
  'from it. This is not a theoretical exposure — it is reconnaissance against a confirmed ' +
334
328
  'exfiltration surface, i.e. an incident likely already in progress.',
335
329
  remediation: 'Treat as an active incident: block the source IPs at the WAF/CDN, close the guest bulk-read surface ' +
336
- '(set external OWD to Private, strip guest object read, enforce "Secure guest user record access"), ' +
330
+ '(remove guest sharing rules and guest object read, reassign guest-owned records), ' +
337
331
  'and preserve/forward the event logs before the short EventLogFile retention window closes.',
338
332
  abuseCase: {
339
333
  actor: 'an unauthenticated visitor already probing the site',
@@ -22,13 +22,18 @@ export class ConnectedAppInactivityCheck {
22
22
  return { findings };
23
23
  }
24
24
  // Query OAuth login history for the last 90 days, grouped by application name.
25
- // Apps NOT appearing in this result have had zero OAuth logins in 90 days.
25
+ // Apps NOT appearing in this result have had zero OAuth logins in 90 days. LoginHistory records
26
+ // an OAuth login as LoginType 'Remote Access 2.0' (or 'Remote Access Client'), and the flow in
27
+ // LoginSubType ('OAuth Web Server', 'OAuth JWT Bearer', ...). No LoginType starts with 'OAuth',
28
+ // so filtering on that found no logins and called every app inactive. Whether a refresh token
29
+ // exchange writes a row is not established, so an app using only refresh tokens may still read
30
+ // as inactive; oauth-token-inventory covers standing tokens.
26
31
  let activeAppNames = new Set();
27
32
  try {
28
33
  const result = await ctx.soql.query(`SELECT Application, COUNT(Id) loginCount
29
34
  FROM LoginHistory
30
35
  WHERE LoginTime > LAST_N_DAYS:90
31
- AND LoginType LIKE 'OAuth%'
36
+ AND (LoginType IN ('Remote Access 2.0', 'Remote Access Client') OR LoginSubType LIKE 'OAuth%')
32
37
  GROUP BY Application`);
33
38
  for (const r of result.records) {
34
39
  if (r.Application)
@@ -56,12 +61,12 @@ export class ConnectedAppInactivityCheck {
56
61
  category: this.category,
57
62
  riskLevel: inactiveApps.length > 5 ? 'MEDIUM' : 'LOW',
58
63
  title: `${inactiveApps.length} connected app(s) have had no OAuth logins in 90 days`,
59
- detail: `${inactiveApps.length} of ${connectedAppNames.length} connected apps show no OAuth login activity in the past 90 days. Inactive apps still hold valid OAuth credentials and expand the attack surface. A compromised or leaked client secret for an inactive app can be used to obtain access tokens without triggering activity alerts.`,
60
- remediation: 'Review each inactive connected app. If the integration is no longer in use, delete or disable the app to revoke its OAuth credentials. Ensure active integrations are documented with an owner.',
64
+ detail: `${inactiveApps.length} of ${connectedAppNames.length} connected apps show no OAuth login activity in the past 90 days. Inactive apps may still hold valid OAuth credentials and expand the attack surface. A compromised or leaked client secret for an inactive app can be used to obtain access tokens without triggering activity alerts.`,
65
+ remediation: "Confirm with the app's owner whether the integration is still needed. If it is not, open Setup → Connected Apps OAuth Usage, revoke the tokens it still holds, and Block the app, which stops it being used and can be reversed. Delete it only once you are sure: a delete cannot be undone, the consumer key and secret are lost with it, and connected app creation is restricted from Spring '26 (Salesforce Support only).",
61
66
  affectedItems: inactiveApps.map((name) => ({
62
67
  label: name,
63
68
  url: setupUrl,
64
- note: 'No OAuth logins in 90 days: verify if still needed and delete if not',
69
+ note: 'No OAuth logins in 90 days: confirm it is still needed',
65
70
  })),
66
71
  });
67
72
  }
@@ -11,13 +11,11 @@ function normalise(meta) {
11
11
  }
12
12
  // Scopes that grant effectively unlimited access as the authorising user.
13
13
  const OVERLY_BROAD_SCOPES = new Set(['Full', 'full']);
14
- // Refresh token policy values that indicate no expiry.
15
- // refreshTokenValidityPeriod = -1 means "use org default" (often hours or longer).
16
- // oauthPolicy.refreshTokenPolicy = 'infinite' means no expiry at all.
14
+ // oauthPolicy.refreshTokenPolicy is where ConnectedApp metadata states a refresh token's lifetime:
15
+ // 'infinite', 'zero', or 'specific_lifetime' / 'specific_inactivity' with a duration. 'infinite'
16
+ // means the token is valid until revoked.
17
17
  function isInfiniteRefreshToken(app) {
18
- const validityPeriod = app.Metadata?.oauthConfig?.refreshTokenValidityPeriod;
19
- const policy = app.Metadata?.oauthPolicy?.refreshTokenPolicy;
20
- return validityPeriod === -1 || policy === 'infinite';
18
+ return app.Metadata?.oauthPolicy?.refreshTokenPolicy === 'infinite';
21
19
  }
22
20
  export class ConnectedAppScopeCheck {
23
21
  id = 'connected-app-scope';
@@ -137,12 +135,12 @@ export class ConnectedAppScopeCheck {
137
135
  category: this.category,
138
136
  riskLevel: 'MEDIUM',
139
137
  title: `${infiniteOnlyApps.length} connected app(s) issue refresh tokens with no expiry`,
140
- detail: 'Connected apps with an infinite or org-default refresh token policy (refreshTokenValidityPeriod = -1 or policy = "infinite") issue tokens that never expire unless manually revoked. A stolen refresh token provides indefinite access to the org as the authorising user. SBS-DEP-006 requires access token lifetimes of 15 minutes or less; refresh token lifetimes should also be bounded.',
138
+ detail: 'Connected apps with the refresh token policy "valid until revoked" (refreshTokenPolicy = infinite) issue tokens that never expire unless manually revoked. A stolen refresh token provides indefinite access to the org as the authorising user. SBS-DEP-006 requires access token lifetimes of 15 minutes or less; refresh token lifetimes should also be bounded.',
141
139
  remediation: 'Set an explicit refresh token validity period in Setup → Connected Apps → OAuth Policies. For machine-to-machine integrations, consider using the Client Credentials flow (which does not issue refresh tokens) instead of the Authorization Code flow. For user-facing apps, a 90-day refresh token limit is a reasonable starting point.',
142
140
  affectedItems: infiniteOnlyApps.map((app) => ({
143
141
  label: app.Name,
144
142
  url: setupUrl,
145
- note: `RefreshTokenPolicy: ${app.Metadata?.oauthPolicy?.refreshTokenPolicy ?? 'unset'}, ValidityPeriod: ${app.Metadata?.oauthConfig?.refreshTokenValidityPeriod ?? 'unset'}`,
143
+ note: `RefreshTokenPolicy: ${app.Metadata?.oauthPolicy?.refreshTokenPolicy ?? 'unset'}`,
146
144
  })),
147
145
  });
148
146
  }
@@ -1,10 +1,23 @@
1
1
  import type { AuditContext } from '@cclabsnz/sf-core';
2
2
  import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ /** Whether a field's own name (no namespace, no __c) says it holds a secret. */
4
+ export declare function namesSecret(qualifiedApiName: string): boolean;
5
+ /**
6
+ * Secrets stored in custom settings or custom metadata types. Their records are readable through
7
+ * the API and Apex by users with access to the type, so a password or token kept there is exposed
8
+ * in a way a Named Credential's secret is not.
9
+ *
10
+ * Evidence is the field, not the type's name: a text field on a custom setting or custom metadata
11
+ * type whose name says it holds a password, secret, token or key. The record values are never read,
12
+ * so a match is a field to review, not a secret found. Managed-package components are listed apart:
13
+ * a protected one is not readable from this org, and only the vendor can change it.
14
+ */
3
15
  export declare class CustomSettingsCheck implements SecurityCheck {
4
16
  readonly id = "custom-settings";
5
17
  readonly name = "Custom Settings and Credentials";
6
18
  readonly category = "Code Security";
7
- readonly description = "Flags custom settings with credential-like names that may store secrets";
19
+ readonly description = "Flags text fields on custom settings and custom metadata types whose names say they hold a password, secret, token or key";
8
20
  run(ctx: AuditContext): Promise<CheckResult>;
21
+ private inconclusive;
9
22
  }
10
23
  //# sourceMappingURL=CustomSettingsCheck.d.ts.map
@@ -1,60 +1,143 @@
1
- const SENSITIVE_KEYWORDS = [
2
- 'password',
3
- 'secret',
4
- 'token',
5
- 'key',
6
- 'credential',
7
- 'api_key',
8
- 'apikey',
9
- ];
1
+ // Words in a field name that say the value is a secret. Bare "key" counts only after a qualifier
2
+ // (api, private, access, client, signing, secret, encryption): alone it names prefixes, record keys
3
+ // and flags far more often than credentials.
4
+ const SECRET_WORDS = new Set(['password', 'passwd', 'pwd', 'passphrase', 'secret', 'token', 'apikey', 'privatekey', 'accesskey', 'credential', 'credentials', 'bearer']);
5
+ const KEY_QUALIFIERS = new Set(['api', 'private', 'access', 'client', 'signing', 'secret', 'encryption']);
6
+ // A name ending in one of these describes a secret (where it lives, what it is called), not the secret.
7
+ const DESCRIBES_ONLY = new Set(['endpoint', 'url', 'uri', 'name', 'label', 'type', 'count', 'length', 'date', 'expiry', 'expiration', 'id']);
8
+ /** Whether a field's own name (no namespace, no __c) says it holds a secret. */
9
+ export function namesSecret(qualifiedApiName) {
10
+ const base = qualifiedApiName.replace(/^[A-Za-z0-9]+__(?=.+__c$)/, '').replace(/__c$/, '');
11
+ const words = base.split(/_+|(?<=[a-z0-9])(?=[A-Z])/).map((w) => w.toLowerCase()).filter(Boolean);
12
+ if (words.length === 0 || DESCRIBES_ONLY.has(words[words.length - 1]))
13
+ return false;
14
+ // The name of a Named Credential is the recommended thing to store, not a secret.
15
+ if (words.some((w, i) => w === 'named' && words[i + 1]?.startsWith('credential')) || words.includes('namedcredential'))
16
+ return false;
17
+ return words.some((w, i) => SECRET_WORDS.has(w) || (w === 'key' && i > 0 && KEY_QUALIFIERS.has(words[i - 1])));
18
+ }
19
+ /** Plain or long text: a value someone could paste a secret into. Encrypted text is not plain. */
20
+ function isPlainText(dataType) {
21
+ return dataType != null && /text/i.test(dataType) && !/encrypt/i.test(dataType);
22
+ }
23
+ // FieldDefinition is read for a set of entities per query, this many at a time.
24
+ const FIELD_BATCH = 50;
25
+ /**
26
+ * Secrets stored in custom settings or custom metadata types. Their records are readable through
27
+ * the API and Apex by users with access to the type, so a password or token kept there is exposed
28
+ * in a way a Named Credential's secret is not.
29
+ *
30
+ * Evidence is the field, not the type's name: a text field on a custom setting or custom metadata
31
+ * type whose name says it holds a password, secret, token or key. The record values are never read,
32
+ * so a match is a field to review, not a secret found. Managed-package components are listed apart:
33
+ * a protected one is not readable from this org, and only the vendor can change it.
34
+ */
10
35
  export class CustomSettingsCheck {
11
36
  id = 'custom-settings';
12
37
  name = 'Custom Settings and Credentials';
13
38
  category = 'Code Security';
14
- description = 'Flags custom settings with credential-like names that may store secrets';
39
+ description = 'Flags text fields on custom settings and custom metadata types whose names say they hold a password, secret, token or key';
15
40
  async run(ctx) {
16
41
  const findings = [];
17
42
  const baseUrl = ctx.orgInfo.instanceUrl;
18
- const customObjects = await ctx.tooling.query(`
19
- SELECT Id, DeveloperName, Description FROM CustomObject
20
- WHERE DeveloperName LIKE '%Setting%'
21
- OR DeveloperName LIKE '%Config%'
22
- OR DeveloperName LIKE '%Credential%'
23
- `);
24
- // Filter for matches with sensitive keywords
25
- const matches = customObjects.filter((obj) => {
26
- const devName = (obj.DeveloperName || '').toLowerCase();
27
- const desc = (obj.Description || '').toLowerCase();
28
- const combined = `${devName} ${desc}`;
29
- return SENSITIVE_KEYWORDS.some((keyword) => combined.includes(keyword));
30
- });
31
- if (matches.length > 0) {
43
+ let settings;
44
+ try {
45
+ settings = await ctx.tooling.query('SELECT QualifiedApiName, NamespacePrefix FROM EntityDefinition WHERE IsCustomSetting = true');
46
+ }
47
+ catch (err) {
48
+ findings.push(this.inconclusive('Custom settings could not be listed', err));
49
+ return { findings };
50
+ }
51
+ // Custom metadata types are read separately: a failure here still leaves custom settings read.
52
+ let mdt = [];
53
+ let mdtError = null;
54
+ try {
55
+ const rows = await ctx.tooling.query("SELECT QualifiedApiName, NamespacePrefix FROM EntityDefinition WHERE QualifiedApiName LIKE '%__mdt'");
56
+ // '_' is a LIKE wildcard, so confirm the suffix.
57
+ mdt = rows.filter((r) => r.QualifiedApiName.endsWith('__mdt'));
58
+ }
59
+ catch (err) {
60
+ mdtError = err instanceof Error ? err.message : String(err);
61
+ }
62
+ const entities = [...settings, ...mdt];
63
+ let fields = [];
64
+ try {
65
+ for (let i = 0; i < entities.length; i += FIELD_BATCH) {
66
+ const names = entities.slice(i, i + FIELD_BATCH).map((e) => `'${e.QualifiedApiName}'`).join(', ');
67
+ fields.push(...(await ctx.tooling.query(`SELECT EntityDefinition.QualifiedApiName, QualifiedApiName, DataType, NamespacePrefix FROM FieldDefinition WHERE EntityDefinition.QualifiedApiName IN (${names})`)));
68
+ }
69
+ }
70
+ catch (err) {
71
+ findings.push(this.inconclusive('Custom setting and custom metadata fields could not be read', err));
72
+ return { findings };
73
+ }
74
+ // A field is the vendor's when the field itself carries a namespace; an org's own field on a
75
+ // managed type is the org's to fix.
76
+ const managed = (f) => Boolean(f.NamespacePrefix);
77
+ const isMdt = (obj) => obj.endsWith('__mdt');
78
+ const matches = fields.filter((f) => f.EntityDefinition?.QualifiedApiName && namesSecret(f.QualifiedApiName) && isPlainText(f.DataType));
79
+ const mdtNote = mdtError ? ` Custom metadata types could not be listed (${mdtError}), so only custom settings were read.` : '';
80
+ const scope = `${settings.length} custom setting(s) and ${mdt.length} custom metadata type(s)`;
81
+ const item = (f) => {
82
+ const obj = f.EntityDefinition.QualifiedApiName;
83
+ return {
84
+ label: `${obj}.${f.QualifiedApiName}`,
85
+ url: `${baseUrl}/lightning/setup/${isMdt(obj) ? 'CustomMetadata' : 'CustomSettings'}/home`,
86
+ note: managed(f)
87
+ ? `${f.DataType}; managed package: ask the vendor whether the type is protected and how the secret is stored`
88
+ : `${f.DataType}; check whether records hold a secret`,
89
+ };
90
+ };
91
+ const own = matches.filter((f) => !managed(f));
92
+ const vendor = matches.filter(managed);
93
+ if (own.length > 0) {
32
94
  findings.push({
33
95
  id: 'custom-settings-credentials',
34
96
  category: this.category,
35
- riskLevel: 'HIGH',
36
- title: `${matches.length} custom object(s) may store sensitive credentials`,
37
- detail: 'Custom objects named with credential-related terms may be storing API keys, passwords, or other secrets in plaintext Salesforce records.',
38
- remediation: 'Replace credential storage in custom objects with Named Credentials or a dedicated secrets management solution.',
39
- affectedItems: matches.map((obj) => ({
40
- label: `${obj.DeveloperName}__c`,
41
- url: `${baseUrl}/lightning/setup/ObjectManager/${obj.DeveloperName}__c/Details/view`,
42
- note: 'Review records for stored secrets and migrate to Named Credentials',
43
- })),
97
+ riskLevel: 'MEDIUM',
98
+ title: `${own.length} custom setting or custom metadata field(s) are named for a password, secret, token or key`,
99
+ detail: `These plain-text fields on ${scope} are named as if they hold a secret. Their records can be read through the API by users with access to the type, so a secret stored there is exposed. Field values were not read: confirm what each holds.${mdtNote}`,
100
+ remediation: 'For each field, check whether its records hold a live secret. Move any that do to a Named Credential with an External Credential, rotate the secret, and clear the field.',
101
+ affectedItems: own.map(item),
44
102
  });
45
103
  }
46
- else {
104
+ // A vendor's field is reported apart and feeds no attack chain: whether it is readable depends
105
+ // on the type's visibility, which this check does not read, and only the vendor can change it.
106
+ if (vendor.length > 0) {
107
+ findings.push({
108
+ id: 'custom-settings-credentials-managed',
109
+ category: this.category,
110
+ riskLevel: 'LOW',
111
+ title: `${vendor.length} managed package field(s) on custom settings or custom metadata are named for a secret`,
112
+ detail: `These plain-text fields belong to installed packages and are named as if they hold a secret. A protected type is not readable from this org; a public one is. Field values were not read.${mdtNote}`,
113
+ remediation: 'Ask each vendor whether the type is protected and how the secret is stored and rotated.',
114
+ affectedItems: vendor.map(item),
115
+ });
116
+ }
117
+ if (matches.length === 0) {
47
118
  findings.push({
48
119
  id: 'custom-settings-clean',
49
120
  category: this.category,
50
121
  riskLevel: 'LOW',
51
122
  passed: true,
52
- title: 'No obviously credential-related custom objects detected',
53
- detail: 'No custom objects with credential-related naming patterns were found.',
54
- remediation: 'Continue to avoid storing secrets in custom objects or custom settings. Use Named Credentials for external authentication.',
123
+ title: 'No custom setting or custom metadata field is named for a secret',
124
+ detail: `Read the fields of ${scope}; no plain-text field is named for a password, secret, token or key. Field values were not read.${mdtNote}`,
125
+ remediation: 'Keep secrets in Named Credentials and External Credentials, not in custom settings or custom metadata.',
55
126
  });
56
127
  }
57
128
  return { findings };
58
129
  }
130
+ inconclusive(what, err) {
131
+ const msg = err instanceof Error ? err.message : String(err);
132
+ return {
133
+ id: 'custom-settings-inconclusive',
134
+ category: this.category,
135
+ riskLevel: 'INFO',
136
+ inconclusive: true,
137
+ title: what,
138
+ detail: `The audit user could not read custom setting or custom metadata definitions. The org returned: ${msg}`,
139
+ remediation: 'If the error is an access error, grant the audit user View Setup and Configuration (see PERMISSIONS.md) and re-run. Otherwise the area is unassessed, not clean.',
140
+ };
141
+ }
59
142
  }
60
143
  //# sourceMappingURL=CustomSettingsCheck.js.map
@@ -1,33 +1,24 @@
1
1
  import type { AuditContext } from '@cclabsnz/sf-core';
2
2
  import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
3
  /**
4
- * Verifies the PREVENTIVE guardrail that stops the guest-ownership-defeats-OWD
5
- * exfiltration vector: "Secure guest user record access".
4
+ * The PREVENTIVE guardrail that stops guest-owned records defeating a Private OWD: "Secure guest
5
+ * user record access". With it, guests reach records only through guest user sharing rules.
6
6
  *
7
- * This is the policy complement to GuestObjectExposureCheck (which detects the
8
- * SYMPTOM — guest-owned records readable under a Private OWD). Once "Secure guest
9
- * user record access" is enforced, guests can no longer be granted record access
10
- * except via explicit guest user sharing rules, and — paired with "Assign new
11
- * records created by guest users to the default owner" — guests stop OWNING the
12
- * records they submit, which is what otherwise nullifies a Private OWD for
13
- * guest-submitted records (an owner can always read its own records).
7
+ * Salesforce has enforced it in every org since Winter '21. From API 50.0,
8
+ * SharingSettings.enableSecureGuestAccess is always true and setting it has no effect, and the
9
+ * Release Update that once carried it is no longer served. So there is no state to read: this
10
+ * check states the platform guarantee for orgs with guest users. It once matched a Release Update
11
+ * by its wording ("guest" plus "record access"), which could only pick up a different guest update.
14
12
  *
15
- * The enforcement ships as a Salesforce Release Update ("Secure guest user record
16
- * access", api-visible as a CriticalUpdate). This check reads that update's
17
- * activation state via the Tooling API and grades:
18
- * - update present & IsEnabled = false => HIGH: guardrail available, NOT activated.
19
- * - update present & IsEnabled = true => pass: guardrail enforced.
20
- * - update absent (older orgs where it was auto-activated long ago, or not
21
- * surfaced) => LOW advisory: confirm the Sharing
22
- * Settings checkboxes manually, since the API no longer exposes the toggle.
23
- * Degrades to inconclusive if guest users or the Tooling API cannot be read.
13
+ * The residual risk is the symptom, not the policy: records a guest already owns, or shares a
14
+ * guest sharing rule grants. GuestObjectExposureCheck and GuestUserAccessCheck read those directly.
15
+ * Degrades to inconclusive if guest users cannot be read.
24
16
  */
25
17
  export declare class GuestRecordAccessPolicyCheck implements SecurityCheck {
26
18
  readonly id = "guest-record-access-policy";
27
19
  readonly name = "Secure Guest User Record Access";
28
20
  readonly category = "Access Control";
29
- readonly description = "Verifies the \"Secure guest user record access\" enforcement is activated, the guardrail that stops guest-owned records defeating a Private org-wide default";
30
- private matchesSecureGuestAccess;
21
+ readonly description = "Confirms the platform enforces \"Secure guest user record access\" for orgs with guest users, the guardrail that stops guest-owned records defeating a Private org-wide default";
31
22
  run(ctx: AuditContext): Promise<CheckResult>;
32
23
  private inconclusive;
33
24
  }
@@ -1,52 +1,22 @@
1
- import { fieldsOf } from '../support/schema.js';
2
1
  /**
3
- * Whether a Tooling ReleaseUpdate status means the update is enabled. Invoked and Revocable
4
- * (enabled, can still be reverted) are on; Invocable (available) and Revoked are off; any other
5
- * status is unknown.
6
- */
7
- function releaseUpdateEnabled(status) {
8
- if (status === 'Invoked' || status === 'Revocable')
9
- return true;
10
- if (status === 'Invocable' || status === 'Revoked')
11
- return false;
12
- return null;
13
- }
14
- /**
15
- * Verifies the PREVENTIVE guardrail that stops the guest-ownership-defeats-OWD
16
- * exfiltration vector: "Secure guest user record access".
2
+ * The PREVENTIVE guardrail that stops guest-owned records defeating a Private OWD: "Secure guest
3
+ * user record access". With it, guests reach records only through guest user sharing rules.
17
4
  *
18
- * This is the policy complement to GuestObjectExposureCheck (which detects the
19
- * SYMPTOM — guest-owned records readable under a Private OWD). Once "Secure guest
20
- * user record access" is enforced, guests can no longer be granted record access
21
- * except via explicit guest user sharing rules, and — paired with "Assign new
22
- * records created by guest users to the default owner" — guests stop OWNING the
23
- * records they submit, which is what otherwise nullifies a Private OWD for
24
- * guest-submitted records (an owner can always read its own records).
5
+ * Salesforce has enforced it in every org since Winter '21. From API 50.0,
6
+ * SharingSettings.enableSecureGuestAccess is always true and setting it has no effect, and the
7
+ * Release Update that once carried it is no longer served. So there is no state to read: this
8
+ * check states the platform guarantee for orgs with guest users. It once matched a Release Update
9
+ * by its wording ("guest" plus "record access"), which could only pick up a different guest update.
25
10
  *
26
- * The enforcement ships as a Salesforce Release Update ("Secure guest user record
27
- * access", api-visible as a CriticalUpdate). This check reads that update's
28
- * activation state via the Tooling API and grades:
29
- * - update present & IsEnabled = false => HIGH: guardrail available, NOT activated.
30
- * - update present & IsEnabled = true => pass: guardrail enforced.
31
- * - update absent (older orgs where it was auto-activated long ago, or not
32
- * surfaced) => LOW advisory: confirm the Sharing
33
- * Settings checkboxes manually, since the API no longer exposes the toggle.
34
- * Degrades to inconclusive if guest users or the Tooling API cannot be read.
11
+ * The residual risk is the symptom, not the policy: records a guest already owns, or shares a
12
+ * guest sharing rule grants. GuestObjectExposureCheck and GuestUserAccessCheck read those directly.
13
+ * Degrades to inconclusive if guest users cannot be read.
35
14
  */
36
15
  export class GuestRecordAccessPolicyCheck {
37
16
  id = 'guest-record-access-policy';
38
17
  name = 'Secure Guest User Record Access';
39
18
  category = 'Access Control';
40
- description = 'Verifies the "Secure guest user record access" enforcement is activated, the guardrail that stops guest-owned records defeating a Private org-wide default';
41
- // Matches the release update / sharing setting regardless of the exact label
42
- // Salesforce uses across versions: the name/description mentions guests AND
43
- // record access.
44
- matchesSecureGuestAccess(u) {
45
- const hay = `${u.Name} ${u.Description ?? ''}`.toLowerCase();
46
- const guest = hay.includes('guest');
47
- const record = hay.includes('record access') || hay.includes('record-level') || hay.includes("access to records") || hay.includes('securely access');
48
- return guest && record;
49
- }
19
+ description = 'Confirms the platform enforces "Secure guest user record access" for orgs with guest users, the guardrail that stops guest-owned records defeating a Private org-wide default';
50
20
  async run(ctx) {
51
21
  const findings = [];
52
22
  const setupUrl = `${ctx.orgInfo.instanceUrl}/lightning/setup/SecuritySharing/page`;
@@ -66,82 +36,19 @@ export class GuestRecordAccessPolicyCheck {
66
36
  passed: true,
67
37
  title: 'No active guest users',
68
38
  detail: 'There are no active guest users, so guest record-access enforcement has no attack surface to protect.',
69
- remediation: 'If an Experience Cloud or Sites site is added later, ensure "Secure guest user record access" is enforced before going live.',
70
- });
71
- return { findings };
72
- }
73
- let updates;
74
- try {
75
- // Current orgs serve Release Updates as Tooling ReleaseUpdate (Status 'Invocable' = available
76
- // but not enabled); CriticalUpdate is the older object. Read whichever this org serves.
77
- if (await fieldsOf(ctx, 'ReleaseUpdate', 'tooling')) {
78
- const rows = await ctx.tooling.query('SELECT Id, DeveloperName, Title, Description, Status FROM ReleaseUpdate');
79
- updates = rows.map((r) => ({
80
- Id: r.Id,
81
- Name: r.Title ?? r.DeveloperName,
82
- Description: r.Description,
83
- IsEnabled: releaseUpdateEnabled(r.Status),
84
- }));
85
- }
86
- else {
87
- updates = await ctx.tooling.query('SELECT Id, Name, Description, IsEnabled FROM CriticalUpdate');
88
- }
89
- }
90
- catch (err) {
91
- findings.push(this.inconclusive('guest-record-access-policy-tooling-inaccessible', 'Release updates could not be queried', err));
92
- return { findings };
93
- }
94
- const match = updates.find((u) => this.matchesSecureGuestAccess(u));
95
- if (match && match.IsEnabled === false) {
96
- findings.push({
97
- id: 'guest-record-access-policy-not-enforced',
98
- category: this.category,
99
- riskLevel: 'HIGH',
100
- title: `"Secure guest user record access" is available but NOT activated (${guests.length} active guest user(s))`,
101
- detail: 'The "Secure guest user record access" Release Update is present but not enabled. Until it is activated, guest users can be granted record access through legacy sharing mechanisms and can own the records they submit via public forms. Because an owner can always read its own records, a Private org-wide default does not protect guest-owned records — this is the exact vector that turns a public submission form into an unauthenticated bulk-read surface.',
102
- remediation: 'Activate "Secure guest user record access" in Setup → Release Updates, and enable "Assign new records created by guest users to the default owner" in Setup → Sharing Settings. Reparent existing guest-owned records to an internal default/integration owner. After enforcement, grant guest read access only through explicit, minimal guest user sharing rules.',
103
- affectedItems: [{ label: match.Name, url: `${ctx.orgInfo.instanceUrl}/lightning/setup/ReleaseUpdates/home`, note: 'Release Update present, IsEnabled = false' }],
104
- });
105
- return { findings };
106
- }
107
- if (match && match.IsEnabled === true) {
108
- findings.push({
109
- id: 'guest-record-access-policy-enforced',
110
- category: this.category,
111
- riskLevel: 'LOW',
112
- passed: true,
113
- title: '"Secure guest user record access" is enforced',
114
- detail: 'The "Secure guest user record access" Release Update is enabled, so guests cannot be granted record access except through explicit guest user sharing rules. Verify "Assign new records created by guest users to the default owner" is also enabled so guests do not own the records they submit.',
115
- remediation: 'Confirm "Assign new records created by guest users to the default owner" is enabled in Setup → Sharing Settings, and periodically review guest user sharing rules for least privilege.',
116
- affectedItems: [{ label: match.Name, url: setupUrl, note: 'Release Update enabled' }],
117
- });
118
- return { findings };
119
- }
120
- if (match) {
121
- // Present, but its status says neither enabled nor available (e.g. a new status value):
122
- // never read as enforced. MN-051.
123
- findings.push({
124
- id: 'guest-record-access-policy-verify-manually',
125
- category: this.category,
126
- riskLevel: 'LOW',
127
- title: `Confirm guest record-access guardrails manually (${guests.length} active guest user(s))`,
128
- detail: `The "Secure guest user record access" Release Update is present, but its status does not say whether it is enabled, so enforcement is not assumed.`,
129
- remediation: 'In Setup → Release Updates and Setup → Sharing Settings, confirm "Secure guest user record access" is on and "Assign new records created by guest users to the default owner" is enabled.',
130
- affectedItems: [{ label: match.Name, url: `${ctx.orgInfo.instanceUrl}/lightning/setup/ReleaseUpdates/home`, note: 'Status unknown' }],
39
+ remediation: 'If an Experience Cloud or Sites site is added later, review its guest user sharing rules and guest-owned records before going live.',
131
40
  });
132
41
  return { findings };
133
42
  }
134
- // No matching update surfaced — typical of orgs where it was auto-activated in
135
- // an earlier release and no longer appears in CriticalUpdate. We got data, so
136
- // this is advisory (LOW), not inconclusive: point the operator at the manual toggles.
137
43
  findings.push({
138
- id: 'guest-record-access-policy-verify-manually',
44
+ id: 'guest-record-access-policy-enforced',
139
45
  category: this.category,
140
46
  riskLevel: 'LOW',
141
- title: `Confirm guest record-access guardrails manually (${guests.length} active guest user(s))`,
142
- detail: 'The "Secure guest user record access" Release Update is no longer exposed via the API (usually because it was auto-activated in an earlier Salesforce release). Enforcement is therefore assumed but not API-verifiable. The two settings that jointly close the guest-ownership-defeats-OWD vector cannot be read programmatically.',
143
- remediation: 'In Setup → Sharing Settings, confirm "Secure guest user record access" is on and "Assign new records created by guest users to the default owner" is enabled. Then confirm no guest user OWNS records (see the guest-object-exposure finding) and that guest access is granted only via minimal guest user sharing rules.',
144
- affectedItems: [{ label: 'Sharing Settings', url: setupUrl, note: 'Manual verification required' }],
47
+ passed: true,
48
+ title: `"Secure guest user record access" is enforced by the platform (${guests.length} active guest user(s))`,
49
+ detail: "Salesforce has enforced secure guest user record access in every org since Winter '21, and from API 50.0 the setting is always on and cannot be turned off. Guests get no access from the org-wide default, and new record access for guests comes only through guest user sharing rules. Records a guest owns, shares granted before Winter '21, and Apex or flows that run without sharing can still reach records.",
50
+ remediation: 'Nothing to switch on. Review the residual paths: guest-object-exposure and guest-user-access report guest-owned and guest-shared records, and guest-executable-apex reports Apex guests can run without sharing.',
51
+ affectedItems: [{ label: 'Sharing Settings', url: setupUrl, note: 'Enforced by the platform' }],
145
52
  });
146
53
  return { findings };
147
54
  }
@@ -155,7 +155,7 @@ export class GuestTrafficAnomalyCheck {
155
155
  riskLevel: 'HIGH',
156
156
  title: `${reconIps.length} source IP(s) ran a GraphQL object-enumeration (totalCount) sweep as a guest`,
157
157
  detail: 'These unauthenticated source IPs issued GraphQL queries that request only totalCount across many distinct objects — the signature of reconnaissance that maps the guest-readable data surface before bulk extraction. This is exactly the pre-attack recon pattern seen through aura://RecordUiController/ACTION$executeGraphQL on Experience Cloud sites.',
158
- remediation: 'Treat these IPs as hostile and block them at the WAF/CDN. Then close the surface they were mapping: set external OWD to Private, strip guest object read permissions, and enforce "Secure guest user record access". Enable Threat Detection storage and a Transaction Security Policy to catch this in real time.',
158
+ remediation: 'Treat these IPs as hostile and block them at the WAF/CDN. Then close the surface they were mapping: remove guest sharing rules and guest object read permissions, and reassign guest-owned records. Enable Threat Detection storage and a Transaction Security Policy to catch this in real time.',
159
159
  affectedItems: reconIps
160
160
  .sort((a, b) => b[1].reconEntities.size - a[1].reconEntities.size)
161
161
  .slice(0, 20)
@@ -2,9 +2,9 @@ import type { AuditContext } from '@cclabsnz/sf-core';
2
2
  import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
3
  export declare class OauthDeviceAndAssetTokenFlowsCheck implements SecurityCheck {
4
4
  readonly id = "oauth-device-and-asset-token-flows";
5
- readonly name = "OAuth Device & Password Flows";
5
+ readonly name = "OAuth Username-Password Flow";
6
6
  readonly category = "Identity & Access";
7
- readonly description = "Flags OAuth 2.0 Device Flow and Username-Password Flow enabled in OAuth and OpenID Connect Settings.";
7
+ readonly description = "Flags the OAuth 2.0 Username-Password Flow when OAuth and OpenID Connect Settings do not block it.";
8
8
  run(ctx: AuditContext): Promise<CheckResult>;
9
9
  }
10
10
  //# sourceMappingURL=OauthDeviceAndAssetTokenFlowsCheck.d.ts.map
@@ -1,13 +1,22 @@
1
+ /** Settings types outside jsforce's schema come back with string values. */
2
+ function asBoolean(v) {
3
+ if (v === true || v === 'true')
4
+ return true;
5
+ if (v === false || v === 'false')
6
+ return false;
7
+ return undefined;
8
+ }
1
9
  export class OauthDeviceAndAssetTokenFlowsCheck {
2
10
  id = 'oauth-device-and-asset-token-flows';
3
- name = 'OAuth Device & Password Flows';
11
+ name = 'OAuth Username-Password Flow';
4
12
  category = 'Identity & Access';
5
- description = 'Flags OAuth 2.0 Device Flow and Username-Password Flow enabled in OAuth and OpenID Connect Settings.';
13
+ description = 'Flags the OAuth 2.0 Username-Password Flow when OAuth and OpenID Connect Settings do not block it.';
6
14
  async run(ctx) {
7
15
  const findings = [];
8
16
  const oauthUrl = `${ctx.orgInfo.instanceUrl}/lightning/setup/OauthOidcSettings/home`;
9
- // Org settings are the only evidence read. A flag counts only when the read returned it as
10
- // a boolean: a failed read, an absent Metadata client or a missing field is not "disabled".
17
+ // Org settings are the only evidence read. The flow counts as blocked or not only when the
18
+ // read returned the field as a boolean: a failed read, an absent Metadata client or a missing
19
+ // field is not "blocked".
11
20
  let settings = null;
12
21
  if (ctx.metadata) {
13
22
  try {
@@ -17,64 +26,44 @@ export class OauthDeviceAndAssetTokenFlowsCheck {
17
26
  settings = null;
18
27
  }
19
28
  }
20
- const device = typeof settings?.isDeviceFlowEnabled === 'boolean' ? settings.isDeviceFlowEnabled : undefined;
21
- const password = typeof settings?.isPasswordFlowEnabled === 'boolean' ? settings.isPasswordFlowEnabled : undefined;
22
- if (device === true) {
23
- findings.push({
24
- id: 'oauth-device-flow-enabled',
25
- category: this.category,
26
- riskLevel: 'HIGH',
27
- title: 'OAuth 2.0 Device Flow is ENABLED in org settings',
28
- detail: 'OAuth 2.0 Device Flow allows a user to authorize a token by entering an 8-character code on a legitimate verification URL. Attackers frequently use Device Code phishing to bypass standard browser-based conditional access and MFA controls, obtaining persistent refresh tokens.',
29
- remediation: 'Disable OAuth 2.0 Device Flow in Setup → OAuth and OpenID Connect Settings unless strictly required for headless devices.',
30
- affectedItems: [
31
- {
32
- label: 'OAuth and OpenID Connect Settings',
33
- url: oauthUrl,
34
- note: 'Disable "Allow OAuth Device Flow"',
35
- },
36
- ],
37
- });
38
- }
39
- if (password === true) {
29
+ const blocked = asBoolean(settings?.blockOAuthUnPwFlow);
30
+ if (blocked === false) {
40
31
  findings.push({
41
32
  id: 'oauth-password-flow-enabled',
42
33
  category: this.category,
43
34
  riskLevel: 'HIGH',
44
- title: 'OAuth 2.0 Username-Password Flow is ENABLED in org settings',
35
+ title: 'OAuth 2.0 Username-Password Flow is not blocked in org settings',
45
36
  detail: 'The Resource Owner Password Credentials (ROPC / Username-Password) flow allows exchanging raw credentials directly for access tokens, completely bypassing interactive SSO redirects, browser-based MFA, and device trust policies.',
46
- remediation: 'Disable Username-Password Flow in Setup → OAuth and OpenID Connect Settings, and migrate integrations to OAuth 2.0 Client Credentials or JWT Bearer flow.',
37
+ remediation: 'Turn on "Block OAuth Username-Password Flows" in Setup → OAuth and OpenID Connect Settings, and migrate integrations to OAuth 2.0 Client Credentials or JWT Bearer flow.',
47
38
  affectedItems: [
48
39
  {
49
40
  label: 'OAuth and OpenID Connect Settings',
50
41
  url: oauthUrl,
51
- note: 'Disable "Allow Username-Password Flow"',
42
+ note: 'Block OAuth Username-Password Flows',
52
43
  },
53
44
  ],
54
45
  });
55
46
  }
56
- if (device === false && password === false) {
47
+ else if (blocked === true) {
57
48
  findings.push({
58
49
  id: 'oauth-device-and-asset-flows-ok',
59
50
  category: this.category,
60
51
  riskLevel: 'LOW',
61
52
  passed: true,
62
- title: 'Phishable OAuth Device Flow and Username-Password Flow are disabled',
63
- detail: 'Org settings confirm both OAuth 2.0 Device Flow and Username-Password Flow are disabled, eliminating secondary token-issuance backdoors.',
64
- remediation: 'Keep Device Flow and Password Flow disabled org-wide.',
53
+ title: 'OAuth Username-Password Flow is blocked org-wide',
54
+ detail: 'OAuth and OpenID Connect Settings block the Username-Password Flow, so no connected app can exchange a raw password for a token. Device Flow is switched on per connected app ("Enable for Device Flow"), and connected app metadata does not report it, so review it in each app that needs it.',
55
+ remediation: 'Keep the Username-Password Flow blocked, and enable Device Flow only on connected apps for headless devices.',
65
56
  });
66
57
  }
67
- else if (device === undefined || password === undefined) {
68
- const unread = [device === undefined && 'Device Flow', password === undefined && 'Username-Password Flow']
69
- .filter(Boolean)
70
- .join(' and ');
58
+ else {
71
59
  findings.push({
72
60
  id: 'oauth-device-and-asset-flows-advisory',
73
61
  category: this.category,
74
62
  riskLevel: 'INFO',
75
- title: `Verify the OAuth ${unread} setting manually`,
76
- detail: `This run could not read the ${unread} setting from OAuth and OpenID Connect Settings, so whether it is enabled is unknown. Both flows let a token be issued outside the browser sign-in, bypassing MFA and conditional access.`,
77
- remediation: 'In Setup → OAuth and OpenID Connect Settings, confirm "Allow OAuth Device Flow" and "Allow OAuth Username-Password Flows" are off unless a documented integration needs them.',
63
+ inconclusive: true,
64
+ title: 'Verify the OAuth Username-Password Flow setting manually',
65
+ detail: 'This run could not read whether OAuth and OpenID Connect Settings block the Username-Password Flow, so whether it is allowed is unknown. The flow lets a token be issued for a raw password, bypassing MFA and conditional access.',
66
+ remediation: 'In Setup → OAuth and OpenID Connect Settings, confirm "Block OAuth Username-Password Flows" is on unless a documented integration needs the flow.',
78
67
  affectedItems: [{ label: 'OAuth and OpenID Connect Settings', url: oauthUrl }],
79
68
  });
80
69
  }
@@ -178,7 +178,7 @@ export const CHECKS = [
178
178
  new PublicContentExposureCheck(), // externally available Documents + public static resources
179
179
  new GuestObjectExposureCheck(), // auto-discovered guest bulk-read surface (UI API) + ownership-defeats-OWD
180
180
  new GuestSiteOptionsCheck(), // guest file access + guest member visibility on Experience sites
181
- new GuestRecordAccessPolicyCheck(), // "Secure guest user record access" enforcement (ownership-defeats-OWD guardrail)
181
+ new GuestRecordAccessPolicyCheck(), // "Secure guest user record access": platform-enforced since API 50.0
182
182
  new ThreatDetectionCheck(), // Guest User Anomaly / Threat Detection event storage enabled
183
183
  new LoginAccessPolicyCheck(), // delegated admin + login-as impersonation paths
184
184
  new DataExportAccessCheck(), // Weekly Export / API+ViewAll bulk-exfil capability
@@ -16,7 +16,7 @@ export const CHECK_META = {
16
16
  'csp-trusted-sites': { effort: 'quick', impact: 'Insecure HTTP CSP entries allow mixed-content loading and man-in-the-middle script injection.' },
17
17
  'named-credentials': { effort: 'quick', impact: 'Unmanaged callout endpoints can send org data to unintended or attacker-controlled destinations.' },
18
18
  'hardcoded-credentials': { effort: 'moderate', impact: 'Secrets embedded in Apex can be read by anyone with code access and reused to reach connected systems.' },
19
- 'custom-settings': { effort: 'quick', impact: 'Credential-like custom settings may store secrets readable by users who can query them.' },
19
+ 'custom-settings': { effort: 'quick', impact: 'A secret kept in a custom setting or custom metadata field is readable by users who can query the type.' },
20
20
  'health-check': { effort: 'moderate', impact: 'Unaddressed Health Check high-risk settings are documented, exploitable misconfigurations.' },
21
21
  'audit-trail': { effort: 'quick', impact: 'Without reviewing the audit trail, malicious permission changes and Login-As abuse go undetected.' },
22
22
  'code-security': { effort: 'project', impact: 'Low Apex test coverage and injection-prone code hide exploitable vulnerabilities behind untested paths.' },
@@ -72,7 +72,7 @@ export const CHECK_META = {
72
72
  'guest-object-exposure': { effort: 'moderate', impact: 'Grades guest-readable objects by ACTUAL UI-API reachability: objects the UI API models whose records the guest owns are bulk-readable unauthenticated via GraphQL (CRITICAL, enabling mass PII exfiltration without login); records shared with guests whatever the OWD (guest sharing rules, legacy manual, Apex or group shares, or a read UserRecordAccess confirms) are HIGH, for the org to confirm they are meant to be public; a public external OWD without a confirmed guest read is MEDIUM, since secure guest record access means the OWD alone gives guests nothing; objects readable only in the sharing model but not UI-API-modelled (Calendar, AuthSession, etc.) are MEDIUM defense-in-depth.' },
73
73
  'guest-site-options': { effort: 'quick', impact: 'Guest file access and member visibility let unauthenticated visitors download public files and enumerate site members.' },
74
74
  'threat-detection': { effort: 'moderate', impact: 'Without Guest User Anomaly storage, malicious guest bulk-reads are never flagged and cannot be reconstructed after the fact.' },
75
- 'guest-record-access-policy': { effort: 'quick', impact: 'Without "Secure guest user record access" enforced, guests own the records they submit and can read them under a Private OWD, turning a public form into an unauthenticated bulk-read surface.' },
75
+ 'guest-record-access-policy': { effort: 'quick', impact: 'The platform enforces this; records a guest owns or that older shares grant stay readable without a login.' },
76
76
  'guest-traffic-anomaly': { effort: 'moderate', impact: 'Guest requests from anonymizer/hosting IPs, single-IP bursts, and GraphQL totalCount sweeps are the live signatures of scraping and pre-exfiltration recon — unmonitored, they only surface after data is gone.' },
77
77
  'login-access-policy': { effort: 'moderate', impact: 'Delegated admins and "log in as any user" let accounts impersonate others and self-escalate, bypassing normal credentials and admin-focused monitoring.' },
78
78
  'data-export-access': { effort: 'quick', impact: 'Weekly Data Export or API access with View/Modify All is a one-step, org-wide exfiltration capability in the wrong hands.' },
@@ -99,7 +99,7 @@ export const CHECK_META = {
99
99
  'data-cloud-data-space-isolation': { effort: 'moderate', impact: 'Default Data Space over-sharing flattens Salesforce OWD record security, exposing sensitive customer data across integrations and partner users.' },
100
100
  'platform-event-subscriber-context': { effort: 'moderate', impact: 'Platform events published by low-trust or guest users trigger subscriber Apex running as Automated Process or Admin, creating a direct privilege escalation bridge.' },
101
101
  'flow-http-callout-credential-bypass': { effort: 'quick', impact: 'Declarative Flow HTTP callouts storing API keys or bearer tokens in formulas bypass Named Credentials and leak secrets in outbound integrations.' },
102
- 'oauth-device-and-asset-token-flows': { effort: 'quick', impact: 'Global OAuth Device Flow and password flows remain open to device-code phishing and credential replay, circumventing SSO and MFA protections.' },
102
+ 'oauth-device-and-asset-token-flows': { effort: 'quick', impact: 'An unblocked Username-Password Flow lets anyone holding a password obtain a token without SSO or MFA.' },
103
103
  'delegated-authentication-exposure': { effort: 'moderate', impact: 'Delegated Authentication over insecure endpoints or assigned to admins allows attackers who compromise the gateway to authenticate as any admin user.' },
104
104
  'delegated-administration-groups': { effort: 'moderate', impact: 'Delegated Admin groups grant shadow-admin capabilities (user management, login-as, permission set assignment) completely invisible to standard permission set queries.' },
105
105
  'auth-provider-registration-handler': { effort: 'moderate', impact: 'Auth Provider registration handlers running as Admin that match users solely on unverified email addresses allow pre-authentication account takeover.' },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cclabsnz/sf-audit",
3
- "version": "1.25.0",
3
+ "version": "1.26.0",
4
4
  "description": "Read-only Salesforce security audit for the sf CLI: 109 checks, attack-chain correlation, A-F risk grading, compliance mapping, free EventLogFile capture, and Guest User Anomaly investigation.",
5
5
  "keywords": [
6
6
  "salesforce",