@cclabsnz/sf-audit 1.16.0 → 1.17.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 +118 -1
- package/README.md +94 -24
- package/config/scoring.sample.json +104 -5
- package/lib/apps/analyzeApps.d.ts +8 -2
- package/lib/apps/analyzeApps.js +7 -2
- package/lib/apps/apiLogSource.d.ts +39 -0
- package/lib/apps/apiLogSource.js +75 -0
- package/lib/apps/appResolver.js +30 -4
- package/lib/apps/grantedAccess.js +16 -3
- package/lib/apps/leastPrivilege.d.ts +3 -1
- package/lib/apps/leastPrivilege.js +7 -3
- package/lib/apps/permissionSetGenerator.d.ts +22 -0
- package/lib/apps/permissionSetGenerator.js +100 -0
- package/lib/apps/types.d.ts +6 -0
- package/lib/apps/usageCollector.d.ts +7 -1
- package/lib/apps/usageCollector.js +57 -26
- package/lib/chains/CapabilityRegistry.js +26 -0
- package/lib/chains/namedChains.js +95 -7
- package/lib/checks/CheckEngine.d.ts +3 -1
- package/lib/checks/CheckEngine.js +11 -3
- package/lib/checks/impl/ApexCrudFLSCheck.js +45 -10
- package/lib/checks/impl/ApexSharingCheck.js +16 -25
- package/lib/checks/impl/AuthProviderRegistrationHandlerCheck.d.ts +10 -0
- package/lib/checks/impl/AuthProviderRegistrationHandlerCheck.js +131 -0
- package/lib/checks/impl/ConnectedAppsCheck.js +47 -1
- package/lib/checks/impl/DataCloudDataSpaceIsolationCheck.d.ts +10 -0
- package/lib/checks/impl/DataCloudDataSpaceIsolationCheck.js +116 -0
- package/lib/checks/impl/DelegatedAdministrationGroupsCheck.d.ts +10 -0
- package/lib/checks/impl/DelegatedAdministrationGroupsCheck.js +75 -0
- package/lib/checks/impl/DelegatedAuthenticationExposureCheck.d.ts +10 -0
- package/lib/checks/impl/DelegatedAuthenticationExposureCheck.js +98 -0
- package/lib/checks/impl/ExternalAccountHierarchyExposureCheck.d.ts +10 -0
- package/lib/checks/impl/ExternalAccountHierarchyExposureCheck.js +73 -0
- package/lib/checks/impl/FlowHttpCalloutCredentialBypassCheck.d.ts +10 -0
- package/lib/checks/impl/FlowHttpCalloutCredentialBypassCheck.js +115 -0
- package/lib/checks/impl/GenAiPromptTemplateGroundingCheck.d.ts +10 -0
- package/lib/checks/impl/GenAiPromptTemplateGroundingCheck.js +227 -0
- package/lib/checks/impl/GuestExecutableApexCheck.d.ts +1 -1
- package/lib/checks/impl/GuestExecutableApexCheck.js +105 -14
- package/lib/checks/impl/HardcodedCredentialsCheck.js +7 -2
- package/lib/checks/impl/InboundEmailHandlerExposureCheck.d.ts +10 -0
- package/lib/checks/impl/InboundEmailHandlerExposureCheck.js +136 -0
- package/lib/checks/impl/OauthDeviceAndAssetTokenFlowsCheck.d.ts +10 -0
- package/lib/checks/impl/OauthDeviceAndAssetTokenFlowsCheck.js +84 -0
- package/lib/checks/impl/OrgWideEmailSpoofingCheck.d.ts +10 -0
- package/lib/checks/impl/OrgWideEmailSpoofingCheck.js +106 -0
- package/lib/checks/impl/PackagePostInstallSupplyChainCheck.d.ts +10 -0
- package/lib/checks/impl/PackagePostInstallSupplyChainCheck.js +89 -0
- package/lib/checks/impl/PlatformEventSubscriberContextCheck.d.ts +10 -0
- package/lib/checks/impl/PlatformEventSubscriberContextCheck.js +84 -0
- package/lib/checks/impl/RestrictionRulesIntegrityCheck.d.ts +10 -0
- package/lib/checks/impl/RestrictionRulesIntegrityCheck.js +105 -0
- package/lib/checks/impl/ShieldTenantSecretLifecycleCheck.d.ts +10 -0
- package/lib/checks/impl/ShieldTenantSecretLifecycleCheck.js +90 -0
- package/lib/checks/registry.js +30 -0
- package/lib/checks/support/apexAccess.d.ts +56 -0
- package/lib/checks/support/apexAccess.js +127 -0
- package/lib/checks/support/missingObject.d.ts +13 -0
- package/lib/checks/support/missingObject.js +35 -0
- package/lib/commands/audit/apps.d.ts +1 -0
- package/lib/commands/audit/apps.js +83 -29
- package/lib/commands/audit/diff.js +2 -2
- package/lib/commands/audit/history.js +2 -2
- package/lib/commands/audit/incident/report.js +2 -2
- package/lib/commands/audit/security.d.ts +3 -0
- package/lib/commands/audit/security.js +58 -9
- package/lib/commands/audit/timeline.js +2 -2
- package/lib/compliance/mapping.js +28 -7
- package/lib/findings/AuditResult.d.ts +8 -0
- package/lib/findings/CheckMeta.js +15 -0
- package/lib/findings/Finding.d.ts +4 -0
- package/lib/findings/ScoringConfig.d.ts +10 -8
- package/lib/findings/ScoringConfig.js +12 -5
- package/lib/findings/coverage.d.ts +28 -0
- package/lib/findings/coverage.js +30 -0
- package/lib/findings/exitCode.js +1 -1
- package/lib/findings/loadScoringConfig.js +51 -8
- package/lib/findings/scoring.js +14 -5
- package/lib/history/HistoryStore.js +9 -3
- package/lib/history/archivePolicy.d.ts +19 -0
- package/lib/history/archivePolicy.js +34 -0
- package/lib/incident/bundleIo.js +4 -3
- package/lib/incident/collect/collectBundle.d.ts +1 -1
- package/lib/incident/collect/collectBundle.js +4 -3
- package/lib/incident/collect/streamGuestLogs.d.ts +1 -1
- package/lib/incident/collect/streamGuestLogs.js +3 -2
- package/lib/incident/csv.js +4 -4
- package/lib/incident/render/evidence.js +3 -3
- package/lib/incident/render/html.js +2 -3
- package/lib/index.d.ts +2 -0
- package/lib/index.js +2 -0
- package/lib/lib/packageInfo.d.ts +6 -0
- package/lib/lib/packageInfo.js +19 -0
- package/lib/renderers/AttackChainDagRenderer.d.ts +7 -0
- package/lib/renderers/AttackChainDagRenderer.js +139 -0
- package/lib/renderers/ClientReportRenderer.d.ts +2 -0
- package/lib/renderers/ClientReportRenderer.js +34 -6
- package/lib/renderers/DiffHtmlRenderer.js +2 -7
- package/lib/renderers/HistoryRenderer.js +19 -11
- package/lib/renderers/HtmlRenderer.js +19 -6
- package/lib/renderers/MarkdownRenderer.js +7 -0
- package/lib/renderers/SarifRenderer.d.ts +43 -0
- package/lib/renderers/SarifRenderer.js +250 -0
- package/lib/report/ExecutivePriorities.js +1 -1
- package/lib/report/RemediationRoadmap.js +1 -1
- package/lib/waivers/WaiverLoader.d.ts +28 -0
- package/lib/waivers/WaiverLoader.js +103 -0
- package/lib/waivers/WaiverModel.d.ts +32 -0
- package/lib/waivers/WaiverModel.js +28 -0
- package/lib/waivers/applyWaivers.d.ts +22 -0
- package/lib/waivers/applyWaivers.js +85 -0
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -9,7 +9,124 @@ published note and carries the signed provenance attestation and CycloneDX SBOM
|
|
|
9
9
|
|
|
10
10
|
## [Unreleased]
|
|
11
11
|
|
|
12
|
-
|
|
12
|
+
## [v1.17.0](https://github.com/cclabsnz/sf-audit-plugin/releases/tag/v1.17.0) — 2026-10-17
|
|
13
|
+
|
|
14
|
+
109 checks (up from 95) and 19 attack chains (up from 17).
|
|
15
|
+
|
|
16
|
+
### Added
|
|
17
|
+
|
|
18
|
+
- Fourteen checks for surfaces the audit did not reach before:
|
|
19
|
+
- `genai-prompt-template-grounding`: active Prompt Templates grounded on system-mode flows or
|
|
20
|
+
unshared Apex, or mixing untrusted external fields with sensitive CRM data.
|
|
21
|
+
- `data-cloud-data-space-isolation`: a default Data Space shared with integrations, partner or
|
|
22
|
+
agent users, and unconstrained Data Share Targets.
|
|
23
|
+
- `platform-event-subscriber-context`: Platform Event subscribers running in system context or
|
|
24
|
+
as an admin while low-trust or guest users can publish the event.
|
|
25
|
+
- `flow-http-callout-credential-bypass`: Flow HTTP callouts with embedded tokens, or that go
|
|
26
|
+
around Named Credentials.
|
|
27
|
+
- `oauth-device-and-asset-token-flows`: the OAuth Device Flow and Username-Password Flow
|
|
28
|
+
enabled in OAuth and OpenID Connect Settings. An unreadable setting is an advisory, never
|
|
29
|
+
"disabled".
|
|
30
|
+
- `delegated-authentication-exposure`: Delegated Authentication over unencrypted or non-mTLS
|
|
31
|
+
endpoints, or assigned to System Administrator profiles.
|
|
32
|
+
- `delegated-administration-groups`: delegated admin groups that can manage users, log in as
|
|
33
|
+
them or assign permission sets, which permission set queries do not show.
|
|
34
|
+
- `auth-provider-registration-handler`: a RegistrationHandler running as an admin that links
|
|
35
|
+
accounts by email, open to pre-auth account takeover.
|
|
36
|
+
- `inbound-email-handler-exposure`: email services that accept any sender and run Apex.
|
|
37
|
+
- `org-wide-email-spoofing`: Org-Wide Email Addresses open to all profiles without SPF/DKIM
|
|
38
|
+
alignment.
|
|
39
|
+
- `external-account-hierarchy-exposure`: Partner Super Users and External Account Hierarchies
|
|
40
|
+
that widen portal record reach past the external OWD.
|
|
41
|
+
- `restriction-rules-integrity`: inactive Restriction Rules leaving records exposed, and
|
|
42
|
+
conflicting active rules on one object.
|
|
43
|
+
- `package-post-install-supply-chain`: packaged Apex implementing `InstallHandler`, which runs
|
|
44
|
+
in system context on every install and push upgrade.
|
|
45
|
+
- `shield-tenant-secret-lifecycle`: Shield tenant secrets not rotated in 365 days.
|
|
46
|
+
- Two attack chains, both CRITICAL: **Unauthenticated inbound email to privileged code
|
|
47
|
+
execution** (`inbound-email-rce`) and **Guest or low-trust platform event publish to automated
|
|
48
|
+
process escalation** (`platform-event-priv-esc`).
|
|
49
|
+
- Every report states its evidence coverage: the share of checks that gathered evidence, and the
|
|
50
|
+
ids of those that could not. Below 90% a would-be A is capped at B, and the report says why.
|
|
51
|
+
`grade` stays a plain A–F letter; the detail is in the new `coverage` field of the JSON output.
|
|
52
|
+
- Accepted-risk waivers (`--waivers`, or `.sfaudit-waivers.json` in the working directory). A
|
|
53
|
+
waived finding leaves the score, `--fail-on` and the executive priorities and roadmap, and is
|
|
54
|
+
listed under Accepted Risks. Matching is exact, waivers run at most 365 days, and a CRITICAL
|
|
55
|
+
finding needs `acknowledgeCritical`. The loaded file's path is always printed.
|
|
56
|
+
- `sf audit security --no-history` skips the automatic archive to `~/.sf/audit-history`, and the
|
|
57
|
+
archive is now skipped by default in CI (`CI` set to a truthy value, `GITHUB_ACTIONS`, `TF_BUILD`
|
|
58
|
+
or `JENKINS_URL`), so ephemeral or shared runners don't keep org data. `--keep-history` archives
|
|
59
|
+
anyway and wins over `--no-history`.
|
|
60
|
+
- `sf audit security --format sarif` writes a SARIF 2.1.0 log for GitHub code scanning. Results
|
|
61
|
+
carry stable fingerprints so a recurring finding keeps one alert, the tool version comes from
|
|
62
|
+
the package, and checks that could not gather evidence are reported as tool notifications
|
|
63
|
+
rather than alerts.
|
|
64
|
+
- Attack chains now render as a diagram: each step is a card (severity, finding, capability
|
|
65
|
+
granted) joined by arrows, with the step whose fix breaks the chain marked as the cut-point.
|
|
66
|
+
It appears in the attack-path cards of the HTML report (dark) and in the Attack Scenarios of
|
|
67
|
+
the executive report (light). The diagram is self-contained inline SVG, so it works under the
|
|
68
|
+
executive report's no-script CSP and prints to PDF; long chains wrap onto rows of four.
|
|
69
|
+
- `sf audit apps --emit-permset <dir>` writes each app's suggested least-privilege permission set as
|
|
70
|
+
a local `.permissionset-meta.xml` for review. Nothing is deployed. Apps whose recommendation is
|
|
71
|
+
held back (soak window, many interactive users, incomplete logs) get no file, and generated names
|
|
72
|
+
are unique, valid metadata API names.
|
|
73
|
+
- `sf audit apps` now reads `BulkApi2`, `GraphQlQueryExecution` and `AuraRequest` logs as well as
|
|
74
|
+
`RestApi`, resolves External Client Apps, and counts profile object permissions as granted access.
|
|
75
|
+
|
|
76
|
+
### Changed
|
|
77
|
+
|
|
78
|
+
- Apex findings now say which control is bypassed. `WITH SYSTEM_MODE` and
|
|
79
|
+
`AccessLevel.SYSTEM_MODE` switch off CRUD/FLS, not record sharing, so they are reported as
|
|
80
|
+
`apex-crud-fls-system-mode` (MEDIUM) and, for guest-callable classes, as the new
|
|
81
|
+
`guest-executable-apex-system-mode` (HIGH), never as a CRITICAL sharing bypass. `USER_MODE`
|
|
82
|
+
counts as CRUD/FLS enforcement.
|
|
83
|
+
- A guest-callable class that calls a helper declared `without sharing` is now CRITICAL
|
|
84
|
+
`guest-executable-apex-unprotected`, naming the helper. A guest-callable `inherited sharing`
|
|
85
|
+
class is no longer reported CRITICAL: at an entry point it runs with sharing.
|
|
86
|
+
- `@RestResource` classes without sharing are reported alongside `@AuraEnabled` and
|
|
87
|
+
`@RemoteAction` ones.
|
|
88
|
+
- A class's sharing keyword is read from its own declaration, ignoring comments, so a
|
|
89
|
+
`without sharing` class mentioning "with sharing" in a comment is no longer read as protected.
|
|
90
|
+
- `salesbleed-pattern` also fires when the way out is a CSP Trusted URL whose domain is parked
|
|
91
|
+
or no longer resolves: whoever registers it receives anything an agent puts in a link or image.
|
|
92
|
+
When the org shows where outsider text enters (an open email handler, guest write access), that
|
|
93
|
+
finding leads the chain as evidence.
|
|
94
|
+
- `--scoring-config` is now checked strictly. An unknown or misspelled key (`gradeTresholds`,
|
|
95
|
+
`minscore`) is an error instead of being silently ignored, `minScore` must be 0–100, and grade
|
|
96
|
+
thresholds must be ordered after merging with the defaults (A at least as strict as B, and so
|
|
97
|
+
on). Errors name the offending path. A JSON Schema for editors ships as
|
|
98
|
+
`schemas/scoring-config.schema.json`, and `config/scoring.sample.json` now lists every
|
|
99
|
+
registered check.
|
|
100
|
+
- The npm description states the current check count, and a test keeps it in step.
|
|
101
|
+
- README documents unattended CI installs and how to check a release's provenance.
|
|
102
|
+
- Requires `@cclabsnz/sf-core` 0.11.0.
|
|
103
|
+
|
|
104
|
+
### Fixed
|
|
105
|
+
|
|
106
|
+
- Several of the fourteen new checks could not see their evidence, and some reported a pass
|
|
107
|
+
when their query failed; their tests passed because the mocks returned fields the real queries
|
|
108
|
+
never selected. They now read what the org actually returns, and a failed read is inconclusive,
|
|
109
|
+
never a pass.
|
|
110
|
+
- `genai-prompt-template-grounding` no longer builds a regular expression from a class name the
|
|
111
|
+
org returns; the declaration is found with literal patterns in one linear pass.
|
|
112
|
+
- `sf audit apps` no longer reports an empty, clean-looking result when `EventLogFile` cannot be
|
|
113
|
+
read: a failed listing is an error, and partly failed downloads mark the output incomplete and
|
|
114
|
+
suppress revoke recommendations.
|
|
115
|
+
- `connected-apps` lists External Client Apps for manual review of their OAuth policies. Their
|
|
116
|
+
policies are not evaluated automatically, so no External Client App is reported as
|
|
117
|
+
unrestricted or as passing. A failure to list them is reported as inconclusive, and the
|
|
118
|
+
connected-app results still stand.
|
|
119
|
+
|
|
120
|
+
### Security
|
|
121
|
+
|
|
122
|
+
- Local stores that hold org data (`~/.sf/audit-history`, incident bundles, evidence CSVs,
|
|
123
|
+
guest-log staging) are now created owner-only: directories 0700, files 0600, through
|
|
124
|
+
`secureFs` from `@cclabsnz/sf-core`. An existing history root is tightened on first use.
|
|
125
|
+
Report files written to a user-chosen `--output` directory keep that directory's permissions.
|
|
126
|
+
- Every HTML report now carries a Content-Security-Policy that forbids all network requests:
|
|
127
|
+
the executive report allows no script at all, and the interactive reports allow inline script
|
|
128
|
+
only. Values in the history report that are read back from disk (grade, score, dates) are
|
|
129
|
+
escaped or coerced, so a tampered history file cannot inject markup or script.
|
|
13
130
|
|
|
14
131
|
## [v1.16.0](https://github.com/cclabsnz/sf-audit-plugin/releases/tag/v1.16.0) — 2026-10-09
|
|
15
132
|
|
package/README.md
CHANGED
|
@@ -15,13 +15,14 @@
|
|
|
15
15
|
|
|
16
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.
|
|
17
17
|
|
|
18
|
-
- **
|
|
19
|
-
- **Attack-chain correlation:** links individual findings into named, multi-step attack scenarios —
|
|
20
|
-
- **Compliance mapping:** every finding mapped to **source-verified** controls across 10 frameworks (OWASP, OWASP LLM Top 10, SOC 2, ISO/IEC 27001:2022, Security Benchmark for Salesforce, NZ Privacy Act, HISO 10029, NZISM
|
|
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
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
|
|
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
|
|
23
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
|
|
24
|
-
- **Connected-app least-privilege:** `sf audit apps` reads the `RestApi`
|
|
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)
|
|
25
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/))
|
|
26
27
|
- Strictly read-only (SOQL/Tooling/REST GETs + Metadata API reads); see [PERMISSIONS.md](PERMISSIONS.md) for the least-privilege access it needs
|
|
27
28
|
|
|
@@ -33,8 +34,37 @@ sf plugins install @cclabsnz/sf-audit
|
|
|
33
34
|
|
|
34
35
|
You will be warned that the plugin is not digitally signed. That is expected and says nothing about
|
|
35
36
|
this plugin: Salesforce only accepts signing keys served from `developer.salesforce.com`, so no
|
|
36
|
-
third-party plugin can satisfy it. Answer `y`.
|
|
37
|
-
|
|
37
|
+
third-party plugin can satisfy it. Answer `y`.
|
|
38
|
+
|
|
39
|
+
### Unattended installs (CI/CD)
|
|
40
|
+
|
|
41
|
+
To install in CI/CD without the interactive prompt, add the plugin to the CLI allowlist first (the merge step needs `jq`):
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
mkdir -p ~/.config/sf
|
|
45
|
+
if [ -f ~/.config/sf/unsignedPluginAllowList.json ]; then
|
|
46
|
+
jq '. + ["@cclabsnz/sf-audit"] | unique' ~/.config/sf/unsignedPluginAllowList.json > ~/.config/sf/unsignedPluginAllowList.json.tmp && mv ~/.config/sf/unsignedPluginAllowList.json.tmp ~/.config/sf/unsignedPluginAllowList.json
|
|
47
|
+
else
|
|
48
|
+
echo '["@cclabsnz/sf-audit"]' > ~/.config/sf/unsignedPluginAllowList.json
|
|
49
|
+
fi
|
|
50
|
+
|
|
51
|
+
sf plugins install @cclabsnz/sf-audit
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
### Verifying provenance
|
|
55
|
+
|
|
56
|
+
Every release is published from GitHub Actions with a signed npm provenance attestation that
|
|
57
|
+
links the tarball to the commit and workflow run that built it. To check a version before
|
|
58
|
+
installing it:
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
npm view @cclabsnz/sf-audit@<version> dist.attestations.provenance.predicateType
|
|
62
|
+
# https://slsa.dev/provenance/v1
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
The package page on npmjs.com shows the same attestation, with a link to the build.
|
|
66
|
+
|
|
67
|
+
Detailed allowlisting and local development setup are in **[docs/INSTALL.md](docs/INSTALL.md)**.
|
|
38
68
|
|
|
39
69
|
Since "trust us" is a poor answer from a tool that authenticates against your production org, the
|
|
40
70
|
guarantees here are checkable rather than asserted — see [Trust & verification](#trust--verification).
|
|
@@ -45,17 +75,19 @@ guarantees here are checkable rather than asserted — see [Trust & verification
|
|
|
45
75
|
sf audit security --target-org <orgAlias>
|
|
46
76
|
```
|
|
47
77
|
|
|
48
|
-
Runs all
|
|
78
|
+
Runs all 109 checks and writes an HTML report to the current directory. `sf audit list` prints every
|
|
49
79
|
check id.
|
|
50
80
|
|
|
51
81
|
| Flag | Default | |
|
|
52
82
|
|------|---------|---|
|
|
53
|
-
| `--format` / `-f` | `html` | `html`, `md`, `json`, `executive` — comma-separated |
|
|
83
|
+
| `--format` / `-f` | `html` | `html`, `md`, `json`, `executive`, `sarif` — comma-separated |
|
|
54
84
|
| `--fail-on` | (none) | Exit 1 if any finding is at or above `CRITICAL`/`HIGH`/`MEDIUM`/`LOW`. For CI |
|
|
55
85
|
| `--fail-on-inconclusive` | `false` | Exit 3 if any check could not gather evidence. For CI |
|
|
86
|
+
| `--waivers` | `.sfaudit-waivers.json` if present | Accepted-risk waivers. See [Accepting a risk](#accepting-a-risk) |
|
|
56
87
|
| `--digest` | `false` | Compact result for programmatic callers — no passing checks, no prose, capped lists |
|
|
57
88
|
| `--checks` | *(all)* | Run only these check ids |
|
|
58
89
|
| `--frameworks` | `universal` | Compliance matrix scope for the executive report |
|
|
90
|
+
| `--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` |
|
|
59
91
|
|
|
60
92
|
```bash
|
|
61
93
|
# Fail a pipeline on HIGH or worse
|
|
@@ -75,6 +107,9 @@ sf audit security --target-org myOrg --json
|
|
|
75
107
|
|
|
76
108
|
# Compact result for an agent or script
|
|
77
109
|
sf audit security --target-org myOrg --json --digest
|
|
110
|
+
|
|
111
|
+
# SARIF 2.1.0 for GitHub code scanning or any SARIF viewer
|
|
112
|
+
sf audit security --target-org myOrg --format sarif --output ./reports
|
|
78
113
|
```
|
|
79
114
|
|
|
80
115
|
In GitHub Actions, [cclabsnz/sf-audit-action](https://github.com/cclabsnz/sf-audit-action) wraps this:
|
|
@@ -96,24 +131,24 @@ A definite finding outranks unknown coverage: when both apply you get `1`, and t
|
|
|
96
131
|
inconclusive count is still in the report body. `3` exists so a pipeline can tell
|
|
97
132
|
"this org is fine" apart from "the audit user could not see enough to judge".
|
|
98
133
|
|
|
99
|
-
|
|
134
|
+
Every flag, more examples, and what the executive report contains:
|
|
100
135
|
**[docs/COMMANDS.md](docs/COMMANDS.md)**.
|
|
101
136
|
|
|
102
137
|
## What It Checks
|
|
103
138
|
|
|
104
|
-
**
|
|
139
|
+
**109 read-only checks** across ten domains. Every finding is risk-rated CRITICAL → INFO, mapped to
|
|
105
140
|
compliance controls, and correlated into [attack chains](#attack-chains).
|
|
106
141
|
|
|
107
142
|
| Domain | Checks |
|
|
108
143
|
|--------|-------:|
|
|
109
|
-
| Identity & Authentication |
|
|
110
|
-
| Users, Permissions & Privilege |
|
|
111
|
-
| Data Access & Sharing |
|
|
112
|
-
| Guest & External-Facing Access |
|
|
113
|
-
| Integrations, Connected Apps & Deployments |
|
|
144
|
+
| Identity & Authentication | 16 |
|
|
145
|
+
| Users, Permissions & Privilege | 14 |
|
|
146
|
+
| Data Access & Sharing | 14 |
|
|
147
|
+
| Guest & External-Facing Access | 13 |
|
|
148
|
+
| Integrations, Connected Apps & Deployments | 14 |
|
|
114
149
|
| Monitoring & Threat Detection | 10 |
|
|
115
|
-
| Apex & Code Security |
|
|
116
|
-
| AI & Agents (Agentforce / GenAI) |
|
|
150
|
+
| Apex & Code Security | 12 |
|
|
151
|
+
| AI & Agents (Agentforce / GenAI) | 9 |
|
|
117
152
|
| Org Health & Configuration | 5 |
|
|
118
153
|
| Secrets & Credential Storage | 2 |
|
|
119
154
|
|
|
@@ -125,9 +160,9 @@ advisories are INFO and never inflate the health score.
|
|
|
125
160
|
|
|
126
161
|
## Compliance frameworks
|
|
127
162
|
|
|
128
|
-
Findings map to controls across
|
|
129
|
-
27001:2022,
|
|
130
|
-
Security Rule
|
|
163
|
+
Findings map to controls across 10 frameworks organized into 8 source-verified general baselines and 2 specialized jurisdictional packs:
|
|
164
|
+
- **8 General Baselines:** OWASP Top 10 (2021), OWASP LLM Top 10 (2025), SOC 2 (2017 TSC), ISO/IEC 27001:2022, Security Benchmark for Salesforce (SBS), New Zealand Privacy Act 2020, HISO 10029:2022, and NZISM (v3.8).
|
|
165
|
+
- **2 Jurisdictional Packs:** HIPAA Security Rule (45 CFR Part 164 Subpart C) and GDPR (Regulation (EU) 2016/679).
|
|
131
166
|
|
|
132
167
|
The mapping is built on a **sourced catalog** — each control carries its framework, pinned version,
|
|
133
168
|
official title and a citation — so a finding ties to an exact, defensible requirement rather than a
|
|
@@ -150,7 +185,7 @@ A list of findings is not a risk assessment. Three MEDIUM findings that combine
|
|
|
150
185
|
unauthenticated path to bulk data matter more than a lone HIGH that leads nowhere, and reading a
|
|
151
186
|
report severity-by-severity hides exactly that.
|
|
152
187
|
|
|
153
|
-
So every audit correlates its findings into attack chains. **
|
|
188
|
+
So every audit correlates its findings into attack chains. **Nineteen named chains** are hand-modelled
|
|
154
189
|
scenarios — each with its own narrative and remediation, several naming the concrete request path an
|
|
155
190
|
attacker would use. Where no named chain explains a combination, an emergent pass reports the
|
|
156
191
|
remaining entry-point → outcome pairs as lower-confidence "potential attack paths", so a novel
|
|
@@ -159,7 +194,7 @@ combination is still surfaced.
|
|
|
159
194
|
Every chain lists the findings forming its steps, and remediating **any one step breaks the chain**.
|
|
160
195
|
A chain is reported only when every ingredient is present: a clean org produces none.
|
|
161
196
|
|
|
162
|
-
All
|
|
197
|
+
All nineteen with severities and trigger conditions: **[docs/ATTACK-CHAINS.md](docs/ATTACK-CHAINS.md)**.
|
|
163
198
|
|
|
164
199
|
## Scope & Liability
|
|
165
200
|
|
|
@@ -201,6 +236,11 @@ Each finding carries a risk weight (CRITICAL 10, HIGH 7, MEDIUM 4, LOW 1, INFO 0
|
|
|
201
236
|
`100 - (total weight / max possible weight) * 100`, capped at 0, and maps to an A–F grade — A needs
|
|
202
237
|
≥ 85 with no HIGH findings; any CRITICAL is an F.
|
|
203
238
|
|
|
239
|
+
Every report also states its **evidence coverage**: how many checks gathered evidence, out of how
|
|
240
|
+
many ran. A check the audit user could not run (missing permission, or an error) is listed by id
|
|
241
|
+
as not assessed. Its area is unknown, not clean. A run below 90% coverage cannot be graded A: it is
|
|
242
|
+
capped at B, and the report says so. Grades below A are never changed by coverage.
|
|
243
|
+
|
|
204
244
|
All weights and grade thresholds are configurable without recompiling, via
|
|
205
245
|
`--scoring-config ./my-scoring.json`. Start from [`config/scoring.sample.json`](config/scoring.sample.json),
|
|
206
246
|
which lists every valid `checkWeights` key; your config is deep-merged with the defaults, so include
|
|
@@ -208,6 +248,36 @@ only what you want to change.
|
|
|
208
248
|
|
|
209
249
|
Grade bands, the full config shape and worked examples: **[docs/SCORING.md](docs/SCORING.md)**.
|
|
210
250
|
|
|
251
|
+
### Accepting a risk
|
|
252
|
+
|
|
253
|
+
A finding you have reviewed and accepted can be waived, which takes it out of the score and out of
|
|
254
|
+
`--fail-on` until the waiver expires. Waivers live in a JSON file passed with `--waivers`, or in
|
|
255
|
+
`.sfaudit-waivers.json` in the working directory; the command always prints which file it loaded.
|
|
256
|
+
|
|
257
|
+
```json
|
|
258
|
+
{
|
|
259
|
+
"$schema": "https://raw.githubusercontent.com/cclabsnz/sf-audit-plugin/main/schemas/waivers.schema.json",
|
|
260
|
+
"waivers": [
|
|
261
|
+
{
|
|
262
|
+
"checkId": "flows-without-sharing",
|
|
263
|
+
"entity": "Order_Processor",
|
|
264
|
+
"reason": "Integration runs without user context; refactor booked for Q3",
|
|
265
|
+
"approvedBy": "security-lead",
|
|
266
|
+
"expiresAt": "2027-03-31"
|
|
267
|
+
}
|
|
268
|
+
]
|
|
269
|
+
}
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
- `entity` must equal an affected item's label exactly (case-insensitive), or the finding id for a
|
|
273
|
+
finding with no affected items. There are no wildcards. A finding is waived only when every one
|
|
274
|
+
of its affected items is covered; otherwise the covered items are annotated and it stays active.
|
|
275
|
+
- `expiresAt` is an ISO 8601 date at most 365 days out. An expired waiver stops applying and the
|
|
276
|
+
finding counts again.
|
|
277
|
+
- A CRITICAL finding is waived only when the waiver also sets `"acknowledgeCritical": true`.
|
|
278
|
+
- Waived findings are listed under Accepted Risks in the executive report, and still take part in
|
|
279
|
+
attack-chain correlation: accepting one weakness does not accept the path it forms with others.
|
|
280
|
+
|
|
211
281
|
## Other commands
|
|
212
282
|
|
|
213
283
|
Beyond the audit itself, the plugin ships five commands. Each is documented in
|
|
@@ -219,7 +289,7 @@ Beyond the audit itself, the plugin ships five commands. Each is documented in
|
|
|
219
289
|
| `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 |
|
|
220
290
|
| `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 |
|
|
221
291
|
| `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 |
|
|
222
|
-
| `sf audit apps` | Read the
|
|
292
|
+
| `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 |
|
|
223
293
|
|
|
224
294
|
To triage captured logs for abuse patterns, pair `events pull` with the companion CLI
|
|
225
295
|
**[sfelf-triage](https://github.com/cclabsnz/sfelf-triage)**, which reads this plugin's
|
|
@@ -9,34 +9,133 @@
|
|
|
9
9
|
},
|
|
10
10
|
"checkWeights": {
|
|
11
11
|
"_comment": "Override the weight for a specific check regardless of its riskLevel. To use: remove this _comment key.",
|
|
12
|
+
"agent-action-surface": 4,
|
|
13
|
+
"agent-channel-exposure": 4,
|
|
14
|
+
"agent-inventory": 4,
|
|
15
|
+
"agent-monitoring-coverage": 4,
|
|
16
|
+
"agent-outbound-actions": 4,
|
|
17
|
+
"agent-query-reach": 4,
|
|
18
|
+
"agent-user-privilege": 4,
|
|
19
|
+
"anonymous-apex-audit": 4,
|
|
20
|
+
"apex-crud-fls": 4,
|
|
21
|
+
"apex-logging": 4,
|
|
22
|
+
"apex-rest-endpoint": 4,
|
|
12
23
|
"apex-sharing": 7,
|
|
24
|
+
"api-client-permission": 4,
|
|
13
25
|
"api-limits": 4,
|
|
14
26
|
"audit-trail": 4,
|
|
27
|
+
"auth-provider-registration-handler": 4,
|
|
28
|
+
"auth-providers": 4,
|
|
29
|
+
"certificate-expiry": 4,
|
|
30
|
+
"classic-sites": 4,
|
|
15
31
|
"code-security": 4,
|
|
32
|
+
"connected-app-inactivity": 4,
|
|
33
|
+
"connected-app-scope": 4,
|
|
16
34
|
"connected-apps": 7,
|
|
35
|
+
"content-links": 4,
|
|
36
|
+
"cors-allowlist": 4,
|
|
37
|
+
"csp-trusted-sites": 4,
|
|
38
|
+
"custom-labels-credential": 4,
|
|
17
39
|
"custom-settings": 4,
|
|
40
|
+
"data-classification": 4,
|
|
41
|
+
"data-cloud-data-space-isolation": 4,
|
|
42
|
+
"data-export-access": 4,
|
|
43
|
+
"debug-log-access": 4,
|
|
44
|
+
"delegated-administration-groups": 4,
|
|
45
|
+
"delegated-authentication-exposure": 4,
|
|
46
|
+
"deployment-identity": 4,
|
|
47
|
+
"email-security": 4,
|
|
48
|
+
"encryption-coverage": 4,
|
|
49
|
+
"enhanced-domains": 4,
|
|
50
|
+
"escalation-perms": 4,
|
|
51
|
+
"event-monitoring": 4,
|
|
52
|
+
"experience-cloud-site": 4,
|
|
53
|
+
"experience-csp": 4,
|
|
54
|
+
"external-account-hierarchy-exposure": 4,
|
|
55
|
+
"external-credentials": 4,
|
|
56
|
+
"failed-login-detection": 4,
|
|
57
|
+
"field-history-tracking": 4,
|
|
18
58
|
"field-level-security": 7,
|
|
59
|
+
"flow-http-callout-credential-bypass": 4,
|
|
19
60
|
"flows-without-sharing": 7,
|
|
61
|
+
"genai-prompt-template-grounding": 4,
|
|
62
|
+
"guest-api-access": 4,
|
|
63
|
+
"guest-executable-apex": 4,
|
|
64
|
+
"guest-object-exposure": 4,
|
|
65
|
+
"guest-record-access-policy": 4,
|
|
66
|
+
"guest-site-options": 4,
|
|
67
|
+
"guest-traffic-anomaly": 4,
|
|
20
68
|
"guest-user-access": 10,
|
|
69
|
+
"guest-user-visibility": 4,
|
|
21
70
|
"hardcoded-credentials": 10,
|
|
22
71
|
"health-check": 7,
|
|
72
|
+
"high-assurance-session": 4,
|
|
23
73
|
"inactive-users": 4,
|
|
74
|
+
"inbound-email-handler-exposure": 4,
|
|
75
|
+
"installed-packages": 4,
|
|
76
|
+
"integration-least-privilege": 4,
|
|
77
|
+
"integration-users": 4,
|
|
78
|
+
"internal-user-mfa": 4,
|
|
24
79
|
"ip-restrictions": 7,
|
|
80
|
+
"legacy-api-version": 4,
|
|
81
|
+
"lightning-message-channel": 4,
|
|
82
|
+
"login-access-policy": 4,
|
|
83
|
+
"login-anomaly": 4,
|
|
25
84
|
"login-session": 4,
|
|
85
|
+
"mfa-enforcement": 4,
|
|
86
|
+
"mfa-method-strength": 4,
|
|
87
|
+
"mfa-registration": 4,
|
|
88
|
+
"my-domain-login-policy": 4,
|
|
26
89
|
"named-credentials": 1,
|
|
90
|
+
"oauth-device-and-asset-token-flows": 4,
|
|
91
|
+
"oauth-token-inventory": 4,
|
|
92
|
+
"org-wide-email-spoofing": 4,
|
|
93
|
+
"outbound-messages": 4,
|
|
94
|
+
"package-post-install-supply-chain": 4,
|
|
27
95
|
"password-session-policy": 7,
|
|
28
96
|
"permissions": 4,
|
|
97
|
+
"platform-event-subscriber-context": 4,
|
|
98
|
+
"privileged-access": 4,
|
|
99
|
+
"public-content-exposure": 4,
|
|
29
100
|
"public-group-sharing": 4,
|
|
101
|
+
"release-updates": 4,
|
|
30
102
|
"remote-sites": 4,
|
|
103
|
+
"report-folder-access": 4,
|
|
104
|
+
"restriction-rules-integrity": 4,
|
|
105
|
+
"sandbox-data-masking": 4,
|
|
31
106
|
"scheduled-apex": 1,
|
|
107
|
+
"separation-of-duties": 4,
|
|
108
|
+
"session-hardening": 4,
|
|
32
109
|
"sharing-model": 7,
|
|
33
|
-
"
|
|
110
|
+
"shield-tenant-secret-lifecycle": 4,
|
|
111
|
+
"siem-integration": 4,
|
|
112
|
+
"soap-login-api-auth": 4,
|
|
113
|
+
"sso-enforcement": 4,
|
|
114
|
+
"standard-profiles": 4,
|
|
115
|
+
"threat-detection": 4,
|
|
116
|
+
"transaction-security-policy": 4,
|
|
117
|
+
"trusted-ip-ranges": 4,
|
|
118
|
+
"trusted-url-hygiene": 4,
|
|
119
|
+
"users-and-admins": 10,
|
|
120
|
+
"visualforce-xss": 4
|
|
34
121
|
},
|
|
35
122
|
"gradeThresholds": {
|
|
36
|
-
"A": {
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
123
|
+
"A": {
|
|
124
|
+
"minScore": 85,
|
|
125
|
+
"maxHigh": 0
|
|
126
|
+
},
|
|
127
|
+
"B": {
|
|
128
|
+
"minScore": 70,
|
|
129
|
+
"maxHigh": 1
|
|
130
|
+
},
|
|
131
|
+
"C": {
|
|
132
|
+
"minScore": 55,
|
|
133
|
+
"maxHigh": 3
|
|
134
|
+
},
|
|
135
|
+
"D": {
|
|
136
|
+
"minScore": 40,
|
|
137
|
+
"maxCritical": 0
|
|
138
|
+
},
|
|
40
139
|
"F": {}
|
|
41
140
|
}
|
|
42
141
|
}
|
|
@@ -1,8 +1,14 @@
|
|
|
1
1
|
import type { AppFinding } from './types.js';
|
|
2
2
|
import type { SoqlClient } from '@cclabsnz/sf-core';
|
|
3
|
-
export
|
|
3
|
+
export interface AnalyzeAppsOptions {
|
|
4
4
|
since: number;
|
|
5
5
|
soakDays: number;
|
|
6
6
|
soapApiCsv?: string;
|
|
7
|
-
|
|
7
|
+
bulkApi2Csv?: string;
|
|
8
|
+
graphQlCsv?: string;
|
|
9
|
+
auraCsv?: string;
|
|
10
|
+
/** Why usage is known to be incomplete (e.g. some log files failed to download); suppresses revoke advice. */
|
|
11
|
+
incompleteUsage?: string;
|
|
12
|
+
}
|
|
13
|
+
export declare function analyzeApps(restApiCsv: string, soql: SoqlClient, opts: AnalyzeAppsOptions): Promise<AppFinding[]>;
|
|
8
14
|
//# sourceMappingURL=analyzeApps.d.ts.map
|
package/lib/apps/analyzeApps.js
CHANGED
|
@@ -3,7 +3,12 @@ import { resolveApps } from './appResolver.js';
|
|
|
3
3
|
import { computeGranted } from './grantedAccess.js';
|
|
4
4
|
import { buildFinding } from './leastPrivilege.js';
|
|
5
5
|
export async function analyzeApps(restApiCsv, soql, opts) {
|
|
6
|
-
const usage = collectUsage(restApiCsv,
|
|
6
|
+
const usage = collectUsage(restApiCsv, {
|
|
7
|
+
soapApiCsv: opts.soapApiCsv,
|
|
8
|
+
bulkApi2Csv: opts.bulkApi2Csv,
|
|
9
|
+
graphQlCsv: opts.graphQlCsv,
|
|
10
|
+
auraCsv: opts.auraCsv,
|
|
11
|
+
});
|
|
7
12
|
const appIds = usage.usage.map((u) => u.appId);
|
|
8
13
|
const allUsers = [...new Set(usage.usage.flatMap((u) => u.userIds))];
|
|
9
14
|
const resolved = await resolveApps(appIds, soql, allUsers);
|
|
@@ -12,7 +17,7 @@ export async function analyzeApps(restApiCsv, soql, opts) {
|
|
|
12
17
|
for (const u of usage.usage) {
|
|
13
18
|
const app = resolvedById.get(u.appId);
|
|
14
19
|
const granted = await computeGranted(u.appId, u.userIds, soql, null);
|
|
15
|
-
findings.push(buildFinding(app, u, granted, { since: opts.since, attributionRatePct: usage.attributionRatePct }, opts.soakDays));
|
|
20
|
+
findings.push(buildFinding(app, u, granted, { since: opts.since, attributionRatePct: usage.attributionRatePct }, opts.soakDays, opts.incompleteUsage));
|
|
16
21
|
}
|
|
17
22
|
return findings;
|
|
18
23
|
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { RestClient, SoqlClient } from '@cclabsnz/sf-core';
|
|
2
|
+
export declare const API_LOG_TYPES: readonly ['RestApi', 'BulkApi2', 'GraphQlQueryExecution', 'AuraRequest'];
|
|
3
|
+
export type ApiLogType = (typeof API_LOG_TYPES)[number];
|
|
4
|
+
export interface ApiLogs {
|
|
5
|
+
csv: Record<ApiLogType, string>;
|
|
6
|
+
/** Log files the query listed. */
|
|
7
|
+
listed: number;
|
|
8
|
+
/** Log files that could not be downloaded or read; their usage is missing from `csv`. */
|
|
9
|
+
failed: {
|
|
10
|
+
id: string;
|
|
11
|
+
eventType: string;
|
|
12
|
+
error: string;
|
|
13
|
+
}[];
|
|
14
|
+
}
|
|
15
|
+
/** Thrown when the EventLogFile listing itself fails: there is no usage to analyze at all. */
|
|
16
|
+
export declare class ApiLogListingError extends Error {
|
|
17
|
+
readonly permission: boolean;
|
|
18
|
+
constructor(message: string, permission: boolean);
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Lists and downloads the API EventLogFiles for the last `since` days. Read-only: one SOQL query and
|
|
22
|
+
* one REST GET per file. A failed listing throws (an empty result would read as "no usage"); a failed
|
|
23
|
+
* download is recorded in `failed` so the caller can flag the analysis as incomplete.
|
|
24
|
+
*/
|
|
25
|
+
export declare function downloadApiLogs(deps: {
|
|
26
|
+
soql: SoqlClient;
|
|
27
|
+
rest: RestClient;
|
|
28
|
+
}, since: number): Promise<ApiLogs>;
|
|
29
|
+
export interface LogCoverage {
|
|
30
|
+
/** Set when there is no usable data at all: the command must stop rather than report. */
|
|
31
|
+
fatal?: string;
|
|
32
|
+
/** Set when some files failed: the analysis runs but is flagged incomplete. */
|
|
33
|
+
incomplete?: string;
|
|
34
|
+
/** Informational: the window simply had no API logs. */
|
|
35
|
+
empty?: string;
|
|
36
|
+
}
|
|
37
|
+
/** Decides whether downloaded logs are complete, partial, or unusable. Never treats a failure as "no usage". */
|
|
38
|
+
export declare function assessLogCoverage(logs: ApiLogs, since: number): LogCoverage;
|
|
39
|
+
//# sourceMappingURL=apiLogSource.d.ts.map
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
|
2
|
+
import { tmpdir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
export const API_LOG_TYPES = ['RestApi', 'BulkApi2', 'GraphQlQueryExecution', 'AuraRequest'];
|
|
5
|
+
/** Thrown when the EventLogFile listing itself fails: there is no usage to analyze at all. */
|
|
6
|
+
export class ApiLogListingError extends Error {
|
|
7
|
+
permission;
|
|
8
|
+
constructor(message, permission) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.permission = permission;
|
|
11
|
+
this.name = 'ApiLogListingError';
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Lists and downloads the API EventLogFiles for the last `since` days. Read-only: one SOQL query and
|
|
16
|
+
* one REST GET per file. A failed listing throws (an empty result would read as "no usage"); a failed
|
|
17
|
+
* download is recorded in `failed` so the caller can flag the analysis as incomplete.
|
|
18
|
+
*/
|
|
19
|
+
export async function downloadApiLogs(deps, since) {
|
|
20
|
+
const csv = { RestApi: '', BulkApi2: '', GraphQlQueryExecution: '', AuraRequest: '' };
|
|
21
|
+
let rows;
|
|
22
|
+
try {
|
|
23
|
+
rows = await deps.soql.queryAll(`SELECT Id, EventType FROM EventLogFile WHERE EventType IN (${API_LOG_TYPES.map((t) => `'${t}'`).join(', ')}) ` +
|
|
24
|
+
`AND LogDate = LAST_N_DAYS:${since} ORDER BY LogDate DESC`);
|
|
25
|
+
}
|
|
26
|
+
catch (e) {
|
|
27
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
28
|
+
const permission = /INSUFFICIENT_ACCESS|HTTP 403|INVALID_TYPE|not supported/i.test(msg);
|
|
29
|
+
throw new ApiLogListingError(permission
|
|
30
|
+
? `Cannot list API event logs: EventLogFile is not readable (the running user needs View Event Log Files, and the org needs Event Monitoring). ${msg}`
|
|
31
|
+
: `Cannot list API event logs: ${msg}`, permission);
|
|
32
|
+
}
|
|
33
|
+
const failed = [];
|
|
34
|
+
if (rows.length === 0)
|
|
35
|
+
return { csv, listed: 0, failed };
|
|
36
|
+
// A private (0700) temp dir: raw logs hold org data and must not sit at a predictable shared path.
|
|
37
|
+
const dir = mkdtempSync(join(tmpdir(), 'sfaudit-apps-'));
|
|
38
|
+
try {
|
|
39
|
+
for (const r of rows) {
|
|
40
|
+
const tmp = join(dir, `${r.Id}.csv`);
|
|
41
|
+
try {
|
|
42
|
+
await deps.rest.getRawToFile(`/sobjects/EventLogFile/${r.Id}/LogFile`, tmp);
|
|
43
|
+
const content = readFileSync(tmp, 'utf-8');
|
|
44
|
+
if (API_LOG_TYPES.includes(r.EventType)) {
|
|
45
|
+
csv[r.EventType] += '\n' + content;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
catch (e) {
|
|
49
|
+
failed.push({ id: r.Id, eventType: r.EventType, error: e instanceof Error ? e.message : String(e) });
|
|
50
|
+
}
|
|
51
|
+
finally {
|
|
52
|
+
rmSync(tmp, { force: true });
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
finally {
|
|
57
|
+
rmSync(dir, { recursive: true, force: true });
|
|
58
|
+
}
|
|
59
|
+
return { csv, listed: rows.length, failed };
|
|
60
|
+
}
|
|
61
|
+
/** Decides whether downloaded logs are complete, partial, or unusable. Never treats a failure as "no usage". */
|
|
62
|
+
export function assessLogCoverage(logs, since) {
|
|
63
|
+
if (logs.listed === 0)
|
|
64
|
+
return { empty: `No API EventLogFiles in the last ${since} day(s): there is no usage to compare against grants.` };
|
|
65
|
+
if (logs.failed.length === logs.listed) {
|
|
66
|
+
return {
|
|
67
|
+
fatal: `None of the ${logs.listed} API log file(s) could be downloaded (first error: ${logs.failed[0].error}). ` +
|
|
68
|
+
'Refusing to report usage from no data.',
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
if (logs.failed.length > 0)
|
|
72
|
+
return { incomplete: `${logs.failed.length} of ${logs.listed} API log file(s) could not be downloaded` };
|
|
73
|
+
return {};
|
|
74
|
+
}
|
|
75
|
+
//# sourceMappingURL=apiLogSource.js.map
|