socketsecurity 2.12.2__py3-none-any.whl → 2.13.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
1
  __author__ = 'socket.dev'
2
- __version__ = '2.12.2'
2
+ __version__ = '2.13.0'
3
3
  USER_AGENT_NAME = 'socket-python-cli'
4
4
  USER_AGENT = f'{USER_AGENT_NAME}/{__version__}'
socketsecurity/config.py CHANGED
@@ -2,15 +2,22 @@ import argparse
2
2
  import json
3
3
  import logging
4
4
  import os
5
+ import sys
5
6
  import tomllib
6
7
  from dataclasses import asdict, dataclass, field
7
- from typing import List, Optional
8
+ from typing import List, NoReturn, Optional
8
9
 
9
10
  from socketdev import INTEGRATION_TYPES, IntegrationType
10
11
 
11
12
  from socketsecurity import __version__
13
+ from socketsecurity.exit_codes import EXIT_USAGE
12
14
 
13
15
 
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
+
14
21
  def get_plugin_config_from_env(prefix: str) -> dict:
15
22
  config_str = os.getenv(f"{prefix}_CONFIG_JSON", "{}")
16
23
  try:
@@ -65,24 +72,44 @@ def load_cli_config_file(config_path: str) -> dict:
65
72
  elif config_path.lower().endswith(".toml"):
66
73
  data = tomllib.load(f)
67
74
  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")
70
76
  except FileNotFoundError:
71
- logging.error(f"Config file not found: {config_path}")
72
- exit(1)
73
- except (json.JSONDecodeError, tomllib.TOMLDecodeError) as e:
74
- logging.error(f"Invalid config file format: {e}")
75
- exit(1)
77
+ _usage_error(f"Config file not found: {config_path}")
78
+ except (json.JSONDecodeError, tomllib.TOMLDecodeError, UnicodeDecodeError) as e:
79
+ _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}")
76
82
 
77
83
  if not isinstance(data, dict):
78
- logging.error("Config file must contain a top-level object/table")
79
- exit(1)
84
+ _usage_error("Config file must contain a top-level object/table")
80
85
 
81
86
  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")
82
89
  if isinstance(scoped, dict):
83
90
  return scoped
84
91
  return data
85
92
 
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
+
86
113
  def normalize_exclude_paths(value) -> Optional[List[str]]:
87
114
  """Normalize a --exclude-paths value into a clean list of patterns.
88
115
 
@@ -106,7 +133,7 @@ def validate_exclude_paths(patterns: List[str]) -> None:
106
133
 
107
134
  Patterns are scan-root-relative globs. Reject the cases coana's --exclude-dirs / fast-glob
108
135
  cannot honor: negation, absolute paths, ``..`` traversal, and degenerate match-everything.
109
- Exits with code 1 on the first invalid pattern.
136
+ Exits with the usage-error code (2) on the first invalid pattern.
110
137
  """
111
138
  # Degenerate match-everything forms, compared against the trailing-slash-stripped pattern
112
139
  # (so "**/" reduces to "**" and is rejected, matching Node's stripTrailingSlash + check).
@@ -114,17 +141,13 @@ def validate_exclude_paths(patterns: List[str]) -> None:
114
141
  for p in patterns:
115
142
  norm = (p or "").strip().replace("\\", "/")
116
143
  if norm.startswith("!"):
117
- logging.error(f"--exclude-paths: negation patterns are not supported: {p!r}")
118
- exit(1)
144
+ _usage_error(f"--exclude-paths: negation patterns are not supported: {p!r}")
119
145
  if norm.startswith("/"):
120
- logging.error(f"--exclude-paths: patterns must be scan-root relative (no leading '/'): {p!r}")
121
- exit(1)
146
+ _usage_error(f"--exclude-paths: patterns must be scan-root relative (no leading '/'): {p!r}")
122
147
  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)
148
+ _usage_error(f"--exclude-paths: '..' path traversal is not allowed: {p!r}")
125
149
  if norm.rstrip("/") in degenerate:
126
- logging.error(f"--exclude-paths: pattern would exclude everything: {p!r}")
127
- exit(1)
150
+ _usage_error(f"--exclude-paths: pattern would exclude everything: {p!r}")
128
151
 
