diff --git a/CHANGELOG.md b/CHANGELOG.md index a680fd59..49751340 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## 2.13.3 +## 2.14.0 ### Changed @@ -15,6 +15,9 @@ table. When a finding has both Warn and Block actions, Block takes precedence. - SARIF reports use advisory IDs to distinguish findings on the same package and manifest. +- Comparisons with missing or invalid package lists fail with exit `3` by + default. `--exit-code-on-api-error` can remap the code, and + `--disable-blocking` takes precedence. ## 2.13.2 diff --git a/docs/ci-cd.md b/docs/ci-cd.md index def55470..bd772b3c 100644 --- a/docs/ci-cd.md +++ b/docs/ci-cd.md @@ -86,8 +86,9 @@ does not mean a clean scan; check the logs for a completed report. Findings block only when a [diff comparison runs](#scan-type-by-pipeline). SCM event filters can also skip unsupported events with exit `0`; confirm a report was created when validating a new workflow. -`--strict-blocking` also checks existing blocking alerts; an incomplete comparison -or incomplete existing-alert data is an infrastructure failure. See the +The CLI treats comparisons marked incomplete or returned with missing or +invalid package lists as infrastructure failures. With `--strict-blocking`, +incomplete existing-alert data is also an infrastructure failure. See the [2.13.0 migration table](../README.md#upgrading-to-2130) when updating existing CI rules. ## Config file usage in CI diff --git a/pyproject.toml b/pyproject.toml index b7578c83..4da80233 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ build-backend = "hatchling.build" [project] name = "socketsecurity" -version = "2.13.3" +version = "2.14.0" requires-python = ">= 3.11" license = {"file" = "LICENSE"} dependencies = [ diff --git a/socketsecurity/__init__.py b/socketsecurity/__init__.py index 0871adeb..0f2224d3 100644 --- a/socketsecurity/__init__.py +++ b/socketsecurity/__init__.py @@ -1,4 +1,4 @@ __author__ = 'socket.dev' -__version__ = '2.13.3' +__version__ = '2.14.0' USER_AGENT_NAME = 'socket-python-cli' USER_AGENT = f'{USER_AGENT_NAME}/{__version__}' diff --git a/socketsecurity/core/__init__.py b/socketsecurity/core/__init__.py index e3f27835..9fc1ec3f 100644 --- a/socketsecurity/core/__init__.py +++ b/socketsecurity/core/__init__.py @@ -145,8 +145,7 @@ # Each poll consumes 1 unit of API quota, so the interval backs off toward # DIFF_SCAN_POLL_MAX_INTERVAL_SECONDS to stay quota-friendly on comparisons that take # minutes to compute. The timeout is a backstop against a diff scan that never -# completes; on expiry (or any other failure of this flow) the caller falls back to the -# legacy streaming comparison rather than failing the scan outright. +# completes. On expiry the caller falls back to the legacy streaming comparison. DIFF_SCAN_POLL_INITIAL_INTERVAL_SECONDS = 5.0 DIFF_SCAN_POLL_MAX_INTERVAL_SECONDS = 10.0 DIFF_SCAN_POLL_BACKOFF_MULTIPLIER = 1.5 @@ -2001,8 +2000,8 @@ def get_diff_scan_artifacts( See the DIFF_SCAN_POLL_* constants for the polling policy. Requires an org token with the ``diff-scans:create``, ``diff-scans:list`` - and ``full-scans:list`` scopes; callers are expected to catch failures and - fall back to the legacy streaming comparison. + and ``full-scans:list`` scopes. A returned comparison marked incomplete + or missing usable package lists raises ``IncompleteComparisonError``. Note that cached diff-scan responses always embed per-package license details (the API ignores ``omit_license_details`` when ``cached=true``), @@ -2115,18 +2114,30 @@ def get_diff_scan_artifacts( response = {"status": "processing"} polls += 1 if response.get("status") != "processing": - scan = response.get("diff_scan") or {} - if scan.get("incomplete") or response.get("incomplete"): + scan = response.get("diff_scan") + if response.get("incomplete") or (isinstance(scan, dict) and scan.get("incomplete")): raise IncompleteComparisonError( f"The scan comparison is incomplete (diff scan {diff_scan_id}): the API " "could not compare every package, so alerts may be missing. Failing " "instead of reporting a result that may not cover the whole change." ) - if scan.get("artifacts") is None: - raise Exception( - f"Error fetching diff scan {diff_scan_id}: unexpected response: {str(response)[:500]}" + if not isinstance(scan, dict): + # The SDK returns {} for HTTP 204. The caller can use streaming. + raise RuntimeError(f"Error fetching diff scan {diff_scan_id}: response has no diff_scan object") + artifacts_dict = scan.get("artifacts") + if not isinstance(artifacts_dict, dict): + raise IncompleteComparisonError( + f"The scan comparison is incomplete (diff scan {diff_scan_id}). " + "The response is missing a valid artifacts object." ) - artifacts_dict = scan["artifacts"] + for key in ("added", "removed", "unchanged", "replaced", "updated"): + # The API uses null for unchanged artifacts when omit_unchanged is set. + allowed_types = (list, type(None)) if key == "unchanged" and omit_unchanged else (list,) + if key not in artifacts_dict or not isinstance(artifacts_dict[key], allowed_types): + raise IncompleteComparisonError( + f"The scan comparison is incomplete (diff scan {diff_scan_id}). " + f"The response is missing a valid artifacts.{key} list." + ) log.info( "Diff scan comparison ready in " f"{time.monotonic() - poll_start:.2f}s: id={diff_scan_id}, " @@ -2144,10 +2155,7 @@ def get_diff_scan_artifacts( last_interval = interval interval = min(interval * DIFF_SCAN_POLL_BACKOFF_MULTIPLIER, DIFF_SCAN_POLL_MAX_INTERVAL_SECONDS) - return DiffArtifacts.from_dict({ - key: artifacts_dict.get(key) or [] - for key in ("added", "removed", "unchanged", "replaced", "updated") - }) + return DiffArtifacts.from_dict({**artifacts_dict, "unchanged": artifacts_dict["unchanged"] or []}) def _requires_unchanged_artifacts(self) -> bool: """Whether any enabled output reads the unchanged half of a comparison. @@ -2237,8 +2245,7 @@ def get_added_and_removed_packages( external_href=external_href, ) except IncompleteComparisonError: - # The streaming comparison reads the same scans, so falling back to it - # would only hide that the result is partial. + # Streaming reads the same scans and cannot report completeness. raise except Exception as error: # SDK error messages can span many lines (path + response headers); the diff --git a/socketsecurity/exit_codes.py b/socketsecurity/exit_codes.py index 4901d017..15c2d637 100644 --- a/socketsecurity/exit_codes.py +++ b/socketsecurity/exit_codes.py @@ -35,8 +35,4 @@ class InfrastructureError(Exception): class IncompleteComparisonError(InfrastructureError): - """The API marked a scan comparison incomplete. - - An incomplete comparison can leave out alerts, so a passing result would not - mean the change is clean. - """ + """The API returned a comparison with incomplete or missing results.""" diff --git a/tests/core/test_existing_alerts.py b/tests/core/test_existing_alerts.py index c11255e8..33a4e5f1 100644 --- a/tests/core/test_existing_alerts.py +++ b/tests/core/test_existing_alerts.py @@ -161,14 +161,10 @@ def test_blocking_cve_persists_across_a_version_change(core, change_type, strict alert = {**_alert("persistent", alert_type="criticalCVE"), "props": {"cveId": "CVE-2025-12345"}} core.sdk.diffscans.create_from_ids.side_effect = None core.sdk.diffscans.create_from_ids.return_value = {"diff_scan": {"id": "comparison"}} - core.sdk.diffscans.get.return_value = { - "diff_scan": { - "artifacts": { - change_type: [_diff_artifact(change_type, "a2", "alpha", version="2.0.0")], - "replaced": [_diff_artifact("replaced", "a1", "alpha", [alert])], - }, - }, - } + artifacts = {key: [] for key in ("added", "removed", "unchanged", "replaced", "updated")} + artifacts[change_type] = [_diff_artifact(change_type, "a2", "alpha", version="2.0.0")] + artifacts["replaced"] = [_diff_artifact("replaced", "a1", "alpha", [alert])] + core.sdk.diffscans.get.return_value = {"diff_scan": {"artifacts": artifacts}} _stream_through_sdk( core, _scan_artifact("a2", "alpha", [alert], version="2.0.0"), diff --git a/tests/core/test_exit_codes.py b/tests/core/test_exit_codes.py index 9ecda02c..22130cd9 100644 --- a/tests/core/test_exit_codes.py +++ b/tests/core/test_exit_codes.py @@ -6,9 +6,13 @@ errors, and Ctrl+C exits 130. See socketsecurity.exit_codes. """ import sys +from contextlib import nullcontext +from types import SimpleNamespace from unittest.mock import MagicMock import pytest +import requests +from socketdev.diffscans import DiffScans from socketdev.exceptions import ( APIFailure, APIInsufficientPermissions, @@ -137,8 +141,13 @@ def test_repo_creation_failure_raises_infrastructure_error(core): # --- Incomplete comparisons ---------------------------------------------------------- -@pytest.fixture(params=[{}, None, "omitted"]) +EMPTY_ARTIFACTS = {"added": [], "removed": [], "unchanged": [], "replaced": [], "updated": []} + + +@pytest.fixture(params=[{}, None, "omitted", "top-level"]) def incomplete_response(request): + if request.param == "top-level": + return {"incomplete": True} scan = {"id": "diff-scan-1", "incomplete": True} if request.param != "omitted": scan["artifacts"] = request.param @@ -164,12 +173,124 @@ def test_incomplete_comparison_does_not_fall_back_to_streaming(core, incomplete_ core.sdk.fullscans.stream_diff.assert_not_called() +@pytest.fixture(params=[ + pytest.param({"incomplete": False, "artifacts": None}, id="null-artifacts-complete"), + pytest.param({"artifacts": None}, id="null-artifacts-flag-unset"), + pytest.param({}, id="artifacts-absent-flag-unset"), + pytest.param({"artifacts": []}, id="artifacts-not-an-object"), + pytest.param({"artifacts": {}}, id="empty-artifacts-object"), + pytest.param({"artifacts": {**EMPTY_ARTIFACTS, "added": None}}, id="null-added"), + pytest.param({"artifacts": {**EMPTY_ARTIFACTS, "unchanged": None}}, id="null-unchanged"), + pytest.param({"artifacts": {**EMPTY_ARTIFACTS, "removed": {}}}, id="removed-not-a-list"), + pytest.param({"artifacts": {**EMPTY_ARTIFACTS, "updated": "invalid"}}, id="updated-not-a-list"), + pytest.param({"artifacts": {key: [] for key in EMPTY_ARTIFACTS if key != "replaced"}}, id="missing-replaced"), +]) +def invalid_artifacts_response(request): + return {"diff_scan": {"id": "diff-scan-1", **request.param}} + + +def test_invalid_artifacts_do_not_fall_back_to_streaming(core, invalid_artifacts_response): + core.sdk.diffscans.create_from_ids.return_value = {"diff_scan": {"id": "diff-scan-1"}} + core.sdk.diffscans.get.return_value = invalid_artifacts_response + + with pytest.raises(IncompleteComparisonError, match="missing a valid artifacts"): + core.get_added_and_removed_packages("head", "new") + + core.sdk.fullscans.stream_diff.assert_not_called() + + +@pytest.mark.parametrize("argv, expected", [ + ([], 3), + (["--exit-code-on-api-error", "42"], 42), + (["--disable-blocking"], 0), + (["--disable-blocking", "--exit-code-on-api-error", "42"], 0), +]) +@pytest.mark.parametrize("strict", [[], ["--strict-blocking"]], ids=["standard", "strict"]) +def test_invalid_artifacts_follow_exit_policy(monkeypatch, caplog, argv, expected, strict): + sdk = MagicMock() + sdk.org.get.return_value = {"organizations": {"org-id": {"slug": "acme"}}} + sdk.diffscans.create_from_ids.return_value = {"diff_scan": {"id": "diff-scan-1"}} + sdk.diffscans.get.return_value = {"diff_scan": {"id": "diff-scan-1", "artifacts": {}}} + monkeypatch.setattr(socketcli, "build_socket_sdk", lambda config: sdk) + monkeypatch.setattr(socketcli, "StreamingLogs", lambda **kwargs: nullcontext(MagicMock())) + monkeypatch.setattr(socketcli, "apply_git_context", lambda config: (False, None)) + monkeypatch.setattr(Core, "has_manifest_files", lambda self, files: True) + monkeypatch.setattr(Core, "create_full_scan", lambda *args, **kwargs: SimpleNamespace(id="new")) + report = MagicMock() + monkeypatch.setattr(socketcli.OutputHandler, "handle_output", report) + monkeypatch.setattr(sys, "argv", [ + "socketcli", "--api-token", "test", "--scm", "api", "--integration", "api", + "--repo", "repo", "--branch", "feature", "--enable-diff", "--base-scan-id", "head", + "--files", '["package.json"]', *strict, *argv, + ]) + + with pytest.raises(SystemExit) as result: + socketcli.cli() + + assert result.value.code == expected + assert "missing a valid artifacts.added list" in caplog.text + sdk.diffscans.get.assert_called_once() + sdk.fullscans.stream_diff.assert_not_called() + report.assert_not_called() + + +class StreamingFallback(Exception): + """Sentinel for a streaming comparison call.""" + + +@pytest.mark.parametrize("response", [ + pytest.param({}, id="empty-dict"), + pytest.param({"diff_scan": None}, id="diff-scan-null"), + pytest.param({"diff_scan": []}, id="diff-scan-not-an-object"), +]) +def test_response_without_diff_scan_object_falls_back_to_streaming(core, response): + core.sdk.diffscans.create_from_ids.return_value = {"diff_scan": {"id": "diff-scan-1"}} + core.sdk.diffscans.get.return_value = response + core.sdk.fullscans.stream_diff.side_effect = StreamingFallback + + with pytest.raises(RuntimeError, match="no diff_scan object"): + core.get_diff_scan_artifacts("head", "new") + + with pytest.raises(StreamingFallback): + core.get_added_and_removed_packages("head", "new") + core.sdk.fullscans.stream_diff.assert_called_once() + + +def test_http_204_through_the_sdk_falls_back_to_streaming(core): + """The SDK maps HTTP 204 to an empty response.""" + no_content = requests.Response() + no_content.status_code = 204 + no_content._content = b"" + api = MagicMock() + api.do_request.return_value = no_content + core.sdk.diffscans = DiffScans(api) + core.sdk.diffscans.create_from_ids = MagicMock(return_value={"diff_scan": {"id": "diff-scan-1"}}) + core.sdk.fullscans.stream_diff.side_effect = StreamingFallback + + with pytest.raises(StreamingFallback): + core.get_added_and_removed_packages("head", "new") + + +def test_omitted_unchanged_bucket_is_still_a_result(core): + core.cli_config = CliConfig(api_token="test", repo="repo") + core.sdk.diffscans.create_from_ids.return_value = {"diff_scan": {"id": "diff-scan-1"}} + core.sdk.diffscans.get.return_value = {"diff_scan": { + "id": "diff-scan-1", "incomplete": False, + "artifacts": {**EMPTY_ARTIFACTS, "unchanged": None}, + }} + + artifacts = core.get_diff_scan_artifacts("head", "new") + + assert core.sdk.diffscans.get.call_args.kwargs["params"]["omit_unchanged"] == "true" + assert artifacts.unchanged == [] + + def test_complete_comparison_is_returned(core): core.sdk.diffscans.create_from_ids.return_value = {"diff_scan": {"id": "diff-scan-1"}} core.sdk.diffscans.get.return_value = { - "diff_scan": {"id": "diff-scan-1", "incomplete": False, "artifacts": {}}, + "diff_scan": {"id": "diff-scan-1", "incomplete": False, "artifacts": EMPTY_ARTIFACTS}, } artifacts = core.get_diff_scan_artifacts("head", "new") - assert artifacts.added == [] + assert artifacts.to_dict() == EMPTY_ARTIFACTS diff --git a/uv.lock b/uv.lock index 57c8b444..d509bbc9 100644 --- a/uv.lock +++ b/uv.lock @@ -1334,7 +1334,7 @@ wheels = [ [[package]] name = "socketsecurity" -version = "2.13.3" +version = "2.14.0" source = { editable = "." } dependencies = [ { name = "beautifulsoup4" },