Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
5 changes: 4 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Changelog

## 2.13.3
## 2.14.0

### Changed

Expand All @@ -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

Expand Down
5 changes: 3 additions & 2 deletions docs/ci-cd.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
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.13.3"
version = "2.14.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.13.3'
__version__ = '2.14.0'
USER_AGENT_NAME = 'socket-python-cli'
USER_AGENT = f'{USER_AGENT_NAME}/{__version__}'
39 changes: 23 additions & 16 deletions socketsecurity/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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``),
Expand Down Expand Up @@ -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}, "
Expand All @@ -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.
Expand Down Expand Up @@ -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
Expand Down
6 changes: 1 addition & 5 deletions socketsecurity/exit_codes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
12 changes: 4 additions & 8 deletions tests/core/test_existing_alerts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down
127 changes: 124 additions & 3 deletions tests/core/test_exit_codes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand All @@ -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
2 changes: 1 addition & 1 deletion uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading