Skip to content

Commit 190af74

Browse files
committed
Merge main into fix/strict-blocking-no-manifest-change
# Conflicts: # CHANGELOG.md
2 parents 2c6eb6c + ce03d4c commit 190af74

6 files changed

Lines changed: 161 additions & 37 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,17 @@
1717

1818
### Fixed
1919

20-
- `--strict-blocking` checks existing Block findings on code-only changes.
21-
GitHub and GitLab pull request comments show those findings under Existing
22-
alerts.
2320
- `--strict-blocking` counts distinct advisories on unchanged dependencies and
2421
lists findings that persist after a version change in the Existing alerts
2522
table. When a finding has both Warn and Block actions, Block takes precedence.
2623
- SARIF reports use advisory IDs to distinguish findings on the same package
2724
and manifest.
25+
- Comparisons with missing or invalid package lists fail with exit `3` by
26+
default. `--exit-code-on-api-error` can remap the code, and
27+
`--disable-blocking` takes precedence.
28+
- `--strict-blocking` checks existing Block findings on code-only changes.
29+
GitHub and GitLab pull request comments show those findings under Existing
30+
alerts.
2831

2932
## 2.13.2
3033

‎docs/ci-cd.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,8 +86,9 @@ does not mean a clean scan; check the logs for a completed report.
8686
Findings block only when a [diff comparison runs](#scan-type-by-pipeline).
8787
SCM event filters can also skip unsupported events with exit `0`; confirm a report
8888
was created when validating a new workflow.
89-
`--strict-blocking` also checks existing blocking alerts; an incomplete comparison
90-
or incomplete existing-alert data is an infrastructure failure. See the
89+
The CLI treats comparisons marked incomplete or returned with missing or
90+
invalid package lists as infrastructure failures. With `--strict-blocking`,
91+
incomplete existing-alert data is also an infrastructure failure. See the
9192
[2.13.0 migration table](../README.md#upgrading-to-2130) when updating existing CI rules.
9293

9394
## Config file usage in CI

‎socketsecurity/core/__init__.py‎

Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -145,8 +145,7 @@
145145
# Each poll consumes 1 unit of API quota, so the interval backs off toward
146146
# DIFF_SCAN_POLL_MAX_INTERVAL_SECONDS to stay quota-friendly on comparisons that take
147147
# minutes to compute. The timeout is a backstop against a diff scan that never
148-
# completes; on expiry (or any other failure of this flow) the caller falls back to the
149-
# legacy streaming comparison rather than failing the scan outright.
148+
# completes. On expiry the caller falls back to the legacy streaming comparison.
150149
DIFF_SCAN_POLL_INITIAL_INTERVAL_SECONDS = 5.0
151150
DIFF_SCAN_POLL_MAX_INTERVAL_SECONDS = 10.0
152151
DIFF_SCAN_POLL_BACKOFF_MULTIPLIER = 1.5
@@ -2001,8 +2000,8 @@ def get_diff_scan_artifacts(
20012000
See the DIFF_SCAN_POLL_* constants for the polling policy.
20022001
20032002
Requires an org token with the ``diff-scans:create``, ``diff-scans:list``
2004-
and ``full-scans:list`` scopes; callers are expected to catch failures and
2005-
fall back to the legacy streaming comparison.
2003+
and ``full-scans:list`` scopes. A returned comparison marked incomplete
2004+
or missing usable package lists raises ``IncompleteComparisonError``.
20062005
20072006
Note that cached diff-scan responses always embed per-package license
20082007
details (the API ignores ``omit_license_details`` when ``cached=true``),
@@ -2115,18 +2114,30 @@ def get_diff_scan_artifacts(
21152114
response = {"status": "processing"}
21162115
polls += 1
21172116
if response.get("status") != "processing":
2118-
scan = response.get("diff_scan") or {}
2119-
if scan.get("incomplete") or response.get("incomplete"):
2117+
scan = response.get("diff_scan")
2118+
if response.get("incomplete") or (isinstance(scan, dict) and scan.get("incomplete")):
21202119
raise IncompleteComparisonError(
21212120
f"The scan comparison is incomplete (diff scan {diff_scan_id}): the API "
21222121
"could not compare every package, so alerts may be missing. Failing "
21232122
"instead of reporting a result that may not cover the whole change."
21242123
)
2125-
if scan.get("artifacts") is None:
2126-
raise Exception(
2127-
f"Error fetching diff scan {diff_scan_id}: unexpected response: {str(response)[:500]}"
2124+
if not isinstance(scan, dict):
2125+
# The SDK returns {} for HTTP 204. The caller can use streaming.
2126+
raise RuntimeError(f"Error fetching diff scan {diff_scan_id}: response has no diff_scan object")
2127+
artifacts_dict = scan.get("artifacts")
2128+
if not isinstance(artifacts_dict, dict):
2129+
raise IncompleteComparisonError(
2130+
f"The scan comparison is incomplete (diff scan {diff_scan_id}). "
2131+
"The response is missing a valid artifacts object."
21282132
)
2129-
artifacts_dict = scan["artifacts"]
2133+
for key in ("added", "removed", "unchanged", "replaced", "updated"):
2134+
# The API uses null for unchanged artifacts when omit_unchanged is set.
2135+
allowed_types = (list, type(None)) if key == "unchanged" and omit_unchanged else (list,)
2136+
if key not in artifacts_dict or not isinstance(artifacts_dict[key], allowed_types):
2137+
raise IncompleteComparisonError(
2138+
f"The scan comparison is incomplete (diff scan {diff_scan_id}). "
2139+
f"The response is missing a valid artifacts.{key} list."
2140+
)
21302141
log.info(
21312142
"Diff scan comparison ready in "
21322143
f"{time.monotonic() - poll_start:.2f}s: id={diff_scan_id}, "
@@ -2144,10 +2155,7 @@ def get_diff_scan_artifacts(
21442155
last_interval = interval
21452156
interval = min(interval * DIFF_SCAN_POLL_BACKOFF_MULTIPLIER, DIFF_SCAN_POLL_MAX_INTERVAL_SECONDS)
21462157

2147-
return DiffArtifacts.from_dict({
2148-
key: artifacts_dict.get(key) or []
2149-
for key in ("added", "removed", "unchanged", "replaced", "updated")
2150-
})
2158+
return DiffArtifacts.from_dict({**artifacts_dict, "unchanged": artifacts_dict["unchanged"] or []})
21512159

21522160
def _requires_unchanged_artifacts(self) -> bool:
21532161
"""Whether any enabled output reads the unchanged half of a comparison.
@@ -2237,8 +2245,7 @@ def get_added_and_removed_packages(
22372245
external_href=external_href,
22382246
)
22392247
except IncompleteComparisonError:
2240-
# The streaming comparison reads the same scans, so falling back to it
2241-
# would only hide that the result is partial.
2248+
# Streaming reads the same scans and cannot report completeness.
22422249
raise
22432250
except Exception as error:
22442251
# SDK error messages can span many lines (path + response headers); the

‎socketsecurity/exit_codes.py‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,4 @@ class InfrastructureError(Exception):
3535

3636

3737
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-
"""
38+
"""The API returned a comparison with incomplete or missing results."""

‎tests/core/test_existing_alerts.py‎

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -161,14 +161,10 @@ def test_blocking_cve_persists_across_a_version_change(core, change_type, strict
161161
alert = {**_alert("persistent", alert_type="criticalCVE"), "props": {"cveId": "CVE-2025-12345"}}
162162
core.sdk.diffscans.create_from_ids.side_effect = None
163163
core.sdk.diffscans.create_from_ids.return_value = {"diff_scan": {"id": "comparison"}}
164-
core.sdk.diffscans.get.return_value = {
165-
"diff_scan": {
166-
"artifacts": {
167-
change_type: [_diff_artifact(change_type, "a2", "alpha", version="2.0.0")],
168-
"replaced": [_diff_artifact("replaced", "a1", "alpha", [alert])],
169-
},
170-
},
171-
}
164+
artifacts = {key: [] for key in ("added", "removed", "unchanged", "replaced", "updated")}
165+
artifacts[change_type] = [_diff_artifact(change_type, "a2", "alpha", version="2.0.0")]
166+
artifacts["replaced"] = [_diff_artifact("replaced", "a1", "alpha", [alert])]
167+
core.sdk.diffscans.get.return_value = {"diff_scan": {"artifacts": artifacts}}
172168
_stream_through_sdk(
173169
core,
174170
_scan_artifact("a2", "alpha", [alert], version="2.0.0"),

‎tests/core/test_exit_codes.py‎

Lines changed: 124 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,13 @@
66
errors, and Ctrl+C exits 130. See socketsecurity.exit_codes.
77
"""
88
import sys
9+
from contextlib import nullcontext
10+
from types import SimpleNamespace
911
from unittest.mock import MagicMock
1012

1113
import pytest
14+
import requests
15+
from socketdev.diffscans import DiffScans
1216
from socketdev.exceptions import (
1317
APIFailure,
1418
APIInsufficientPermissions,
@@ -137,8 +141,13 @@ def test_repo_creation_failure_raises_infrastructure_error(core):
137141
# --- Incomplete comparisons ----------------------------------------------------------
138142

139143

140-
@pytest.fixture(params=[{}, None, "omitted"])
144+
EMPTY_ARTIFACTS = {"added": [], "removed": [], "unchanged": [], "replaced": [], "updated": []}
145+
146+
147+
@pytest.fixture(params=[{}, None, "omitted", "top-level"])
141148
def incomplete_response(request):
149+
if request.param == "top-level":
150+
return {"incomplete": True}
142151
scan = {"id": "diff-scan-1", "incomplete": True}
143152
if request.param != "omitted":
144153
scan["artifacts"] = request.param
@@ -164,12 +173,124 @@ def test_incomplete_comparison_does_not_fall_back_to_streaming(core, incomplete_
164173
core.sdk.fullscans.stream_diff.assert_not_called()
165174

166175

176+
@pytest.fixture(params=[
177+
pytest.param({"incomplete": False, "artifacts": None}, id="null-artifacts-complete"),
178+
pytest.param({"artifacts": None}, id="null-artifacts-flag-unset"),
179+
pytest.param({}, id="artifacts-absent-flag-unset"),
180+
pytest.param({"artifacts": []}, id="artifacts-not-an-object"),
181+
pytest.param({"artifacts": {}}, id="empty-artifacts-object"),
182+
pytest.param({"artifacts": {**EMPTY_ARTIFACTS, "added": None}}, id="null-added"),
183+
pytest.param({"artifacts": {**EMPTY_ARTIFACTS, "unchanged": None}}, id="null-unchanged"),
184+
pytest.param({"artifacts": {**EMPTY_ARTIFACTS, "removed": {}}}, id="removed-not-a-list"),
185+
pytest.param({"artifacts": {**EMPTY_ARTIFACTS, "updated": "invalid"}}, id="updated-not-a-list"),
186+
pytest.param({"artifacts": {key: [] for key in EMPTY_ARTIFACTS if key != "replaced"}}, id="missing-replaced"),
187+
])
188+
def invalid_artifacts_response(request):
189+
return {"diff_scan": {"id": "diff-scan-1", **request.param}}
190+
191+
192+
def test_invalid_artifacts_do_not_fall_back_to_streaming(core, invalid_artifacts_response):
193+
core.sdk.diffscans.create_from_ids.return_value = {"diff_scan": {"id": "diff-scan-1"}}
194+
core.sdk.diffscans.get.return_value = invalid_artifacts_response
195+
196+
with pytest.raises(IncompleteComparisonError, match="missing a valid artifacts"):
197+
core.get_added_and_removed_packages("head", "new")
198+
199+
core.sdk.fullscans.stream_diff.assert_not_called()
200+
201+
202+
@pytest.mark.parametrize("argv, expected", [
203+
([], 3),
204+
(["--exit-code-on-api-error", "42"], 42),
205+
(["--disable-blocking"], 0),
206+
(["--disable-blocking", "--exit-code-on-api-error", "42"], 0),
207+
])
208+
@pytest.mark.parametrize("strict", [[], ["--strict-blocking"]], ids=["standard", "strict"])
209+
def test_invalid_artifacts_follow_exit_policy(monkeypatch, caplog, argv, expected, strict):
210+
sdk = MagicMock()
211+
sdk.org.get.return_value = {"organizations": {"org-id": {"slug": "acme"}}}
212+
sdk.diffscans.create_from_ids.return_value = {"diff_scan": {"id": "diff-scan-1"}}
213+
sdk.diffscans.get.return_value = {"diff_scan": {"id": "diff-scan-1", "artifacts": {}}}
214+
monkeypatch.setattr(socketcli, "build_socket_sdk", lambda config: sdk)
215+
monkeypatch.setattr(socketcli, "StreamingLogs", lambda **kwargs: nullcontext(MagicMock()))
216+
monkeypatch.setattr(socketcli, "apply_git_context", lambda config: (False, None))
217+
monkeypatch.setattr(Core, "has_manifest_files", lambda self, files: True)
218+
monkeypatch.setattr(Core, "create_full_scan", lambda *args, **kwargs: SimpleNamespace(id="new"))
219+
report = MagicMock()
220+
monkeypatch.setattr(socketcli.OutputHandler, "handle_output", report)
221+
monkeypatch.setattr(sys, "argv", [
222+
"socketcli", "--api-token", "test", "--scm", "api", "--integration", "api",
223+
"--repo", "repo", "--branch", "feature", "--enable-diff", "--base-scan-id", "head",
224+
"--files", '["package.json"]', *strict, *argv,
225+
])
226+
227+
with pytest.raises(SystemExit) as result:
228+
socketcli.cli()
229+
230+
assert result.value.code == expected
231+
assert "missing a valid artifacts.added list" in caplog.text
232+
sdk.diffscans.get.assert_called_once()
233+
sdk.fullscans.stream_diff.assert_not_called()
234+
report.assert_not_called()
235+
236+
237+
class StreamingFallback(Exception):
238+
"""Sentinel for a streaming comparison call."""
239+
240+
241+
@pytest.mark.parametrize("response", [
242+
pytest.param({}, id="empty-dict"),
243+
pytest.param({"diff_scan": None}, id="diff-scan-null"),
244+
pytest.param({"diff_scan": []}, id="diff-scan-not-an-object"),
245+
])
246+
def test_response_without_diff_scan_object_falls_back_to_streaming(core, response):
247+
core.sdk.diffscans.create_from_ids.return_value = {"diff_scan": {"id": "diff-scan-1"}}
248+
core.sdk.diffscans.get.return_value = response
249+
core.sdk.fullscans.stream_diff.side_effect = StreamingFallback
250+
251+
with pytest.raises(RuntimeError, match="no diff_scan object"):
252+
core.get_diff_scan_artifacts("head", "new")
253+
254+
with pytest.raises(StreamingFallback):
255+
core.get_added_and_removed_packages("head", "new")
256+
core.sdk.fullscans.stream_diff.assert_called_once()
257+
258+
259+
def test_http_204_through_the_sdk_falls_back_to_streaming(core):
260+
"""The SDK maps HTTP 204 to an empty response."""
261+
no_content = requests.Response()
262+
no_content.status_code = 204
263+
no_content._content = b""
264+
api = MagicMock()
265+
api.do_request.return_value = no_content
266+
core.sdk.diffscans = DiffScans(api)
267+
core.sdk.diffscans.create_from_ids = MagicMock(return_value={"diff_scan": {"id": "diff-scan-1"}})
268+
core.sdk.fullscans.stream_diff.side_effect = StreamingFallback
269+
270+
with pytest.raises(StreamingFallback):
271+
core.get_added_and_removed_packages("head", "new")
272+
273+
274+
def test_omitted_unchanged_bucket_is_still_a_result(core):
275+
core.cli_config = CliConfig(api_token="test", repo="repo")
276+
core.sdk.diffscans.create_from_ids.return_value = {"diff_scan": {"id": "diff-scan-1"}}
277+
core.sdk.diffscans.get.return_value = {"diff_scan": {
278+
"id": "diff-scan-1", "incomplete": False,
279+
"artifacts": {**EMPTY_ARTIFACTS, "unchanged": None},
280+
}}
281+
282+
artifacts = core.get_diff_scan_artifacts("head", "new")
283+
284+
assert core.sdk.diffscans.get.call_args.kwargs["params"]["omit_unchanged"] == "true"
285+
assert artifacts.unchanged == []
286+
287+
167288
def test_complete_comparison_is_returned(core):
168289
core.sdk.diffscans.create_from_ids.return_value = {"diff_scan": {"id": "diff-scan-1"}}
169290
core.sdk.diffscans.get.return_value = {
170-
"diff_scan": {"id": "diff-scan-1", "incomplete": False, "artifacts": {}},
291+
"diff_scan": {"id": "diff-scan-1", "incomplete": False, "artifacts": EMPTY_ARTIFACTS},
171292
}
172293

173294
artifacts = core.get_diff_scan_artifacts("head", "new")
174295

175-
assert artifacts.added == []
296+
assert artifacts.to_dict() == EMPTY_ARTIFACTS

0 commit comments

Comments
 (0)