22import json
33import logging
44import os
5+ import sys
56import tomllib
67from dataclasses import asdict , dataclass , field
7- from typing import List , Optional
8+ from typing import List , NoReturn , Optional
89
910from socketdev import INTEGRATION_TYPES , IntegrationType
1011
1112from 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+
1421def 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
0 commit comments