129
152
 
130
153
  @dataclass
@@ -239,6 +262,13 @@ class CliConfig:
239
262
 
240
263
  @classmethod
241
264
  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':
242
272
  parser = create_argument_parser()
243
273
 
244
274
  pre_parser = argparse.ArgumentParser(add_help=False)
@@ -256,6 +286,23 @@ class CliConfig:
256
286
  parser.set_defaults(**normalized_defaults)
257
287
 
258
288
  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")
259
306
  integration_explicit = hasattr(args, "integration")
260
307
  pr_number_explicit = hasattr(args, "pr_number")
261
308
 
@@ -416,11 +463,13 @@ class CliConfig:
416
463
  try:
417
464
  config_args["excluded_ecosystems"] = json.loads(excluded_ecosystems.replace("'", '"'))
418
465
  except json.JSONDecodeError:
419
- logging.error(f"Unable to parse excluded_ecosystems: {excluded_ecosystems}")
420
- exit(1)
466
+ _usage_error(f"Unable to parse excluded_ecosystems: {excluded_ecosystems}")
421
467
  else:
422
- logging.error(f"Unable to parse excluded_ecosystems: {excluded_ecosystems}")
423
- exit(1)
468
+ _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")
424
473
  # Build Slack plugin config, merging CLI arg with env config
425
474
  slack_config = get_plugin_config_from_env("SOCKET_SLACK")
426
475
  if args.slack_webhook:
@@ -444,21 +493,18 @@ class CliConfig:
444
493
 
445
494
  # Validate that sub_paths and workspace_name are used together
446
495
  if args.sub_paths and not args.workspace_name:
447
- logging.error("--sub-path requires --workspace-name to be specified")
448
- exit(1)
496
+ _usage_error("--sub-path requires --workspace-name to be specified")
449
497
  if args.workspace_name and not args.sub_paths:
450
- logging.error("--workspace-name requires --sub-path to be specified")
451
- exit(1)
498
+ _usage_error("--workspace-name requires --sub-path to be specified")
452
499
 
453
500
  # The API validates the repo as a slug, which can't contain "/", so an
454
501
  # owner/repo value would otherwise fail later at repository creation.
455
502
  if args.repo and "/" in args.repo:
456
503
  suggested = args.repo.rstrip("/").rsplit("/", 1)[-1]
457
- logging.error(
504
+ _usage_error(
458
505
  f"--repo takes the repository slug without its owner, but got '{args.repo}'. "
459
506
  f"Use --repo {suggested}, and --workspace for the owner if your repositories use one."
460
507
  )
461
- exit(1)
462
508
 
463
509
  if args.pending_head:
464
510
  logging.warning(
@@ -469,21 +515,16 @@ class CliConfig:
469
515
  # argparse only enforces the mutually exclusive group for real CLI args;
470
516
  # this also catches both values arriving via a --config file.
471
517
  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)
518
+ _usage_error("--base-scan-id and --base-commit-sha are mutually exclusive")
474
519
 
475
520
  if args.sarif_scope == "full" and not args.reach:
476
- logging.error("--sarif-scope full requires --reach to be specified")
477
- exit(1)
521
+ _usage_error("--sarif-scope full requires --reach to be specified")
478
522
  if args.sarif_reachability != "all" and not args.reach:
479
- logging.error("--sarif-reachability requires --reach to be specified")
480
- exit(1)
523
+ _usage_error("--sarif-reachability requires --reach to be specified")
481
524
  if args.sarif_grouping == "alert" and args.sarif_scope != "full":
482
- logging.error("--sarif-grouping alert currently requires --sarif-scope full")
483
- exit(1)
525
+ _usage_error("--sarif-grouping alert currently requires --sarif-scope full")
484
526
  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)
527
+ _usage_error("--sarif-reachability potentially/reachable-or-potentially requires --sarif-scope full")
487
528
 
488
529
  # Validate --exclude-paths patterns up front (mirrors Node's assertValidExcludePaths).
489
530
  if config_args.get("exclude_paths"):
