Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,75 @@
# Changelog

## 2.13.0

### Upgrade notes

This release changes exit codes. Check any CI step that matches on a specific
code.

- **Invalid flags exit `2`, not `1`.** `1` now always means blocking security
findings. `2` is the code argparse already used for its own usage errors.
`--disable-blocking` does not apply to usage errors.
- **Ctrl+C exits `130`, not `2`.** `130` is the POSIX code for a process stopped
by SIGINT.
- **`--disable-blocking` and `--exit-code-on-api-error` apply to more failures.**
A missing API token, `GITLAB_TOKEN` or `GH_API_TOKEN`, missing reachability
dependencies, a plan without reachability, and a repository that can't be
created used to exit with a hard-coded `2` or `3`. They now exit `3`, or your
`--exit-code-on-api-error` value, and `--disable-blocking` turns them into `0`.
- **`--strict-blocking` now fails on existing blocking alerts.** It didn't
before, because the scan comparison doesn't include alerts on unchanged
packages. Runs that passed with existing blocking alerts will now fail, which
is what the flag documents. To roll it out gradually, see
[Strict Blocking Mode](docs/cli-reference.md#strict-blocking-mode).
- **An incomplete scan comparison fails the run** with the infrastructure-error
code instead of reporting a result that may be missing alerts.

### Changed: exit codes are decided in one place

- Failures that are not security findings raise one error type, and the
top-level handler applies `--disable-blocking` and `--exit-code-on-api-error`
to all of them. See [Exit codes](README.md#exit-codes).

### Fixed: `--strict-blocking` passed with existing blocking alerts

- The CLI reads alerts on unchanged packages from the new full scan, because
the scan comparison returns those packages without their alerts. This costs
one more API request per run, and only runs when an output needs existing
alerts: `--strict-blocking`, `--enable-gitlab-security` or
`--legal-format fossa`. The GitLab security report and FOSSA output, which
list every current finding, were missing the same alerts.
- If that request fails, the run fails with the infrastructure-error code
rather than passing without the existing alerts.

### Fixed: duplicate findings with `--strict-blocking`

- Alerts on added packages are no longer also reported as existing alerts. Each
finding on an added package was listed twice in JSON, SARIF, Slack and GitLab
output, and counted again in the summary's "EXISTING blocking issues" line and
the GitLab commit status.

### Fixed: a package's second CVE was dropped

- Alerts were collapsed on package and alert type, and every CVE of one
severity shares an alert type, so only one advisory per package and severity
was reported. A blocking advisory could be dropped behind a warning on the
same package, letting the run pass. Each GHSA or CVE is now reported, and the
PR comment shows its ID next to the title.

### Added: existing alerts in PR/MR comments

- Under `--strict-blocking`, the security comment lists existing alerts in
their own table after the new ones, blocking first. `@SocketSecurity ignore`
applies to them too. The table stops before the comment reaches GitHub's size
limit and links to the full report for the rest.

### Fixed: a token without `repo:list` was reported as a missing repository

- A repository lookup that fails with 401 or 403 now says the token may be
missing the `repo:list` scope. Before, the CLI treated it as a missing
repository, tried to create it, and failed with a `repo:create` error.
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

## 2.12.1

### Changed: bump pinned Coana CLI to 15.15.1
Expand Down
21 changes: 12 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -217,12 +217,13 @@ Minimal pattern:

## Exit codes

| Code | Meaning |
|------|---------|
| `0` | Clean scan — no blocking issues (or `--disable-blocking` set) |
| `1` | Blocking security finding(s) detected |
| `2` | Scan interrupted (SIGINT / Ctrl+C) |
| `3` | Infrastructure or API error (timeout, network failure, unexpected error) |
| Code | Meaning |
|-------|---------|
| `0` | Clean scan — no blocking issues (or `--disable-blocking` set) |
| `1` | Blocking security finding(s) detected |
| `2` | Invalid flags or configuration (usage error), including argparse's own errors |
| `3` | Infrastructure or API error: missing API or SCM token, permission or plan problem, timeout, network failure, incomplete scan comparison, unexpected error |
| `130` | Scan interrupted (SIGINT / Ctrl+C) |

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

- **`--disable-blocking` wins over everything.** It forces exit `0` for *all*
outcomes — security findings *and* infrastructure errors. If you set it,
`--exit-code-on-api-error` has no effect (you'll always get `0`).
- **`--disable-blocking` wins for every run that gets past flag parsing.** It
forces exit `0` for security findings, infrastructure errors and interrupts.
If you set it, `--exit-code-on-api-error` has no effect (you'll always get `0`).
It does not apply to usage errors (`2`): a run with invalid flags never scanned
anything, so it always fails.
- **`--exit-code-on-api-error` only applies when `--disable-blocking` is *not*
set.** It changes the infra-error code (and the generic-error code); it never
touches the security-finding code (`1`).
Expand Down
4 changes: 3 additions & 1 deletion docs/cli-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -437,7 +437,7 @@ The CLI runs a pinned version of the Coana CLI, the analysis engine; it does **n
| Parameter | Required | Default | Description |
|:-------------------------|:---------|:--------|:----------------------------------------------------------------------|
| `--ignore-commit-files` | False | False | Compare regardless of which files changed, scanning every manifest |
| `--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`. |
| `--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`. |
| `--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). |
| `--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). |
| `--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. |
Expand Down Expand Up @@ -643,6 +643,8 @@ Security issues detected by Socket Security:

- **Diff Mode Only**: The flag only works in diff mode (with SCM integration). In API mode, a warning is logged.
- **Error-Level Only**: Only fails on `error=True` alerts (blocking severity), not warnings.
- **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, the run fails with the infrastructure-error code rather than passing without them.
- **PR/MR comments**: Existing alerts are listed in their own table after the new ones, blocking first. `@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.
- **Priority**: `--disable-blocking` takes precedence - if both flags are set, the build will always pass.
- **First Scan**: On the very first scan of a repository, there are no "existing" violations, so behavior is identical to standard mode.

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ build-backend = "hatchling.build"

[project]
name = "socketsecurity"
version = "2.12.1"
version = "2.13.0"
requires-python = ">= 3.11"
license = {"file" = "LICENSE"}
dependencies = [
Expand Down
2 changes: 1 addition & 1 deletion socketsecurity/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
__author__ = 'socket.dev'
__version__ = '2.12.1'
__version__ = '2.13.0'
USER_AGENT_NAME = 'socket-python-cli'
USER_AGENT = f'{USER_AGENT_NAME}/{__version__}'
77 changes: 31 additions & 46 deletions socketsecurity/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,22 @@
import json
import logging
import os
import sys
import tomllib
from dataclasses import asdict, dataclass, field
from typing import List, Optional
from typing import List, NoReturn, Optional

from socketdev import INTEGRATION_TYPES, IntegrationType

from socketsecurity import __version__
from socketsecurity.exit_codes import EXIT_USAGE


def _usage_error(message: str) -> NoReturn:
"""Log an invalid flag or config value and exit like an argparse usage error."""
logging.error(message)
sys.exit(EXIT_USAGE)

def get_plugin_config_from_env(prefix: str) -> dict:
config_str = os.getenv(f"{prefix}_CONFIG_JSON", "{}")
try:
Expand Down Expand Up @@ -65,18 +72,14 @@ def load_cli_config_file(config_path: str) -> dict:
elif config_path.lower().endswith(".toml"):
data = tomllib.load(f)
else:
logging.error("--config must be a .json or .toml file")
exit(1)
_usage_error("--config must be a .json or .toml file")
except FileNotFoundError:
logging.error(f"Config file not found: {config_path}")
exit(1)
_usage_error(f"Config file not found: {config_path}")
except (json.JSONDecodeError, tomllib.TOMLDecodeError) as e:
logging.error(f"Invalid config file format: {e}")
exit(1)
_usage_error(f"Invalid config file format: {e}")

if not isinstance(data, dict):
logging.error("Config file must contain a top-level object/table")
exit(1)
_usage_error("Config file must contain a top-level object/table")

scoped = data.get("socketcli")
if isinstance(scoped, dict):
Expand Down Expand Up @@ -106,25 +109,21 @@ def validate_exclude_paths(patterns: List[str]) -> None:

Patterns are scan-root-relative globs. Reject the cases coana's --exclude-dirs / fast-glob
cannot honor: negation, absolute paths, ``..`` traversal, and degenerate match-everything.
Exits with code 1 on the first invalid pattern.
Exits with the usage-error code (2) on the first invalid pattern.
"""
# Degenerate match-everything forms, compared against the trailing-slash-stripped pattern
# (so "**/" reduces to "**" and is rejected, matching Node's stripTrailingSlash + check).
degenerate = {"", ".", "**", "./**", "/**"}
for p in patterns:
norm = (p or "").strip().replace("\\", "/")
if norm.startswith("!"):
logging.error(f"--exclude-paths: negation patterns are not supported: {p!r}")
exit(1)
_usage_error(f"--exclude-paths: negation patterns are not supported: {p!r}")
if norm.startswith("/"):
logging.error(f"--exclude-paths: patterns must be scan-root relative (no leading '/'): {p!r}")
exit(1)
_usage_error(f"--exclude-paths: patterns must be scan-root relative (no leading '/'): {p!r}")
if norm == ".." or norm.startswith("../") or "/../" in norm or norm.endswith("/.."):
logging.error(f"--exclude-paths: '..' path traversal is not allowed: {p!r}")
exit(1)
_usage_error(f"--exclude-paths: '..' path traversal is not allowed: {p!r}")
if norm.rstrip("/") in degenerate:
logging.error(f"--exclude-paths: pattern would exclude everything: {p!r}")
exit(1)
_usage_error(f"--exclude-paths: pattern would exclude everything: {p!r}")


@dataclass
Expand Down Expand Up @@ -416,11 +415,9 @@ def from_args(cls, args_list: Optional[List[str]] = None) -> 'CliConfig':
try:
config_args["excluded_ecosystems"] = json.loads(excluded_ecosystems.replace("'", '"'))
except json.JSONDecodeError:
logging.error(f"Unable to parse excluded_ecosystems: {excluded_ecosystems}")
exit(1)
_usage_error(f"Unable to parse excluded_ecosystems: {excluded_ecosystems}")
else:
logging.error(f"Unable to parse excluded_ecosystems: {excluded_ecosystems}")
exit(1)
_usage_error(f"Unable to parse excluded_ecosystems: {excluded_ecosystems}")
# Build Slack plugin config, merging CLI arg with env config
slack_config = get_plugin_config_from_env("SOCKET_SLACK")
if args.slack_webhook:
Expand All @@ -444,21 +441,18 @@ def from_args(cls, args_list: Optional[List[str]] = None) -> 'CliConfig':

# Validate that sub_paths and workspace_name are used together
if args.sub_paths and not args.workspace_name:
logging.error("--sub-path requires --workspace-name to be specified")
exit(1)
_usage_error("--sub-path requires --workspace-name to be specified")
if args.workspace_name and not args.sub_paths:
logging.error("--workspace-name requires --sub-path to be specified")
exit(1)
_usage_error("--workspace-name requires --sub-path to be specified")

# The API validates the repo as a slug, which can't contain "/", so an
# owner/repo value would otherwise fail later at repository creation.
if args.repo and "/" in args.repo:
suggested = args.repo.rstrip("/").rsplit("/", 1)[-1]
logging.error(
_usage_error(
f"--repo takes the repository slug without its owner, but got '{args.repo}'. "
f"Use --repo {suggested}, and --workspace for the owner if your repositories use one."
)
exit(1)

if args.pending_head:
logging.warning(
Expand All @@ -469,45 +463,36 @@ def from_args(cls, args_list: Optional[List[str]] = None) -> 'CliConfig':
# argparse only enforces the mutually exclusive group for real CLI args;
# this also catches both values arriving via a --config file.
if args.base_scan_id and args.base_commit_sha:
logging.error("--base-scan-id and --base-commit-sha are mutually exclusive")
exit(1)
_usage_error("--base-scan-id and --base-commit-sha are mutually exclusive")

if args.sarif_scope == "full" and not args.reach:
logging.error("--sarif-scope full requires --reach to be specified")
exit(1)
_usage_error("--sarif-scope full requires --reach to be specified")
if args.sarif_reachability != "all" and not args.reach:
logging.error("--sarif-reachability requires --reach to be specified")
exit(1)
_usage_error("--sarif-reachability requires --reach to be specified")
if args.sarif_grouping == "alert" and args.sarif_scope != "full":
logging.error("--sarif-grouping alert currently requires --sarif-scope full")
exit(1)
_usage_error("--sarif-grouping alert currently requires --sarif-scope full")
if args.sarif_reachability in ("potentially", "reachable-or-potentially") and args.sarif_scope != "full":
logging.error("--sarif-reachability potentially/reachable-or-potentially requires --sarif-scope full")
exit(1)
_usage_error("--sarif-reachability potentially/reachable-or-potentially requires --sarif-scope full")

# Validate --exclude-paths patterns up front (mirrors Node's assertValidExcludePaths).
if config_args.get("exclude_paths"):
validate_exclude_paths(config_args["exclude_paths"])

# Validate that only_facts_file requires reach
if args.only_facts_file and not args.reach:
logging.error("--only-facts-file requires --reach to be specified")
exit(1)
_usage_error("--only-facts-file requires --reach to be specified")

# Validate that reach_use_only_pregenerated_sboms requires reach
if args.reach_use_only_pregenerated_sboms and not args.reach:
logging.error("--reach-use-only-pregenerated-sboms requires --reach to be specified")
exit(1)
_usage_error("--reach-use-only-pregenerated-sboms requires --reach to be specified")

# Validate reach_concurrency is >= 1 if provided
if args.reach_concurrency is not None and args.reach_concurrency < 1:
logging.error("--reach-concurrency must be >= 1")
exit(1)
_usage_error("--reach-concurrency must be >= 1")

# Validate max_purl_batch_size is within allowed range
if args.max_purl_batch_size < 1 or args.max_purl_batch_size > 9999:
logging.error("--max-purl-batch-size must be between 1 and 9999")
exit(1)
_usage_error("--max-purl-batch-size must be between 1 and 9999")

return cls(**config_args)

Expand Down
Loading
Loading