@cclabsnz/sf-audit 1.25.1 → 1.27.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,112 @@ published note and carries the signed provenance attestation and CycloneDX SBOM
9
9
 
10
10
  ## [Unreleased]
11
11
 
12
+ ## [v1.27.0](https://github.com/cclabsnz/sf-audit-plugin/releases/tag/v1.27.0) — 2026-11-11
13
+
14
+ sf-audit is now easier for an AI agent to drive. `--summary` returns page one of the report as
15
+ compact JSON, `sf audit explain` explains a check or a finding, and a Claude Code plugin in this repo
16
+ runs the audit and triages it. `--checks` now works for any selection. No check or score changes.
17
+
18
+ ### Added
19
+
20
+ - **A Claude Code plugin** in `claude-plugin/`, installable with
21
+ `/plugin install sf-audit --marketplace cclabsnz/sf-audit-plugin`. It runs the audit and
22
+ reports page one: the grade and why, coverage, what to fix first and the attack paths. It then
23
+ explains any finding and compares runs (`/sf-audit:audit`, `/sf-audit:fix-first`,
24
+ `/sf-audit:explain`, `/sf-audit:diff`). It needs this CLI at 1.27.0 or later. It is not part of
25
+ the npm package.
26
+ - **`--summary`**, with `--json`: page one of the report as data. It gives the grade and its reason,
27
+ evidence coverage, counts, the fix-first plan and the attack paths, labelled C1 and P1 as in the
28
+ reports. Each action lists the ids of the findings it closes. It carries no detail prose or
29
+ affected lists, so it is a fraction of `--digest`'s size, and it is meant for an agent to triage
30
+ before reading further.
31
+ - **`sf audit explain <id>`**. With a check id it gives what the check looks for, its domain,
32
+ typical effort, why it matters and its compliance mapping. With `--file` and a finding id from a
33
+ run it gives what the finding affects, the attack chains it is part of (and whether fixing it
34
+ breaks them) and the fix-first action that closes it. With `--file` and a check id it lists that
35
+ check's findings in the run. Works offline.
36
+
37
+ ### Fixed
38
+
39
+ - **`--checks` runs any selection.** A check that reads data another check collects (Apex bodies,
40
+ connected app names, named credential endpoints and others) failed with "depends on cache key ...
41
+ but no preceding check declares it" unless that check was selected too, so `--checks apex-sharing`
42
+ and the documented example `--checks hardcoded-credentials,apex-sharing` both stopped before
43
+ running. The command now adds the checks that collect that data, runs them first, and names them
44
+ in a warning (shown with `--json` too); their findings count toward the grade and `--fail-on`.
45
+ A test runs every check alone. docs/COMMANDS.md no longer says there are 88 checks.
46
+
47
+ ## [v1.26.0](https://github.com/cclabsnz/sf-audit-plugin/releases/tag/v1.26.0) — 2026-11-11
48
+
49
+ Four checks read fields or values Salesforce does not have, or matched by wording, so they could
50
+ not report what they were for. They now read what the platform writes, confirmed against a
51
+ Developer Edition org. Grades can move either way: orgs that allow the OAuth Username-Password
52
+ Flow get a new HIGH finding and may fall; orgs lose a false HIGH guest finding and most
53
+ connected-app inactivity noise, and custom settings matches drop from HIGH to MEDIUM or LOW.
54
+
55
+ ### Changed
56
+
57
+ - **The custom settings check looks at fields, not object names.** It flagged any custom object
58
+ named with "Setting", "Config" or "Credential" whose name or description contained a word such
59
+ as "key", at HIGH, so most of its hits were not secrets. It now reads the fields of actual custom
60
+ settings and custom metadata types, and reports plain-text fields whose own name says they hold
61
+ a secret: password, passphrase, secret, token, credential, bearer, or a qualified key such as API,
62
+ private, client or signing key. Bare "key", names that only describe a secret (`Token_Endpoint`,
63
+ `Secret_Name`), and a Named Credential's name are not reported, nor are encrypted, number and
64
+ checkbox fields. Record values are still never read.
65
+ - `custom-settings-credentials` is MEDIUM and covers the org's own fields.
66
+ - Managed-package fields are reported apart as `custom-settings-credentials-managed`, LOW. It
67
+ feeds no attack chain, since whether the field is readable depends on the type's visibility,
68
+ which is not read.
69
+ - Ordinary custom objects are no longer reported for their names. Secrets in Apex and custom
70
+ labels are still covered by `hardcoded-credentials` and `custom-labels-credential`.
71
+ - A failed read is now inconclusive rather than an error. If custom metadata types cannot be
72
+ listed, custom settings are still read and the finding says so.
73
+
74
+ ### Fixed
75
+
76
+ - **The OAuth Username-Password Flow check reads the setting Salesforce has.** It read
77
+ `isDeviceFlowEnabled` and `isPasswordFlowEnabled` from OAuth and OpenID Connect Settings, which
78
+ has neither field, so every run ended in "verify manually". It now reads `blockOAuthUnPwFlow`,
79
+ confirmed against a Developer Edition org, and reports `oauth-password-flow-enabled` when the
80
+ flow is not blocked. Orgs that allow the flow will see the finding, and it feeds the
81
+ credential-theft chain, so some grades may fall. When the setting cannot be read, the advisory
82
+ is now marked inconclusive, so the check no longer counts as assessed.
83
+ - **The Device Flow finding is removed.** Device Flow is switched on per connected app, and neither
84
+ OauthOidcSettings nor ConnectedApp metadata carries it, so `oauth-device-flow-enabled` could
85
+ never fire. A waiver on that id now matches nothing and can be deleted. The check is renamed
86
+ OAuth Username-Password Flow; its id is unchanged, so waivers on the check still apply.
87
+ - **Infinite refresh tokens are read from the refresh token policy only.** The connected-app scope
88
+ check also flagged `oauthConfig.refreshTokenValidityPeriod = -1`, which is not a ConnectedApp
89
+ metadata field. `oauthPolicy.refreshTokenPolicy = infinite` is how the Metadata API states a
90
+ token valid until revoked, and it already raised the finding. Results do not change.
91
+ - **Inactive connected apps are found by real OAuth logins.** The check counted LoginHistory rows
92
+ with `LoginType LIKE 'OAuth%'`, and no LoginType starts with "OAuth": an OAuth login is recorded
93
+ as `Remote Access 2.0` or `Remote Access Client`, with the flow in `LoginSubType`. The filter
94
+ matched nothing, so every connected app was reported as having no OAuth logins in 90 days. It
95
+ now reads either field, so apps that sign in count as active and orgs will see far fewer
96
+ `connected-app-inactive` items. An app that only exchanges refresh tokens may still read as
97
+ inactive: whether that writes a LoginHistory row is not established, and
98
+ `oauth-token-inventory` covers standing tokens.
99
+ - **The inactive connected app remedy no longer leads with deleting the app.** It asks the owner
100
+ first, then revokes tokens and blocks the app in Connected Apps OAuth Usage, which can be
101
+ reversed. A delete cannot be undone, loses the consumer key and secret, and connected app
102
+ creation is restricted from Spring '26. The finding now says inactive apps *may* still hold
103
+ credentials.
104
+ - **The schema guard judges LIKE on picklists.** A LIKE pattern that fits no value of a picklist
105
+ fails the guard, as an unknown `=` or `IN` value already did. The deep-path guard now drives the
106
+ inactivity check to its LoginHistory read.
107
+ - **Secure guest user record access is reported as the platform guarantee it is.** Salesforce has
108
+ enforced it in every org since Winter '21: from API 50.0 `SharingSettings.enableSecureGuestAccess`
109
+ is always true, and the Release Update that carried it is gone. The check looked for a Release
110
+ Update whose title or description mentioned "guest" and "record access", which could only find a
111
+ different guest update. Depending on that update's status it reported a false pass, a false HIGH
112
+ `guest-record-access-policy-not-enforced` (which also fed the unauthenticated chains), or a LOW
113
+ "verify manually". It now passes for orgs with guest users and points to
114
+ `guest-object-exposure` and `guest-user-access`, which read guest-owned and guest-shared records
115
+ directly. `guest-record-access-policy-not-enforced`, `-verify-manually` and
116
+ `-tooling-inaccessible` are removed; waivers on them match nothing and can be deleted.
117
+
12
118
  ## [v1.25.1](https://github.com/cclabsnz/sf-audit-plugin/releases/tag/v1.25.1) — 2026-11-11
