Skip to content

Commit 766e50b

Browse files
committed
Audit CLI exit policy and validate configuration before setup
1 parent 5a6a3f8 commit 766e50b

14 files changed

Lines changed: 435 additions & 78 deletions

‎CHANGELOG.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ code; see [Exit codes](README.md#exit-codes).
1313
- Missing tokens and other setup failures now honor `--disable-blocking` and
1414
`--exit-code-on-api-error`.
1515
- `--strict-blocking` now fails on existing blocking alerts.
16+
- Config-file booleans, integers and choices are validated before scan setup.
1617

1718
### Added
1819

@@ -35,8 +36,10 @@ code; see [Exit codes](README.md#exit-codes).
3536
- GitLab reports keep findings from different ecosystems and namespaces separate.
3637
- PR/MR comments group existing license violations and retain warnings about
3738
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.
3841
- A token without `repo:list` is reported as a missing scope, not a missing
39-
repository.
42+
repository. Only a missing repository triggers a create request.
4043

4144
## 2.12.1
4245

‎README.md‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,7 @@ Minimal pattern:
219219
220220
| Code | Meaning |
221221
|-------|---------|
222-
| `0` | Clean scan — no blocking issues (or `--disable-blocking` set) |
222+
| `0` | Successful report, skipped SCM event, or `--disable-blocking` set; findings gate only evaluated diffs |
223223
| `1` | Blocking security finding(s) detected |
224224
| `2` | Invalid flags or configuration (usage error), including argparse's own errors |
225225
| `3` | Infrastructure or API error: missing API or SCM token, permission or plan problem, timeout, network failure, incomplete scan comparison, unexpected error |
@@ -278,6 +278,11 @@ Blocking findings still exit `1`. With `--strict-blocking`, existing blocking
278278
alerts can now fail jobs that previously passed. GitLab report findings also get
279279
new IDs once; see the [release notes](CHANGELOG.md#2130).
280280

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+
281286
For a compact comparison of failure-handling policies, see
282287
[Exit codes in CI](docs/ci-cd.md#exit-codes-in-ci).
283288

‎docs/ci-cd.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,8 @@ they also hide findings and usage errors. Even with exit `0`, a setup/API failur
8484
does not mean a clean scan; check the logs for a completed report.
8585

8686
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.
8789
`--strict-blocking` also checks existing blocking alerts; an incomplete comparison
8890
or incomplete existing-alert data is an infrastructure failure. See the
8991
[2.13.0 migration table](../README.md#upgrading-to-2130) when updating existing CI rules.

‎docs/cli-reference.md‎

Lines changed: 10 additions & 3 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
@@ -446,7 +453,7 @@ The CLI runs a pinned version of the Coana CLI, the analysis engine; it does **n
446453
| `--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. |
447454
| `--enable-diff` | False | False | Enable diff mode even when using `--integration api` (forces diff mode without SCM integration) |
448455
| `--scm` | False | api | Source control management type |
449-
| `--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. |
450457
451458
#### Plugins
452459

‎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

‎docs/troubleshooting.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
| Symptom | What to check |
66
|---------|---------------|
7-
| Exit `2`, even with `--disable-blocking` | Fix the flags or configuration reported in the logs. Usage errors are never suppressed. |
7+
| Exit `2`, even with `--disable-blocking` | Fix the flags or configuration reported in the logs. Check config-file readability, native boolean/integer values, a positive timeout and the `files` array. Usage errors are never suppressed. |
88
| Exit `3` with no reported findings | Check tokens, scopes, baseline lookup and scan-completeness errors. This is a failed evaluation; `--exit-code-on-api-error` can remap its code. |
99
| Ctrl+C is treated as a configuration error | Update wrapper/CI rules: Ctrl+C changed from `2` to `130` in 2.13.0. |
1010
| Exit `0` despite expected blockers | Check `--disable-blocking`, remapping to `0`, and whether the run produced a full scan instead of a diff. Full scans do not gate on findings. |

‎pytest.ini‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
[pytest]
2-
testpaths = tests/unit
2+
testpaths = tests/unit tests/core
33
; addopts = -vv --no-cov --tb=short -ra
44
addopts = -vv --tb=short -ra --cov=socketsecurity --cov-report=term-missing
55
python_files = test_*.py

‎socketsecurity/config.py‎

Lines changed: 64 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -75,17 +75,41 @@ def load_cli_config_file(config_path: str) -> dict:
7575
_usage_error("--config must be a .json or .toml file")
7676
except FileNotFoundError:
7777
_usage_error(f"Config file not found: {config_path}")
78-
except (json.JSONDecodeError, tomllib.TOMLDecodeError) as e:
78+
except (json.JSONDecodeError, tomllib.TOMLDecodeError, UnicodeDecodeError) as e:
7979
_usage_error(f"Invalid config file format: {e}")
80+
except OSError as e:
81+
_usage_error(f"Unable to read config file {config_path}: {e}")
8082

8183
if not isinstance(data, dict):
8284
_usage_error("Config file must contain a top-level object/table")
8385

8486
scoped = data.get("socketcli")
87+
if "socketcli" in data and not isinstance(scoped, dict):
88+
_usage_error("The socketcli config section must be an object/table")
8589
if isinstance(scoped, dict):
8690
return scoped
8791
return data
8892

93+
94+
def parse_files(value) -> List[str]:
95+
"""Read CLI/config file lists before credentials or scan setup are evaluated."""
96+
if isinstance(value, str):
97+
encoded = value.strip()
98+
if len(encoded) >= 2 and encoded[0] == encoded[-1] and encoded[0] in ("'", '"'):
99+
inner = encoded[1:-1]
100+
if inner.startswith("[") and inner.endswith("]"):
101+
encoded = inner
102+
try:
103+
value = json.loads(encoded)
104+
except json.JSONDecodeError:
105+
try:
106+
value = json.loads(encoded.replace("'", '"'))
107+
except json.JSONDecodeError:
108+
_usage_error("--files must be a JSON array of file paths")
109+
if not isinstance(value, list) or any(not isinstance(path, str) or not path.strip() for path in value):
110+
_usage_error("--files must be a JSON array of nonempty file paths")
111+
return value
112+
89113
def normalize_exclude_paths(value) -> Optional[List[str]]:
90114
"""Normalize a --exclude-paths value into a clean list of patterns.
91115
@@ -238,6 +262,13 @@ def __post_init__(self):
238262

239263
@classmethod
240264
def from_args(cls, args_list: Optional[List[str]] = None) -> 'CliConfig':
265+
try:
266+
return cls._from_args(args_list)
267+
except (TypeError, ValueError, AttributeError) as error:
268+
_usage_error(f"Invalid CLI configuration: {error}")
269+
270+
@classmethod
271+
def _from_args(cls, args_list: Optional[List[str]] = None) -> 'CliConfig':
241272
parser = create_argument_parser()
242273

243274
pre_parser = argparse.ArgumentParser(add_help=False)
@@ -255,6 +286,23 @@ def from_args(cls, args_list: Optional[List[str]] = None) -> 'CliConfig':
255286
parser.set_defaults(**normalized_defaults)
256287

257288
args = parser.parse_args(args_list)
289+
# argparse validates explicit flags, but typed JSON/TOML defaults bypass
290+
# some checks (notably booleans and choices). Validate effective values
291+
# after CLI overrides, so a string "false" cannot enable nonblocking mode.
292+
for action in parser._actions:
293+
value = getattr(args, action.dest, None)
294+
if value is None:
295+
continue
296+
option = action.option_strings[0] if action.option_strings else action.dest
297+
if isinstance(action, (argparse._StoreTrueAction, argparse._StoreFalseAction)) and not isinstance(value, bool):
298+
parser.error(f"{option} must be a boolean")
299+
if action.type is int and (not isinstance(value, int) or isinstance(value, bool)):
300+
parser.error(f"{option} must be an integer")
301+
if action.choices is not None and value not in action.choices:
302+
parser.error(f"{option}: invalid choice: {value!r}")
303+
parse_files(args.files)
304+
if args.timeout is not None and args.timeout <= 0:
305+
parser.error("--timeout must be greater than zero")
258306
integration_explicit = hasattr(args, "integration")
259307
pr_number_explicit = hasattr(args, "pr_number")
260308

@@ -418,6 +466,10 @@ def from_args(cls, args_list: Optional[List[str]] = None) -> 'CliConfig':
418466
_usage_error(f"Unable to parse excluded_ecosystems: {excluded_ecosystems}")
419467
else:
420468
_usage_error(f"Unable to parse excluded_ecosystems: {excluded_ecosystems}")
469+
if not isinstance(config_args["excluded_ecosystems"], list) or any(
470+
not isinstance(ecosystem, str) for ecosystem in config_args["excluded_ecosystems"]
471+
):
472+
_usage_error("--excluded-ecosystems must be an array of ecosystem names")
421473
# Build Slack plugin config, merging CLI arg with env config
422474
slack_config = get_plugin_config_from_env("SOCKET_SLACK")
423475
if args.slack_webhook:
@@ -502,7 +554,9 @@ def to_dict(self) -> dict:
502554
def create_argument_parser() -> argparse.ArgumentParser:
503555
parser = argparse.ArgumentParser(
504556
prog="socketcli",
505-
description="The Socket Security CLI will get the head scan for the provided repo from Socket, create a new one, and then report any alerts introduced by the changes. Any new alerts will cause the CLI to exit with a non-Zero exit code (1 for error alerts, 5 for warnings)."
557+
description="Scan dependencies and report security alerts. In diff mode, blocking findings exit 1; "
558+
"warnings alone exit 0. Invalid flags or configuration exit 2, infrastructure "
559+
"failures exit 3 by default, and Ctrl+C exits 130."
506560
)
507561

508562
# Authentication
@@ -956,9 +1010,9 @@ def create_argument_parser() -> argparse.ArgumentParser:
9561010
dest="disable_blocking",
9571011
action="store_true",
9581012
help=(
959-
"Non-blocking CI mode: always exit 0, even when blocking alerts are present "
960-
"(including with --strict-blocking), on uncaught errors, or on Socket API failures. "
961-
"Findings and errors are still logged. Overrides --strict-blocking."
1013+
"Non-blocking CI mode: exit 0 for blocking findings (including with --strict-blocking), "
1014+
"setup/API/runtime failures and interrupts. Invalid flags or configuration still exit 2. "
1015+
"Findings and errors are still logged. Overrides --strict-blocking and --exit-code-on-api-error."
9621016
),
9631017
)
9641018
advanced_group.add_argument(
@@ -1022,7 +1076,7 @@ def create_argument_parser() -> argparse.ArgumentParser:
10221076
"--timeout",
10231077
type=int,
10241078
metavar="<seconds>",
1025-
help="Timeout in seconds for API requests",
1079+
help="Timeout in seconds for API requests (must be greater than zero)",
10261080
required=False
10271081
)
10281082
advanced_group.add_argument(
@@ -1033,10 +1087,12 @@ def create_argument_parser() -> argparse.ArgumentParser:
10331087
metavar="<int>",
10341088
help=(
10351089
"Exit code to use when the CLI fails on an API or infrastructure error "
1036-
"(timeout, network failure, unexpected exception). Default: 3. Useful for "
1090+
"(missing credentials, setup failure, incomplete scan data, timeout, network failure, "
1091+
"unexpected exception). Default: 3. Findings (1), usage errors (2) and Ctrl+C (130) "
1092+
"are unaffected. Useful for "
10371093
"distinguishing infrastructure failures from security findings (exit 1) in "
10381094
"CI -- e.g. set to a Buildkite soft_fail code. NOTE: --disable-blocking "
1039-
"forces exit 0 for ALL outcomes and therefore overrides this flag; do not "
1095+
"overrides this flag but never suppresses usage errors; do not "
10401096
"combine the two if you want the custom code to take effect."
10411097
)
10421098
)

‎socketsecurity/core/__init__.py‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1516,8 +1516,7 @@ def get_repo_info(self, repo_slug: str, default_branch: str = "socket-default-br
15161516
# This module logs through "socketdev" too, so a failed lookup must not leave it muted.
15171517
sdk_logger.setLevel(original_level)
15181518
if not response.success:
1519-
log.error(f"Failed to get repository: {response.status}")
1520-
# log.error(response.message)
1519+
raise APIFailure(response.message or "Repository lookup failed", status_code=response.status)
15211520
except APIFailure as lookup_error:
15221521
# Only a missing repository should be created. A token without the
15231522
# repo:list scope gets 401/403 here, and treating that as "doesn't
@@ -1527,6 +1526,10 @@ def get_repo_info(self, repo_slug: str, default_branch: str = "socket-default-br
15271526
f"Failed to get repository {repo_slug} (HTTP {lookup_error.status_code}). "
15281527
"The API token may be missing the repo:list scope."
15291528
) from lookup_error
1529+
if lookup_error.status_code != 404:
1530+
status = f" (HTTP {lookup_error.status_code})" if lookup_error.status_code else ""
1531+
reason = str(lookup_error).split("\n", 1)[0] or type(lookup_error).__name__
1532+
raise InfrastructureError(f"Failed to get repository {repo_slug}{status}: {reason}") from lookup_error
15301533
log.warning(f"Failed to get repository {repo_slug}, attempting to create it")
15311534
try:
15321535

@@ -1543,6 +1546,8 @@ def get_repo_info(self, repo_slug: str, default_branch: str = "socket-default-br
15431546
raise Exception("Failed to create repository: empty response")
15441547
else:
15451548
response = self.sdk.repos.repo(self.config.org_slug, repo_slug, use_types=True)
1549+
if not response.success:
1550+
raise APIFailure(response.message or "Repository lookup failed", status_code=response.status)
15461551
return response.data
15471552

15481553
except APIFailure as e:
@@ -2104,17 +2109,17 @@ def get_diff_scan_artifacts(
21042109
polls += 1
21052110
if response.get("status") != "processing":
21062111
scan = response.get("diff_scan") or {}
2107-
if scan.get("artifacts") is None:
2108-
raise Exception(
2109-
f"Error fetching diff scan {diff_scan_id}: unexpected response: {str(response)[:500]}"
2110-
)
2111-
artifacts_dict = scan["artifacts"]
21122112
if scan.get("incomplete") or response.get("incomplete"):
21132113
raise IncompleteComparisonError(
21142114
f"The scan comparison is incomplete (diff scan {diff_scan_id}): the API "
21152115
"could not compare every package, so alerts may be missing. Failing "
21162116
"instead of reporting a result that may not cover the whole change."
21172117
)
2118+
if scan.get("artifacts") is None:
2119+
raise Exception(
2120+
f"Error fetching diff scan {diff_scan_id}: unexpected response: {str(response)[:500]}"
2121+
)
2122+
artifacts_dict = scan["artifacts"]
21182123
log.info(
21192124
"Diff scan comparison ready in "
21202125
f"{time.monotonic() - poll_start:.2f}s: id={diff_scan_id}, "

‎socketsecurity/exit_codes.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
"""Process exit codes, and the exceptions that map onto them.
22
3-
``socketcli.cli()`` is the only place that turns an outcome into an exit code,
4-
so ``--disable-blocking`` and ``--exit-code-on-api-error`` apply to every run
5-
that gets past argument parsing:
3+
``socketcli.cli()`` applies runtime failure policy using the configuration loaded
4+
at startup. Argument validation exits with ``EXIT_USAGE`` directly; successful
5+
reports and findings use OutputHandler, and SCM event filters may skip a run.
66
7-
* ``EXIT_OK`` (0): no blocking findings, or ``--disable-blocking`` is set.
7+
* ``EXIT_OK`` (0): successful report, skipped event, or ``--disable-blocking``.
88
* ``EXIT_BLOCKING`` (1): blocking security findings.
99
* ``EXIT_USAGE`` (2): invalid flags or configuration. The same code argparse uses
1010
for its own usage errors. ``--disable-blocking`` does not apply, because a

0 commit comments

Comments
 (0)