Skip to content

Commit 51ada53

Browse files
committed
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.
1 parent 4f19040 commit 51ada53

12 files changed

Lines changed: 349 additions & 155 deletions

File tree

‎socketsecurity/config.py‎

Lines changed: 31 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,22 @@
22
import json
33
import logging
44
import os
5+
import sys
56
import tomllib
67
from dataclasses import asdict, dataclass, field
7-
from typing import List, Optional
8+
from typing import List, NoReturn, Optional
89

910
from socketdev import INTEGRATION_TYPES, IntegrationType
1011

1112
from socketsecurity import __version__
13+
from socketsecurity.exit_codes import EXIT_USAGE
1214

1315

16+
def _usage_error(message: str) -> NoReturn:
17+
"""Log an invalid flag or config value and exit like an argparse usage error."""
18+
logging.error(message)
19+
sys.exit(EXIT_USAGE)
20+
1421
def get_plugin_config_from_env(prefix: str) -> dict:
1522
config_str = os.getenv(f"{prefix}_CONFIG_JSON", "{}")
1623
try:
@@ -65,18 +72,14 @@ def load_cli_config_file(config_path: str) -> dict:
6572
elif config_path.lower().endswith(".toml"):
6673
data = tomllib.load(f)
6774
else:
68-
logging.error("--config must be a .json or .toml file")
69-
exit(1)
75+
_usage_error("--config must be a .json or .toml file")
7076
except FileNotFoundError:
71-
logging.error(f"Config file not found: {config_path}")
72-
exit(1)
77+
_usage_error(f"Config file not found: {config_path}")
7378
except (json.JSONDecodeError, tomllib.TOMLDecodeError) as e:
74-
logging.error(f"Invalid config file format: {e}")
75-
exit(1)
79+
_usage_error(f"Invalid config file format: {e}")
7680

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