@@ -491,23 +532,19 @@ class CliConfig:
491
532
 
492
533
  # Validate that only_facts_file requires reach
493
534
  if args.only_facts_file and not args.reach:
494
- logging.error("--only-facts-file requires --reach to be specified")
495
- exit(1)
535
+ _usage_error("--only-facts-file requires --reach to be specified")
496
536
 
497
537
  # Validate that reach_use_only_pregenerated_sboms requires reach
498
538
  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)
539
+ _usage_error("--reach-use-only-pregenerated-sboms requires --reach to be specified")
501
540
 
502
541
  # Validate reach_concurrency is >= 1 if provided
503
542
  if args.reach_concurrency is not None and args.reach_concurrency < 1:
504
- logging.error("--reach-concurrency must be >= 1")
505
- exit(1)
543
+ _usage_error("--reach-concurrency must be >= 1")
506
544
 
507
545
  # Validate max_purl_batch_size is within allowed range
508
546
  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)
547
+ _usage_error("--max-purl-batch-size must be between 1 and 9999")
511
548
 
512
549
  return cls(**config_args)
513
550
 
@@ -517,7 +554,9 @@ class CliConfig:
517
554
  def create_argument_parser() -> argparse.ArgumentParser:
518
555
  parser = argparse.ArgumentParser(
519
556
  prog="socketcli",
520
- 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."
521
560
  )
522
561
 
523
562
  # Authentication
@@ -971,9 +1010,9 @@ def create_argument_parser() -> argparse.ArgumentParser:
971
1010
  dest="disable_blocking",
972
1011
  action="store_true",
973
1012
  help=(
974
- "Non-blocking CI mode: always exit 0, even when blocking alerts are present "
975
- "(including with --strict-blocking), on uncaught errors, or on Socket API failures. "
976
- "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."
977
1016
  ),
978
1017
  )
979
1018
  advanced_group.add_argument(
@@ -1037,7 +1076,7 @@ def create_argument_parser() -> argparse.ArgumentParser:
1037
1076
  "--timeout",
1038
1077
  type=int,
1039
1078
  metavar="<seconds>",
1040
- help="Timeout in seconds for API requests",
1079
+ help="Timeout in seconds for API requests (must be greater than zero)",
1041
1080
  required=False
1042
1081
  )
1043
1082
  advanced_group.add_argument(
@@ -1048,10 +1087,12 @@ def create_argument_parser() -> argparse.ArgumentParser:
1048
1087
  metavar="<int>",
1049
1088
  help=(
1050
1089
  "Exit code to use when the CLI fails on an API or infrastructure error "
1051
- "(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 "
1052
1093
  "distinguishing infrastructure failures from security findings (exit 1) in "
1053
1094
  "CI -- e.g. set to a Buildkite soft_fail code. NOTE: --disable-blocking "
1054
- "forces exit 0 for ALL outcomes and therefore overrides this flag; do not "
1095
+ "overrides this flag but never suppresses usage errors; do not "
1055
1096
  "combine the two if you want the custom code to take effect."
1056
1097
  )
1057
1098
  )
@@ -8,7 +8,6 @@ import os
8
8
  import random
9
9
  import re
10
10
  import shutil
11
- import sys
12
11
  import tarfile
13
12
  import tempfile
14
13
  import time
@@ -32,6 +31,7 @@ from socketdev.repos import RepositoryInfo
32
31
  from socketsecurity import USER_AGENT, __version__
33
32
  from socketsecurity.core.classes import Alert, Diff, FullScan, Issue, Package, Purl
34
33
  from socketsecurity.core.exceptions import APIResourceNotFound
34
+ from socketsecurity.exit_codes import IncompleteComparisonError, InfrastructureError
35
35
 
36
36
  from .resource_utils import check_file_count_against_ulimit
37
37
  from .socket_config import SocketConfig
@@ -1357,13 +1357,13 @@ class Core:
1357
1357
  packages=packages
1358
1358
  )
1359
1359
 
1360
- consolidated: Set[str] = set()
1360
+ consolidated: Set[Tuple[str, str, str, str]] = set()
1361
1361
  for alert_key, alerts in all_alerts_collection.items():