13
119
 
14
120
  Documentation only. No change to checks, scores or reports.
@@ -322,7 +428,6 @@ mean what they say. Found by running the audit against a Developer Edition org a
322
428
  - `scripts/capture-schema.mjs` and a captured Developer Edition schema
323
429
  (`test/fixtures/schema/developer-edition.json`, standard fields only). A test runs every
324
430
  check against it and fails on any query the org would reject.
325
- ||||||| a23c86e
326
431
 
327
432
  ## [v1.17.0](https://github.com/cclabsnz/sf-audit-plugin/releases/tag/v1.17.0) — 2026-10-17
328
433
 
package/README.md CHANGED
@@ -89,7 +89,8 @@ check id.
89
89
  | `--fail-on` | (none) | Exit 1 if any finding is at or above `CRITICAL`/`HIGH`/`MEDIUM`/`LOW`. For CI |
90
90
  | `--fail-on-inconclusive` | `false` | Exit 3 if any check could not gather evidence. For CI |
91
91
  | `--waivers` | `.sfaudit-waivers.json` if present | Accepted-risk waivers. See [Accepting a risk](#accepting-a-risk) |
92
- | `--digest` | `false` | Compact result for programmatic callers — no passing checks, no prose, capped lists |
92
+ | `--digest` | `false` | With `--json`: compact result for programmatic callers — no passing checks, no prose, capped lists |
93
+ | `--summary` | `false` | With `--json`: page one as data — grade and why, coverage, the fix-first plan with the finding ids each action closes, attack paths. Smaller than `--digest` |
93
94
  | `--checks` | *(all)* | Run only these check ids |
94
95
  | `--frameworks` | `universal` | Compliance matrix scope for the executive report |
95
96
  | `--no-history` / `--keep-history` | `false` | Skip, or force, the archive to `~/.sf/audit-history`. Skipped in CI (`CI` set, `GITHUB_ACTIONS`, `TF_BUILD`, `JENKINS_URL`) unless `--keep-history` |
@@ -139,6 +140,16 @@ inconclusive count is still in the report body. `3` exists so a pipeline can tel
139
140
  Every flag, more examples, and what the executive report contains:
140
141
  **[docs/COMMANDS.md](docs/COMMANDS.md)**.
141
142
 
143
+ ## Using it from Claude Code
144
+
145
+ A Claude Code plugin in this repo runs the audit and triages it for you: the grade and why, what to fix first, the attack paths, and any finding explained. It drives this CLI, so install the CLI first (1.27.0 or later), then in Claude Code:
146
+
147
+ ```text
148
+ /plugin install sf-audit --marketplace cclabsnz/sf-audit-plugin
149
+ ```
150
+
151
+ Then `/sf-audit:audit myOrg`, `/sf-audit:fix-first`, `/sf-audit:explain <id>` and `/sf-audit:diff`. Any agent can do the same without the plugin: `sf audit security --json --summary` returns page one as compact JSON, and `sf audit explain` explains a check or finding.
152
+
142
153
  ## What It Checks
143
154
 
144
155
  **109 read-only checks** across ten domains. Every finding is risk-rated CRITICAL → INFO, mapped to
@@ -294,7 +305,7 @@ A finding you have reviewed and accepted can be waived, which takes it out of th
294
305
 
295
306
  ## Other commands
296
307
 
297
- Beyond the audit itself, the plugin ships five commands. Each is documented in
308
+ Beyond the audit itself, the plugin ships these commands. Each is documented in
298
309
  **[docs/COMMANDS.md](docs/COMMANDS.md)**.
299
310
 
300
311
  | Command | What it does |
@@ -302,6 +313,7 @@ Beyond the audit itself, the plugin ships five commands. Each is documented in
302
313
  | `sf audit history` / `sf audit diff` | Every run auto-archives to `~/.sf/audit-history/{orgId}`. Show posture drift across runs as a table plus an HTML timeline, or diff any two report JSONs |
303
314
  | `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 |
304
315
  | `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 |
316
+ | `sf audit explain` | Explain a check, or one finding from a run: what it affects, the attack chains it is part of, and the fix-first action that closes it. Offline |
305
317
  | `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 |
306
318
  | `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 |
307
319
 
@@ -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
  }