8184
scoped = data.get("socketcli")
8285
if isinstance(scoped, dict):
@@ -106,25 +109,21 @@ def validate_exclude_paths(patterns: List[str]) -> None:
106109
107110
Patterns are scan-root-relative globs. Reject the cases coana's --exclude-dirs / fast-glob
108111
cannot honor: negation, absolute paths, ``..`` traversal, and degenerate match-everything.
109-
Exits with code 1 on the first invalid pattern.
112+
Exits with the usage-error code (2) on the first invalid pattern.
110113
"""
111114
# Degenerate match-everything forms, compared against the trailing-slash-stripped pattern
112115
# (so "**/" reduces to "**" and is rejected, matching Node's stripTrailingSlash + check).
113116
degenerate = {"", ".", "**", "./**", "/**"}
114117
for p in patterns:
115118
norm = (p or "").strip().replace("\\", "/")
116119
if norm.startswith("!"):
117-
logging.error(f"--exclude-paths: negation patterns are not supported: {p!r}")
118-
exit(1)
120+
_usage_error(f"--exclude-paths: negation patterns are not supported: {p!r}")
119121
if norm.startswith("/"):
120-
logging.error(f"--exclude-paths: patterns must be scan-root relative (no leading '/'): {p!r}")
121-
exit(1)
122+
_usage_error(f"--exclude-paths: patterns must be scan-root relative (no leading '/'): {p!r}")
122123
if norm == ".." or norm.startswith("../") or "/../" in norm or norm.endswith("/.."):
123-
logging.error(f"--exclude-paths: '..' path traversal is not allowed: {p!r}")
124-
exit(1)
124+
_usage_error(f"--exclude-paths: '..' path traversal is not allowed: {p!r}")
125125
if norm.rstrip("/") in degenerate:
126-
logging.error(f"--exclude-paths: pattern would exclude everything: {p!r}")
127-
exit(1)
126+
_usage_error(f"--exclude-paths: pattern would exclude everything: {p!r}")
128127

129128

130129
@dataclass
@@ -416,11 +415,9 @@ def from_args(cls, args_list: Optional[List[str]] = None) -> 'CliConfig':
416415
try:
417416
config_args["excluded_ecosystems"] = json.loads(excluded_ecosystems.replace("'", '"'))
418417
except json.JSONDecodeError:
419-
logging.error(f"Unable to parse excluded_ecosystems: {excluded_ecosystems}")
420-
exit(1)
418+
_usage_error(f"Unable to parse excluded_ecosystems: {excluded_ecosystems}")
421419
else:
422-
logging.error(f"Unable to parse excluded_ecosystems: {excluded_ecosystems}")
423-
exit(1)
420+
_usage_error(f"Unable to parse excluded_ecosystems: {excluded_ecosystems}")
424421
# Build Slack plugin config, merging CLI arg with env config
425422
slack_config = get_plugin_config_from_env("SOCKET_SLACK")
426423
if args.slack_webhook:
@@ -444,21 +441,18 @@ def from_args(cls, args_list: Optional[List[str]] = None) -> 'CliConfig':
444441

445442
# Validate that sub_paths and workspace_name are used together
446443
if args.sub_paths and not args.workspace_name:
447-
logging.error("--sub-path requires --workspace-name to be specified")
448-
exit(1)
444+
_usage_error("--sub-path requires --workspace-name to be specified")
449445
if args.workspace_name and not args.sub_paths:
450-
logging.error("--workspace-name requires --sub-path to be specified")
451-
exit(1)
446+
_usage_error("--workspace-name requires --sub-path to be specified")
452447

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

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

475468
if args.sarif_scope == "full" and not args.reach:
476-
logging.error("--sarif-scope full requires --reach to be specified")
477-
exit(1)
469+
_usage_error("--sarif-scope full requires --reach to be specified")
478470
if args.sarif_reachability != "all" and not args.reach:
479-
logging.error("--sarif-reachability requires --reach to be specified")
480-
exit(1)
471+
_usage_error("--sarif-reachability requires --reach to be specified")
481472
if args.sarif_grouping == "alert" and args.sarif_scope != "full":
482-
logging.error("--sarif-grouping alert currently requires --sarif-scope full")
483-
exit(1)
473+
_usage_error("--sarif-grouping alert currently requires --sarif-scope full")
484474
if args.sarif_reachability in ("potentially", "reachable-or-potentially") and args.sarif_scope != "full":
485-
logging.error("--sarif-reachability potentially/reachable-or-potentially requires --sarif-scope full")
486-
exit(1)
475+
_usage_error("--sarif-reachability potentially/reachable-or-potentially requires --sarif-scope full")
487476

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

492481
# Validate that only_facts_file requires reach
493482
if args.only_facts_file and not args.reach:
494-
logging.error("--only-facts-file requires --reach to be specified")
495-
exit(1)
483+
_usage_error("--only-facts-file requires --reach to be specified")
496484

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

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

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

512497
return cls(**config_args)
513498

‎socketsecurity/core/__init__.py‎

Lines changed: 29 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
import random
99
import re
1010
import shutil
11-
import sys
1211
import tarfile
1312
import tempfile
1413
import time
@@ -32,6 +31,7 @@
3231
from socketsecurity import USER_AGENT, __version__
3332
from socketsecurity.core.classes import Alert, Diff, FullScan, Issue, Package, Purl
3433
from socketsecurity.core.exceptions import APIResourceNotFound
34+
from socketsecurity.exit_codes import IncompleteComparisonError, InfrastructureError
3535

3636
from .resource_utils import check_file_count_against_ulimit
3737
from .socket_config import SocketConfig
@@ -1501,7 +1501,8 @@ def get_repo_info(self, repo_slug: str, default_branch: str = "socket-default-br
15011501
RepositoryInfo object
15021502
15031503
Raises:
1504-
Exception: If API request fails
1504+
InfrastructureError: If the token can't read the repository, or the
1505+
repository doesn't exist and can't be created.
15051506
"""
15061507
try:
15071508
# Need to switch to either standard logger or not call our module logging so that there isn't a conflict
@@ -1517,7 +1518,15 @@ def get_repo_info(self, repo_slug: str, default_branch: str = "socket-default-br
15171518
if not response.success:
15181519
log.error(f"Failed to get repository: {response.status}")
15191520
# log.error(response.message)
1520-
except APIFailure:
1521+
except APIFailure as lookup_error:
1522+
# Only a missing repository should be created. A token without the
1523+
# repo:list scope gets 401/403 here, and treating that as "doesn't
1524+
# exist" would end in a confusing repo:create failure instead.
1525+
if lookup_error.status_code in (401, 403):
1526+
raise InfrastructureError(
1527+
f"Failed to get repository {repo_slug} (HTTP {lookup_error.status_code}). "
1528+
"The API token may be missing the repo:list scope."
1529+
) from lookup_error
15211530
log.warning(f"Failed to get repository {repo_slug}, attempting to create it")
15221531
try:
15231532

@@ -1541,10 +1550,10 @@ def get_repo_info(self, repo_slug: str, default_branch: str = "socket-default-br
15411550
# The SDK appends the request path and response headers after the first line,
15421551
# and some subclasses carry no message at all.
15431552
reason = str(e).split("\n", 1)[0] or type(e).__name__
1544-
log.error(f"API failure while creating repository {repo_slug}{status}: {reason}")
1553+
message = f"API failure while creating repository {repo_slug}{status}: {reason}"
15451554
if e.status_code == 403 and not isinstance(e, (APIInsufficientQuota, APIOrganizationNotAllowed)):
1546-
log.error("A 403 here usually means the API token is missing the repo:create scope.")
1547-
sys.exit(2) # Exit here with code 2. Code 1 indicates a successfully-detected security issue.
1555+
message += "\nA 403 here usually means the API token is missing the repo:create scope."
1556+
raise InfrastructureError(message) from e
15481557

15491558
return response.data
15501559

@@ -1864,16 +1873,13 @@ def resolve_base_full_scan_id(self, params: FullScanParams) -> Optional[str]:
18641873
"the merge base."
18651874
)
18661875
else:
1867-
log.error(
1876+
raise InfrastructureError(
18681877
f"No full scan found for commit {commit_sha} in repo {params.repo} "
18691878
"(--base-commit-sha), and no scanned ancestor within "
18701879
f"{ANCESTOR_WALK_MAX_DEPTH} commits of it. Ensure a scan was "
18711880
"created for that commit (e.g. the CLI runs on default-branch "
18721881
"pushes), or pass --base-scan-id instead."
18731882
)
1874-
if self.cli_config.disable_blocking:
1875-
sys.exit(0)
1876-
sys.exit(self.cli_config.exit_code_on_api_error)
18771883
log.info(
18781884
f"Baseline selected: source={baseline_source} "
18791885
f"scan_id={json.dumps(scan_id)} commit={json.dumps(baseline_commit)}"
@@ -1892,14 +1898,11 @@ def resolve_base_full_scan_id(self, params: FullScanParams) -> Optional[str]:
18921898
# Returning None would make the caller create an empty baseline scan,
18931899
# reporting every dependency as newly added, so fail loudly like the
18941900
# --base-commit-sha path above.
1895-
log.error(
1896-
f"Failed to resolve the matching head scan for repo {params.repo}: {error}"
1897-
)
18981901
if self.cli_config is None:
18991902
raise
1900-
if self.cli_config.disable_blocking:
1901-
sys.exit(0)
1902-
sys.exit(self.cli_config.exit_code_on_api_error)
1903+
raise InfrastructureError(
1904+
f"Failed to resolve the matching head scan for repo {params.repo}: {error}"
1905+
) from error
19031906
if scan_id:
19041907
log.info(
19051908
"Baseline selected: source=repository-head "
@@ -2106,6 +2109,12 @@ def get_diff_scan_artifacts(
21062109
f"Error fetching diff scan {diff_scan_id}: unexpected response: {str(response)[:500]}"
21072110
)
21082111
artifacts_dict = scan["artifacts"]
2112+
if scan.get("incomplete") or response.get("incomplete"):
2113+
raise IncompleteComparisonError(
2114+
f"The scan comparison is incomplete (diff scan {diff_scan_id}): the API "
2115+
"could not compare every package, so alerts may be missing. Failing "
2116+
"instead of reporting a result that may not cover the whole change."
2117+
)
21092118
log.info(
21102119
"Diff scan comparison ready in "
21112120
f"{time.monotonic() - poll_start:.2f}s: id={diff_scan_id}, "
@@ -2215,6 +2224,10 @@ def get_added_and_removed_packages(
22152224
new_full_scan_id,
22162225
external_href=external_href,
22172226
)
2227+
except IncompleteComparisonError:
2228+
# The streaming comparison reads the same scans, so falling back to it
2229+
# would only hide that the result is partial.
2230+
raise
22182231
except Exception as error:
22192232
# SDK error messages can span many lines (path + response headers); the
22202233
# first line carries the status, which is all the warning needs.

‎socketsecurity/core/scm/github.py‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from socketsecurity.core.exceptions import APIFailure
1212
from socketsecurity.core.git_remote import parse_git_remote
1313
from socketsecurity.core.scm_comments import Comments
14+
from socketsecurity.exit_codes import InfrastructureError
1415
from socketsecurity.socketcli import CliClient
1516

1617

@@ -54,8 +55,7 @@ def from_env(cls, pr_number: Optional[str] = None) -> 'GithubConfig':
5455
"""Create config from environment variables with optional overrides"""
5556
token = os.getenv('GH_API_TOKEN')
5657
if not token:
57-
log.error("Unable to get Github API Token from GH_API_TOKEN")
58-
sys.exit(2)
58+
raise InfrastructureError("Unable to get Github API Token from GH_API_TOKEN")
5959

6060
is_buildkite = os.getenv("BUILDKITE") == "true"
6161
buildkite_pr = os.getenv("BUILDKITE_PULL_REQUEST")
@@ -172,8 +172,7 @@ def __init__(
172172
self._ignore_permission_cache: dict[str, Optional[bool]] = {}
173173

174174
if not self.config.token:
175-
log.error("Unable to get Github API Token")
176-
sys.exit(2)
175+
raise InfrastructureError("Unable to get Github API Token")
177176

178177
def check_event_type(self) -> str:
179178
if self.config.event_name.lower() in ["push", "workflow_dispatch"]:

‎socketsecurity/core/scm/gitlab.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from socketsecurity.core import log
1212
from socketsecurity.core.classes import Comment
1313
from socketsecurity.core.scm_comments import Comments
14+
from socketsecurity.exit_codes import InfrastructureError
1415
from socketsecurity.socketcli import CliClient
1516

1617

@@ -37,8 +38,7 @@ class GitlabConfig:
3738
def from_env(cls) -> 'GitlabConfig':
3839
token = os.getenv('GITLAB_TOKEN')
3940
if not token:
40-
log.error("Unable to get GitLab API Token from GITLAB_TOKEN")
41-
sys.exit(2)
41+
raise InfrastructureError("Unable to get GitLab API Token from GITLAB_TOKEN")
4242

4343
project_name = os.getenv('CI_PROJECT_NAME', '')
4444
if "/" in project_name:

‎socketsecurity/exit_codes.py‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""Process exit codes, and the exceptions that map onto them.
2+
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:
6+
7+
* ``EXIT_OK`` (0): no blocking findings, or ``--disable-blocking`` is set.
8+
* ``EXIT_BLOCKING`` (1): blocking security findings.
9+
* ``EXIT_USAGE`` (2): invalid flags or configuration. The same code argparse uses
10+
for its own usage errors. ``--disable-blocking`` does not apply, because a
11+
misconfigured run never got far enough to scan anything.
12+
* ``EXIT_INFRASTRUCTURE`` (3): missing credentials, API or environment failures.
13+
``--exit-code-on-api-error`` replaces it; ``--disable-blocking`` turns it into 0.
14+
* ``EXIT_INTERRUPTED`` (130): Ctrl+C / SIGINT, the POSIX 128 + signal number
15+
convention. ``--disable-blocking`` turns it into 0.
16+
17+
This module imports nothing from the package so config parsing can use it
18+
without pulling in ``socketsecurity.core``.
19+
"""
20+
21+
EXIT_OK = 0
22+
EXIT_BLOCKING = 1
23+
EXIT_USAGE = 2
24+
EXIT_INFRASTRUCTURE = 3
25+
EXIT_INTERRUPTED = 130
26+
27+
28+
class InfrastructureError(Exception):
29+
"""A run that cannot continue for a reason other than its own findings.
30+
31+
Raise it instead of calling ``sys.exit`` so ``cli()`` can apply
32+
``--disable-blocking`` and ``--exit-code-on-api-error``. The message is
33+
logged as is, without a traceback.
34+
"""
35+
36+
37+
class IncompleteComparisonError(InfrastructureError):
38+
"""The API marked a scan comparison incomplete.
39+
40+
An incomplete comparison can leave out alerts, so a passing result would not
41+
mean the change is clean.
42+
"""

0 commit comments

Comments
 (0)