1362
1362
  for alert in alerts:
1363
- alert_str = f"{alert.purl},{alert.type}"
1364
- if (alert.error or alert.warn) and alert_str not in consolidated:
1363
+ finding_key = alert.consolidation_key()
1364
+ if (alert.error or alert.warn) and finding_key not in consolidated:
1365
1365
  diff.new_alerts.append(alert)
1366
- consolidated.add(alert_str)
1366
+ consolidated.add(finding_key)
1367
1367
  diff.alerts_fetched = True
1368
1368
 
1369
1369
  sbom_end = time.time()
@@ -1501,7 +1501,8 @@ class Core:
1501
1501
  RepositoryInfo object
1502
1502
 
1503
1503
  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.
1505
1506
  """
1506
1507
  try:
1507
1508
  # Need to switch to either standard logger or not call our module logging so that there isn't a conflict
@@ -1515,9 +1516,20 @@ class Core:
1515
1516
  # This module logs through "socketdev" too, so a failed lookup must not leave it muted.
1516
1517
  sdk_logger.setLevel(original_level)
1517
1518
  if not response.success:
1518
- log.error(f"Failed to get repository: {response.status}")
1519
- # log.error(response.message)
1520
- except APIFailure:
1519
+ raise APIFailure(response.message or "Repository lookup failed", status_code=response.status)
1520
+ except APIFailure as lookup_error:
1521
+ # Only a missing repository should be created. A token without the
1522
+ # repo:list scope gets 401/403 here, and treating that as "doesn't
1523
+ # exist" would end in a confusing repo:create failure instead.
1524
+ if lookup_error.status_code in (401, 403):
1525
+ raise InfrastructureError(
1526
+ f"Failed to get repository {repo_slug} (HTTP {lookup_error.status_code}). "
1527
+ "The API token may be missing the repo:list scope."
1528
+ ) 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
1521
1533
  log.warning(f"Failed to get repository {repo_slug}, attempting to create it")
1522
1534
  try:
1523
1535
 
@@ -1534,6 +1546,8 @@ class Core:
1534
1546
  raise Exception("Failed to create repository: empty response")
1535
1547
  else:
1536
1548
  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)
1537
1551
  return response.data
1538
1552
 
1539
1553
  except APIFailure as e:
@@ -1541,10 +1555,10 @@ class Core:
1541
1555
  # The SDK appends the request path and response headers after the first line,
1542
1556
  # and some subclasses carry no message at all.
1543
1557
  reason = str(e).split("\n", 1)[0] or type(e).__name__
1544
- log.error(f"API failure while creating repository {repo_slug}{status}: {reason}")
1558
+ message = f"API failure while creating repository {repo_slug}{status}: {reason}"
1545
1559
  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.
1560
+ message += "\nA 403 here usually means the API token is missing the repo:create scope."
1561
+ raise InfrastructureError(message) from e
1548
1562
 
1549
1563
  return response.data
1550
1564
 
@@ -1864,16 +1878,13 @@ class Core:
1864
1878
  "the merge base."
1865
1879
  )
1866
1880
  else:
1867
- log.error(
1881
+ raise InfrastructureError(
1868
1882
  f"No full scan found for commit {commit_sha} in repo {params.repo} "
1869
1883
  "(--base-commit-sha), and no scanned ancestor within "
1870
1884
  f"{ANCESTOR_WALK_MAX_DEPTH} commits of it. Ensure a scan was "
1871
1885
  "created for that commit (e.g. the CLI runs on default-branch "
1872
1886
  "pushes), or pass --base-scan-id instead."
1873
1887
  )
1874
- if self.cli_config.disable_blocking:
1875
- sys.exit(0)
1876
- sys.exit(self.cli_config.exit_code_on_api_error)
1877
1888
  log.info(
1878
1889
  f"Baseline selected: source={baseline_source} "
1879
1890
  f"scan_id={json.dumps(scan_id)} commit={json.dumps(baseline_commit)}"
@@ -1892,14 +1903,11 @@ class Core:
1892
1903
  # Returning None would make the caller create an empty baseline scan,
1893
1904
  # reporting every dependency as newly added, so fail loudly like the
1894
1905
  # --base-commit-sha path above.
1895
- log.error(
1896
- f"Failed to resolve the matching head scan for repo {params.repo}: {error}"
1897
- )
1898
1906
  if self.cli_config is None:
1899
1907
  raise
1900
- if self.cli_config.disable_blocking:
1901
- sys.exit(0)
1902
- sys.exit(self.cli_config.exit_code_on_api_error)
1908
+ raise InfrastructureError(
1909
+ f"Failed to resolve the matching head scan for repo {params.repo}: {error}"
1910
+ ) from error
1903
1911
  if scan_id:
1904
1912
  log.info(
1905
1913
  "Baseline selected: source=repository-head "
@@ -2101,6 +2109,12 @@ class Core:
2101
2109
  polls += 1
2102
2110
  if response.get("status") != "processing":
2103
2111
  scan = response.get("diff_scan") or {}
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
+ )
2104
2118
  if scan.get("artifacts") is None:
2105
2119
  raise Exception(
2106
2120
  f"Error fetching diff scan {diff_scan_id}: unexpected response: {str(response)[:500]}"
@@ -2215,6 +2229,10 @@ class Core:
2215
2229
  new_full_scan_id,
2216
2230
  external_href=external_href,
2217
2231
  )
2232
+ except IncompleteComparisonError:
2233
+ # The streaming comparison reads the same scans, so falling back to it
2234
+ # would only hide that the result is partial.
2235
+ raise
2218
2236
  except Exception as error:
2219
2237
  # SDK error messages can span many lines (path + response headers); the
2220
2238
  # first line carries the status, which is all the warning needs.
@@ -2480,11 +2498,9 @@ class Core:
2480
2498
  external_href=external_href,
2481
2499
  )
2482
2500
 
2483
- # Separate unchanged packages from added/removed for --strict-blocking support
2484
- unchanged_packages = {
2485
- pkg_id: pkg for pkg_id, pkg in packages.items()
2486
- if pkg_id not in added_packages and pkg_id not in removed_packages
2487
- }
2501
+ unchanged_packages = Core.get_unchanged_packages(packages, added_packages, removed_packages)
2502
+ if unchanged_packages and self._requires_unchanged_alerts():
2503
+ self.add_existing_alerts_from_full_scan(unchanged_packages, new_full_scan.id)
2488
2504
 
2489
2505
  diff = self.create_diff_report(added_packages, removed_packages, unchanged_packages)
2490
2506
  diff.packages = packages
@@ -2509,6 +2525,104 @@ class Core:
2509
2525
 
2510
2526
  return diff
2511
2527
 
2528
+ def _requires_unchanged_alerts(self) -> bool:
2529
+ """Whether an enabled output reads alerts on unchanged packages.
2530
+
2531
+ ``--strict-blocking`` fails the run on them, and the GitLab security report
2532
+ and FOSSA-format output list every current finding, not only new ones.
2533
+ A subset of _requires_unchanged_artifacts.
2534
+ """
2535
+ config = self.cli_config
2536
+ if config is None:
2537
+ return False
2538
+ return bool(
2539
+ getattr(config, "strict_blocking", False)
2540
+ or getattr(config, "enable_gitlab_security", False)
2541
+ or getattr(config, "legal_format", "socket") == "fossa"
2542
+ )
2543
+
2544
+ def add_existing_alerts_from_full_scan(
2545
+ self, unchanged_packages: Dict[str, Package], full_scan_id: str
2546
+ ) -> None:
2547
+ """Fill in the alerts on unchanged packages from the new full scan.
2548
+
2549
+ The cached diff-scans endpoint returns unchanged artifacts with an empty
2550
+ ``alerts`` list, because it keeps only the alerts it counts as new. The full
2551
+ scan of the same commit carries every package's alerts with their policy
2552
+ actions, so they are read from there. Packages are matched by artifact ID,
2553
+ then by ecosystem, namespace, name and version.
2554
+
2555
+ Skipped when any unchanged package already has alerts: the comparison then
2556
+ came from an endpoint that includes them, such as the streaming fallback.
2557
+ A failed fetch or an unmatched package raises, because reporting existing
2558
+ alerts as absent would let ``--strict-blocking`` pass a run it should fail.
2559
+ """
2560
+ if any(package.alerts for package in unchanged_packages.values()):
2561
+ log.debug("The comparison already includes alerts on unchanged packages")
2562
+ return
2563
+
2564
+ start = time.time()
2565
+ by_id: Dict[str, List[dict]] = {}
2566
+ by_identity: Dict[Tuple[str, str, str, str], List[dict]] = {}
2567
+ for artifact in self.get_sbom_data(full_scan_id).values():
2568
+ data = asdict(artifact)
2569
+ alerts = data.get("alerts") or []
2570
+ by_id[data["id"]] = alerts
2571
+ by_identity[Core._package_identity(
2572
+ data["type"], data.get("namespace"), data["name"], data["version"]
2573
+ )] = alerts
2574
+
2575
+ matched = 0
2576
+ alert_count = 0
2577
+ for package in unchanged_packages.values():
2578
+ alerts = by_id.get(package.id)
2579
+ if alerts is None:
2580
+ alerts = by_identity.get(Core._package_identity(
2581
+ package.type, package.namespace, package.name, package.version
2582
+ ))
2583
+ if alerts is None:
2584
+ continue
2585
+ package.alerts = alerts
2586
+ matched += 1
2587
+ alert_count += len(alerts)
2588
+
2589
+ log.info(
2590
+ f"Loaded {alert_count} alerts for {matched} of {len(unchanged_packages)} "
2591
+ f"unchanged packages from full scan {full_scan_id} in {time.time() - start:.2f}s"
2592
+ )
2593
+ if matched < len(unchanged_packages):
2594
+ raise InfrastructureError(
2595
+ f"{len(unchanged_packages) - matched} of {len(unchanged_packages)} unchanged packages "
2596
+ f"were not found in full scan {full_scan_id}; unable to evaluate all existing alerts."
2597
+ )
2598
+
2599
+ @staticmethod
2600
+ def _package_identity(package_type, namespace, name, version) -> Tuple[str, str, str, str]:
2601
+ return (
2602
+ str(Package.normalize_type(package_type) or ""),
2603
+ (namespace or "").strip("/"),
2604
+ name or "",
2605
+ version or "",
2606
+ )
2607
+
2608
+ @staticmethod
2609
+ def get_unchanged_packages(
2610
+ packages: Dict[str, Package],
2611
+ added_packages: Dict[str, Package],
2612
+ removed_packages: Dict[str, Package],
2613
+ ) -> Dict[str, Package]:
2614
+ """Return the packages in ``packages`` that were neither added nor removed.
2615
+
2616
+ ``packages`` is keyed by ``type/purl`` while the added and removed dicts are
2617
+ keyed by artifact ID, so membership is checked on ``Package.id``. The result
2618
+ is keyed by artifact ID to match the other two, which is what
2619
+ ``get_source_data`` expects when it resolves ``topLevelAncestors``.
2620
+ """
2621
+ return {
2622
+ pkg.id: pkg for pkg in packages.values()
2623
+ if pkg.id not in added_packages and pkg.id not in removed_packages
2624
+ }
2625
+
2512
2626
  def create_diff_report(
2513
2627
  self,
2514
2628
  added_packages: Dict[str, Package],
@@ -2853,29 +2967,27 @@ class Core:
2853
2967
  if alert_key not in removed_package_alerts:
2854
2968
  new_alerts = added_package_alerts[alert_key]
2855
2969
  for alert in new_alerts:
2856
- # Consolidate by package and alert type, not by manifest details
2857
- alert_str = f"{alert.purl},{alert.type}"
2970
+ finding_key = alert.consolidation_key()
2858
2971
 
2859
2972
  if alert.error or alert.warn:
2860
- if alert_str not in consolidated_alerts:
2973
+ if finding_key not in consolidated_alerts:
2861
2974
  alerts.append(alert)
2862
- consolidated_alerts.add(alert_str)
2975
+ consolidated_alerts.add(finding_key)
2863
2976
  else:
2864
2977
  new_alerts = added_package_alerts[alert_key]
2865
2978
  removed_alerts = removed_package_alerts[alert_key]
2866
2979
 
2867
2980
  for alert in new_alerts:
2868
- # Consolidate by package and alert type, not by manifest details
2869
- alert_str = f"{alert.purl},{alert.type}"
2981
+ finding_key = alert.consolidation_key()
2870
2982
 
2871
2983
  # Only add if:
2872
2984
  # 1. Alert isn't in removed packages (or we're not ignoring readded alerts)
2873
2985
  # 2. We haven't already recorded this alert
2874
2986
  # 3. It's an error or warning
2875
- if (not ignore_readded or alert not in removed_alerts) and alert_str not in consolidated_alerts:
2987
+ if (not ignore_readded or alert not in removed_alerts) and finding_key not in consolidated_alerts:
2876
2988
  if alert.error or alert.warn:
2877
2989
  alerts.append(alert)
2878
- consolidated_alerts.add(alert_str)
2990
+ consolidated_alerts.add(finding_key)
2879
2991
 
2880
2992
  return alerts
2881
2993
 
@@ -2900,13 +3012,12 @@ class Core:
2900
3012
 
2901
3013
  for alert_key in unchanged_package_alerts:
2902
3014
  for alert in unchanged_package_alerts[alert_key]:
2903
- # Consolidate by package and alert type
2904
- alert_str = f"{alert.purl},{alert.type}"
3015
+ finding_key = alert.consolidation_key()
2905
3016
 
2906
3017
  # Only include error or warning alerts
2907
- if (alert.error or alert.warn) and alert_str not in consolidated_alerts:
3018
+ if (alert.error or alert.warn) and finding_key not in consolidated_alerts:
2908
3019
  alerts.append(alert)
2909
- consolidated_alerts.add(alert_str)
3020
+ consolidated_alerts.add(finding_key)
2910
3021
 
2911
3022
  return alerts
2912
3023
 
@@ -2930,10 +3041,10 @@ class Core:
2930
3041
 
2931
3042
  for alert_key in removed_package_alerts:
2932
3043
  for alert in removed_package_alerts[alert_key]:
2933
- alert_str = f"{alert.purl},{alert.type}"
3044
+ finding_key = alert.consolidation_key()
2934
3045
 
2935
- if alert_str not in consolidated_alerts:
3046
+ if finding_key not in consolidated_alerts:
2936
3047
  alerts.append(alert)
2937
- consolidated_alerts.add(alert_str)
3048
+ consolidated_alerts.add(finding_key)
2938
3049
 
2939
3050
  return alerts
@@ -15,14 +15,26 @@ def select_diff_alerts(diff: Diff, strict_blocking: bool = False) -> List[Issue]
15
15
  """Select diff alerts for output rendering.
