Skip to content

Commit ef5a7fb

Browse files
authored
Fail on existing alerts under --strict-blocking, streamline exit code behavior (#453)
* List each finding once under --strict-blocking create_new_diff built the unchanged package set by filtering packages keyed by type/purl against added and removed packages keyed by artifact ID. The keys never matched, so every added package was also treated as unchanged, and under --strict-blocking its alerts were reported twice: once as new and once as existing. Against an empty baseline that doubled every finding in JSON, SARIF, Slack and GitLab output, and inflated the "EXISTING blocking issues" count in the summary and GitLab commit status. The exit code was not affected. Unchanged packages are now selected and keyed by artifact ID, which also lets transitive unchanged alerts resolve their introducing package. select_diff_alerts additionally skips an unchanged alert already listed as new, matching on purl and alert type like the rest of the diff. Bumps the version to 2.12.2. * Include the ecosystem in the strict-blocking dedupe key Issue.purl holds only name and version, so an npm and a PyPI package can share it. Keying the dedupe on purl and alert type alone would hide an existing PyPI alert behind a new npm alert with the same name, version and type. The regression tests now run Core.create_new_diff with the scan upload mocked out, instead of repeating its package assembly, so they fail if create_new_diff goes back to filtering unchanged packages by purl key. * Decide exit codes in one place so the exit flags apply to every run Failures that are not security findings now raise InfrastructureError instead of calling sys.exit, and cli() maps them through --disable-blocking and --exit-code-on-api-error. Before, a missing API or SCM token, missing reachability dependencies, an ineligible plan, a failed repository create and a failed reachability run each exited with a hard-coded 2 or 3 that ignored both flags. - Invalid flags and config values exit 2, the code argparse already uses for its own usage errors, instead of 1, which means blocking findings. --disable-blocking does not apply to them. - Ctrl+C exits 130 instead of 2, so it no longer shares a code with usage errors. - A diff scan the API marks incomplete fails as an infrastructure error instead of reporting a result that may be missing alerts. It does not fall back to the streaming comparison, which reads the same scans. - A repository lookup that fails with 401 or 403 is reported as a missing repo:list scope instead of being treated as a missing repository and ending in a repo:create failure. * Keep each advisory when collapsing repeat alerts The diff collapsed alerts on (purl, alert type) so a package pulled in by several manifests reports each finding once. Every CVE of one severity on a package shares an alert type, so a package's second advisory was dropped from every output, and a blocking advisory could be dropped behind a warning on the same package, letting the run pass. Alerts now collapse on Issue.consolidation_key, which adds the ecosystem and the GHSA or CVE ID. The PR comment shows that ID next to the title, so two advisories on one package no longer render as identical rows. * Report existing alerts from the full scan, and list them in the PR comment The cached diff-scans endpoint returns unchanged artifacts with no alerts, so --strict-blocking had nothing to block on and passed runs with blocking alerts on packages the change didn't touch. The GitLab security report and FOSSA-format output, which list every current finding, missed the same alerts. When one of those outputs is enabled, the CLI now reads the alerts on unchanged packages from the new full scan. It skips that request when the comparison already carries them, as the streaming fallback does, and fails the run if the request fails rather than reporting no existing alerts. Under --strict-blocking the PR comment lists existing alerts in their own table after the new ones, blocking first, and stops adding rows before the comment reaches GitHub's size limit. Ignore comments apply to existing alerts too, since they now fail the run and each row offers the command. * Release 2.13.0 with upgrade notes for the exit-code changes Bumps the minor version because exit codes change: invalid flags exit 2 instead of 1, Ctrl+C exits 130 instead of 2, more failures honor --disable-blocking and --exit-code-on-api-error, and --strict-blocking now fails on existing blocking alerts. The CHANGELOG lists each change a CI step matching on exit codes needs to know about, and the README exit-code table and the --disable-blocking and --strict-blocking docs describe the new behavior. * Group the 2.13.0 changelog entry by change type, like 2.12.0 * Keep each CVE apart in GitLab reports, and group existing license alerts GitLab finding IDs were built from package, alert type and severity, so two CVEs of one severity on a package shared an ID and the report kept only one. The ID now includes the advisory ID when the alert has one; other findings keep the IDs GitLab already tracks them by. A repeated ID is skipped, since GitLab expects each finding once per report. In the PR comment's existing-alerts table, license policy violations are grouped per package with the license row, as in the new-alerts table, instead of rendering as security findings with a malware link. The 2.13.0 changelog entry is cut to short bullets of observable behavior. * Fail on missing existing alerts and preserve distinct findings * Document exit-code migration and CI failure policies * Audit CLI exit policy and validate configuration before setup * Document and test advisory identity boundaries * Document the repository lookup failures and the full-scan read Troubleshooting now shows the two messages a missing repository scope produces in 2.13.0, which scope each one points at, and that both follow the exit-code flags. It also says full-scans:list covers the full-scan read that --strict-blocking, --enable-gitlab-security and --legal-format fossa use for alerts on unchanged packages.
1 parent 5bb64de commit ef5a7fb

31 files changed

Lines changed: 2228 additions & 363 deletions

‎CHANGELOG.md‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,46 @@
11
# Changelog
22

3+
## 2.13.0
4+
5+
### Upgrade notes
6+
7+
Exit codes change in this release. Check any CI step that matches on a specific
8+
code; see [Exit codes](README.md#exit-codes).
9+
10+
- Invalid flags exit `2` instead of `1`. `--disable-blocking` doesn't apply to
11+
them.
12+
- Ctrl+C exits `130` instead of `2`.
13+
- Missing tokens and other setup failures now honor `--disable-blocking` and
14+
`--exit-code-on-api-error`.
15+
- `--strict-blocking` now fails on existing blocking alerts.
16+
- Config-file booleans, integers and choices are validated before scan setup.
17+
18+
### Added
19+
20+
- Under `--strict-blocking`, PR/MR comments list existing alerts in their own
21+
table.
22+
23+
### Changed
24+
25+
- Incomplete scan comparisons or existing-alert results fail the run with the
26+
infrastructure-error code.
27+
- GitLab security report IDs include the ecosystem, full package coordinate and
28+
advisory ID, so existing findings get new IDs once.
29+
30+
### Fixed
31+
32+
- `--strict-blocking`, the GitLab security report and FOSSA output include
33+
alerts on unchanged packages.
34+
- `--strict-blocking` no longer lists findings on added packages twice.
35+
- Every CVE on a package is reported, not one per severity.
36+
- GitLab reports keep findings from different ecosystems and namespaces separate.
37+
- PR/MR comments group existing license violations and retain warnings about
38+
omitted findings after individual ignores.
39+
- Invalid file lists and unreadable config files exit with the usage-error code.
40+
- Exit-code flags retain their startup values if the config file changes during a run.
41+
- A token without `repo:list` is reported as a missing scope, not a missing
42+
repository. Only a missing repository triggers a create request.
43+
344
## 2.12.2
445

546
### Changed: bump pinned Coana CLI to 15.15.2

‎README.md‎

Lines changed: 34 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -217,12 +217,13 @@ Minimal pattern:
217217
218218
## Exit codes
219219
220-
| Code | Meaning |
221-
|------|---------|
222-
| `0` | Clean scan — no blocking issues (or `--disable-blocking` set) |
223-
| `1` | Blocking security finding(s) detected |
224-
| `2` | Scan interrupted (SIGINT / Ctrl+C) |
225-
| `3` | Infrastructure or API error (timeout, network failure, unexpected error) |
220+
| Code | Meaning |
221+
|-------|---------|
222+
| `0` | Successful report, skipped SCM event, or `--disable-blocking` set; findings gate only evaluated diffs |
223+
| `1` | Blocking security finding(s) detected |
224+
| `2` | Invalid flags or configuration (usage error), including argparse's own errors |
225+
| `3` | Infrastructure or API error: missing API or SCM token, permission or plan problem, timeout, network failure, incomplete scan comparison, unexpected error |
226+
| `130` | Scan interrupted (SIGINT / Ctrl+C) |
226227

227228
`--exit-code-on-api-error <N>` remaps the infrastructure-error code (`3`) to any
228229
value — e.g. a Buildkite
@@ -239,12 +240,12 @@ error, so the supervisor's exit status (commonly 124 or 137) takes precedence.
239240
The two flags that affect exit codes can cancel each other out, so the order of
240241
precedence matters:
241242

242-
- **`--disable-blocking` wins over everything.** It forces exit `0` for *all*
243-
outcomes — security findings *and* infrastructure errors. If you set it,
244-
`--exit-code-on-api-error` has no effect (you'll always get `0`).
243+
- **`--disable-blocking` forces exit `0` for findings, infrastructure errors and
244+
interrupts.** It takes precedence over `--exit-code-on-api-error` and
245+
`--strict-blocking`. Usage errors still exit `2`.
245246
- **`--exit-code-on-api-error` only applies when `--disable-blocking` is *not*
246-
set.** It changes the infra-error code (and the generic-error code); it never
247-
touches the security-finding code (`1`).
247+
set.** It changes the infrastructure-error code, including unexpected runtime
248+
failures. Findings (`1`), usage errors (`2`) and Ctrl+C (`130`) keep their codes.
248249

249250
So for the common "don't let Socket outages block my pipeline, but still fail on
250251
real findings" goal, use `--exit-code-on-api-error` **without** `--disable-blocking`:
@@ -263,6 +264,28 @@ scan exit `0` on *both* findings and outages — the `soft_fail: 100` rule would
263264
never match, and real findings would stop blocking. That's usually not what you
264265
want.
265266

267+
### Upgrading to 2.13.0
268+
269+
Update pipeline rules and wrapper scripts that match specific exit codes:
270+
271+
| Outcome | Before 2.13.0 | From 2.13.0 |
272+
|---------|---------------|-------------|
273+
| Invalid flags or configuration | CLI validation: `1`; argparse: `2` | `2` for both; never suppressed by `--disable-blocking` |
274+
| Ctrl+C | `2` | `130`, or `0` with `--disable-blocking` |
275+
| Missing token or other setup failure | Fixed `2` or `3`, depending on the failure | Infrastructure-error code (`3` by default); both exit-code flags now apply |
276+
277+
Blocking findings still exit `1`. With `--strict-blocking`, existing blocking
278+
alerts can now fail jobs that previously passed. GitLab report findings also get
279+
new IDs once; see the [release notes](CHANGELOG.md#2130).
280+
281+
Configuration is validated before credentials or network setup. Use native
282+
JSON/TOML booleans such as `false`, a positive integer `timeout`, and an array of
283+
file paths for `files`. Invalid or unreadable configuration exits `2` even when
284+
credentials are missing or blocking is disabled.
285+
286+
For a compact comparison of failure-handling policies, see
287+
[Exit codes in CI](docs/ci-cd.md#exit-codes-in-ci).
288+
266289
## Common gotchas
267290

268291
See [`docs/troubleshooting.md`](https://github.com/SocketDev/socket-python-cli/blob/main/docs/troubleshooting.md#common-gotchas).

‎docs/ci-cd.md‎

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,44 @@ steps:
5252
- "results.sarif"
5353
```
5454
55+
## Exit codes in CI
56+
57+
Choose which outcomes may leave your scan step green. The values below are the
58+
CLI's exit status; CI cancellation and external timeouts can have their own status.
59+
60+
| Outcome | Default | `--exit-code-on-api-error 100` | `--disable-blocking` |
61+
|---------|---------|--------------------------------|----------------------|
62+
| No blocking findings | `0` | `0` | `0` |
63+
| Blocking findings | `1` | `1` | `0` |
64+
| Invalid flags or configuration | `2` | `2` | `2` |
65+
| Setup, API or runtime failure | `3` | `100` | `0` |
66+
| Ctrl+C handled by the CLI | `130` | `130` | `0` |
67+
68+
Use a custom infrastructure code with your CI provider's exit-code allowlist; the
69+
[Buildkite example](../README.md#how-these-options-interact) shows this pattern.
70+
For providers without that feature, remap infrastructure errors to `0`:
71+
72+
```bash
73+
# Keep findings blocking; allow setup/API failures to pass.
74+
socketcli --config .socketcli.toml --exit-code-on-api-error 0
75+
76+
# Report-only mode: findings, infrastructure failures and Ctrl+C exit 0.
77+
# Invalid flags/configuration still exit 2.
78+
socketcli --config .socketcli.toml --disable-blocking
79+
```
80+
81+
Combining the flags gives `--disable-blocking` precedence. Avoid blanket shell
82+
`|| true` or job-wide `continue-on-error` when only API failures should be allowed:
83+
they also hide findings and usage errors. Even with exit `0`, a setup/API failure
84+
does not mean a clean scan; check the logs for a completed report.
85+
86+
Findings block only when a [diff comparison runs](#scan-type-by-pipeline).
87+
SCM event filters can also skip unsupported events with exit `0`; confirm a report
88+
was created when validating a new workflow.
89+
`--strict-blocking` also checks existing blocking alerts; an incomplete comparison
90+
or incomplete existing-alert data is an infrastructure failure. See the
91+
[2.13.0 migration table](../README.md#upgrading-to-2130) when updating existing CI rules.
92+
5593
## Config file usage in CI
5694

5795
Use `--config .socketcli.toml` or `--config .socketcli.json` to keep pipeline commands small.
@@ -465,7 +503,7 @@ With `--scm github` or `--scm gitlab`, the detected event decides the scan type:
465503

466504
| Event | Scan | Blocks the build |
467505
|:------|:-----|:-----------------|
468-
| Pull request / merge request | Diff scan against the repository's baseline | Yes, on newly introduced alerts |
506+
| Pull request / merge request | Diff scan against the repository's baseline | Yes, on new blocking alerts; also existing blockers with `--strict-blocking` |
469507
| Any other pipeline, including default-branch pushes | Full scan | No |
470508

471509
A full scan has no baseline, so it cannot tell a newly introduced alert from one

‎docs/cli-reference.md‎

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -358,7 +358,7 @@ If you don't want to provide the Socket API Token every time then you can use th
358358
359359
**Reachability Analysis Requirements:**
360360
361-
The Python CLI verifies the following **up front** (before invoking the analysis engine) and exits with code **3** if any are unmet:
361+
The Python CLI verifies the following **up front** (before invoking the analysis engine). Missing requirements use the infrastructure-error code (`3` by default), subject to `--exit-code-on-api-error` and `--disable-blocking`:
362362
- `node` - Required to run the analysis engine (the Coana CLI). The engine needs Node.js 22.13 or later.
363363
- `uv` - Required by the analysis engine
364364
- An **Enterprise** Socket organization plan (any `enterprise*` plan, including Enterprise trials)
@@ -372,7 +372,7 @@ Separately, the analysis engine (coana) needs the **per-ecosystem build toolchai
372372
| Host | Used for | If blocked |
373373
|---|---|---|
374374
| `api.socket.dev` | Socket API calls, and a signed URL for the engine download | The CLI fails |
375-
| `storage.googleapis.com` | Downloading the engine and its analyzers (about 120 MB) | The CLI exits with code **3**: `Failed to run reachability analysis: HTTPSConnectionPool(host='storage.googleapis.com', ...)` |
375+
| `storage.googleapis.com` | Downloading the engine and its analyzers (about 120 MB) | The CLI reports an infrastructure error (`3` by default, subject to the exit-code flags): `Failed to run reachability analysis: HTTPSConnectionPool(host='storage.googleapis.com', ...)` |
376376
| The package registry of each scanned ecosystem, for example `registry.npmjs.org` | Installing your project's dependencies for analysis | The scan still completes, but the affected vulnerabilities are reported as `INSTALL ERROR` with no reachability result |
377377
378378
The engine comes from Socket, not npm, so an npm mirror or registry proxy does not cover the engine download. The registry row does not apply when your dependencies are already installed in the target path, for example a `node_modules` directory from an earlier `npm ci`. The engine is cached as described below; with a warm cache, `storage.googleapis.com` is not contacted.
@@ -389,6 +389,13 @@ Socket's reachability analysis comes in three forms, referred to by their full n
389389
390390
## Config file support
391391
392+
Values are validated after CLI overrides and before scan setup. Boolean options
393+
use native JSON/TOML booleans; integer options use integers, with `timeout` greater
394+
than zero. `files` accepts an array of nonempty file paths, or its JSON string
395+
representation. Invalid values and unreadable config files exit `2`, including
396+
with `--disable-blocking`. Runtime exit policy uses the configuration loaded at
397+
startup; changing or removing the file during a run does not change its exit code.
398+
392399
Use `--config <path>` to load defaults from a `.toml` or `.json` file.
393400
CLI arguments always take precedence over config file values.
394401
@@ -430,20 +437,23 @@ Sample config files:
430437
### CI/CD usage tips
431438
432439
For CI-specific examples and guidance, see [`ci-cd.md`](ci-cd.md).
440+
Exit statuses and flag precedence are listed in [Exit codes](../README.md#exit-codes),
441+
with pipeline examples in [Exit codes in CI](ci-cd.md#exit-codes-in-ci).
433442
434443
The CLI runs a pinned version of the Coana CLI, the analysis engine; it does **not** auto-update the engine. It downloads the engine from the Socket API on first use and keeps it in `$XDG_CACHE_HOME/socket/coana/v1` (`~/.cache/socket/coana/v1` when `XDG_CACHE_HOME` is unset). Pass `--reach-version latest` to opt into the newest published version. Use `--reach` to enable reachability analysis during a full scan, or add `--only-facts-file` (with `--reach`) to submit only the reachability facts file (`.socket.facts.json`) when creating the full scan.
435444
436445
#### Advanced Configuration
437446
| Parameter | Required | Default | Description |
438447
|:-------------------------|:---------|:--------|:----------------------------------------------------------------------|
439448
| `--ignore-commit-files` | False | False | Compare regardless of which files changed, scanning every manifest |
440-
| `--disable-blocking` | False | False | Non-blocking CI mode: the CLI always exits **0**, even when blocking alerts are present (including with `--strict-blocking`). Also exits 0 on uncaught runtime errors and Socket API failures, so the job is treated as successful while findings and errors are still logged. Takes precedence over `--strict-blocking`. |
449+
| `--exit-code-on-api-error` | False | 3 | Remap infrastructure failures, including missing tokens, setup failures, incomplete scan data and unexpected runtime errors. Findings (`1`), usage errors (`2`) and Ctrl+C (`130`) are unaffected. `--disable-blocking` takes precedence. |
450+
| `--disable-blocking` | False | False | Non-blocking CI mode: the CLI exits **0** even when blocking alerts are present (including with `--strict-blocking`). Also exits 0 on infrastructure errors (missing API or SCM token, Socket API failures, uncaught runtime errors) and interrupts, so the job is treated as successful while findings and errors are still logged. Invalid flags still exit **2**. Takes precedence over `--strict-blocking`. |
441451
| `--disable-ignore` | False | False | Disable support for `@SocketSecurity ignore` commands in PR comments. When set, alerts cannot be suppressed via comments and ignore instructions are hidden from comment output. See [Who can ignore an alert](#who-can-ignore-an-alert). |
442452
| `--ignore-authorization` | False | enforce | Who may suppress alerts with `@SocketSecurity ignore`. `enforce` requires write access and honors the command with a warning when the provider cannot report it; `strict` rejects it in that case; `off` honors any commenter. See [Who can ignore an alert](#who-can-ignore-an-alert). |
443453
| `--strict-blocking` | False | False | Fail on ANY security policy violations (blocking severity), not just new ones. Only works in diff mode. See [Strict Blocking Mode](#strict-blocking-mode) for details. |
444454
| `--enable-diff` | False | False | Enable diff mode even when using `--integration api` (forces diff mode without SCM integration) |
445455
| `--scm` | False | api | Source control management type |
446-
| `--timeout` | False | 1200 | Timeout in seconds for each API request. This is not a total CLI runtime limit and does not limit local discovery, Git, or reachability analysis. |
456+
| `--timeout` | False | 1200 | Positive integer timeout in seconds for each API request. This is not a total CLI runtime limit and does not limit local discovery, Git, or reachability analysis. |
447457
448458
#### Plugins
449459
@@ -641,8 +651,10 @@ Security issues detected by Socket Security:
641651
642652
### Important Notes
643653
644-
- **Diff Mode Only**: The flag only works in diff mode (with SCM integration). In API mode, a warning is logged.
654+
- **Diff Mode Only**: The flag applies when a scan comparison runs, with or without SCM integration. A full scan logs a warning and does not evaluate existing violations; see [Scan type by pipeline](ci-cd.md#scan-type-by-pipeline).
645655
- **Error-Level Only**: Only fails on `error=True` alerts (blocking severity), not warnings.
656+
- **Existing alerts come from the full scan**: The scan comparison doesn't carry alerts on unchanged packages, so the CLI reads them from the new full scan, at the cost of one more API request per run. If that request fails or omits an unchanged package, the run fails with the infrastructure-error code rather than passing without them.
657+
- **PR/MR comments**: Existing alerts are listed in their own table after the new ones, blocking first, with license violations grouped per package. `@SocketSecurity ignore` applies to them too. Very large sets are cut off before the comment reaches GitHub's size limit, with a link to the full report. Ignoring every displayed alert preserves the warning about omitted findings; `ignore-all` also clears omitted findings.
646658
- **Priority**: `--disable-blocking` takes precedence - if both flags are set, the build will always pass.
647659
- **First Scan**: On the very first scan of a repository, there are no "existing" violations, so behavior is identical to standard mode.
648660
@@ -881,9 +893,16 @@ The GitLab Security Dashboard report and the JSON/SARIF diff outputs use differe
881893
882894
### Alert Ignoring via PR/MR Comments
883895
884-
When using the CLI with SCM integration (`--scm github` or `--scm gitlab`), users can ignore specific alerts by reacting to Socket's PR/MR comments. Ignored alerts are removed from `--enable-json`, `--enable-sarif`, and console output.
896+
In SCM diff mode (`--scm github` or `--scm gitlab`), an authorized
897+
`@SocketSecurity ignore <ecosystem>/<package>@<version>` or
898+
`@SocketSecurity ignore-all` comment removes matching new alerts from the CLI's
899+
reports, including the GitLab report. With `--strict-blocking`, it also removes
900+
matching existing alerts from blocking checks and reports. Without strict blocking,
901+
the GitLab report still includes existing findings.
885902
886-
However, the GitLab Security Dashboard report includes **all** alerts matching your security policy (new and existing), regardless of comment-based ignores. This ensures the Security Dashboard always reflects the full set of known issues. To suppress a vulnerability from the GitLab report, adjust the alert's policy in Socket's dashboard rather than ignoring it via a PR comment.
903+
`--disable-ignore` disables these commands. See [Who can ignore an alert](#who-can-ignore-an-alert)
904+
for authorization rules. To suppress a finding across future PRs, update its policy
905+
or triage state in Socket's dashboard.
887906
888907
### Report Schema
889908
@@ -900,6 +919,10 @@ Socket CLI generates reports compliant with [GitLab Dependency Scanning schema v
900919
901920
**Schema compatibility:** The v15.0.0 schema is supported across all GitLab versions 12.0+ (both self-hosted and cloud). The report includes the `dependency_files` field, which is required by v15.0.0 and accepted as an optional extra by newer schema versions, ensuring maximum compatibility across GitLab instances.
902921
922+
Finding IDs distinguish the ecosystem, full package coordinate and advisory, so
923+
different namespaces or CVEs remain separate findings. Upgrading to 2.13.0 changes
924+
existing finding IDs once; GitLab may show them as newly detected on the first report.
925+
903926
### Performance Notes
904927
905928
When `--enable-gitlab-security` (or `--enable-json` / `--enable-sarif`) is used with a full scan (non-diff mode), the CLI fetches package and alert data from the scan results to populate the report. This adds time proportional to the number of packages in the scan. Without these output flags, no additional data is fetched and scan performance is unchanged.

‎docs/development.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,12 @@ Run tests:
4040
make test
4141
```
4242

43+
This runs both the unit and core suites. To focus on the CLI exit-code contract:
44+
45+
```bash
46+
uv run pytest tests/core/test_cli_exit_contract.py tests/core/test_exit_codes.py
47+
```
48+
4349
Run lint/format checks:
4450

4551
```bash

0 commit comments

Comments
 (0)