16
16
 
17
17
  In strict blocking mode, include unchanged alerts so rendered output aligns
18
- with pass/fail policy evaluation.
18
+ with pass/fail policy evaluation. An unchanged alert already listed as new
19
+ (same Issue.consolidation_key) is skipped so each finding is rendered once.
19
20
  """
20
21
  selected = list(getattr(diff, "new_alerts", []) or [])
21
22
  if strict_blocking:
22
- selected.extend(getattr(diff, "unchanged_alerts", []) or [])
23
+ seen = {_alert_identity(alert) for alert in selected} - {None}
24
+ for alert in getattr(diff, "unchanged_alerts", []) or []:
25
+ identity = _alert_identity(alert)
26
+ if identity is None or identity not in seen:
27
+ selected.append(alert)
28
+ seen.add(identity)
23
29
  return selected
24
30
 
25
31
 
32
+ def _alert_identity(alert: Issue) -> Optional[Tuple[str, str, str, str]]:
33
+ if not (getattr(alert, "purl", "") or ""):
34
+ return None
35
+ return alert.consolidation_key()
36
+
37
+
26
38
  def clone_diff_with_selected_alerts(diff: Diff, selected_alerts: List[Issue]) -> Diff:
27
39
  """Clone a diff object while replacing new_alerts with selected alerts."""
28
40
  selected_diff = Diff(