Skip to content

Commit 1b80894

Browse files
committed
Fail on missing existing alerts and preserve distinct findings
1 parent 60ddc10 commit 1b80894

8 files changed

Lines changed: 237 additions & 25 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@ code; see [Exit codes](README.md#exit-codes).
2323

2424
- An incomplete scan comparison fails the run with the infrastructure-error
2525
code.
26-
- GitLab security report IDs for CVE findings include the advisory ID, so
27-
existing CVE findings get new IDs once.
26+
- GitLab security report IDs include the ecosystem, full package coordinate and
27+
advisory ID, so existing findings get new IDs once.
2828

2929
### Fixed
3030

‎docs/cli-reference.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -643,7 +643,7 @@ Security issues detected by Socket Security:
643643
644644
- **Diff Mode Only**: The flag only works in diff mode (with SCM integration). In API mode, a warning is logged.
645645
- **Error-Level Only**: Only fails on `error=True` alerts (blocking severity), not warnings.
646-
- **Existing alerts come from the full scan**: The scan comparison doesn't carry alerts on unchanged packages, so the CLI reads them from the new full scan, at the cost of one more API request per run. If that request fails, the run fails with the infrastructure-error code rather than passing without them.
646+
- **Existing alerts come from the full scan**: The scan comparison doesn't carry alerts on unchanged packages, so the CLI reads them from the new full scan, at the cost of one more API request per run. If that request fails or omits an unchanged package, the run fails with the infrastructure-error code rather than passing without them.
647647
- **PR/MR comments**: Existing alerts are listed in their own table after the new ones, blocking first. `@SocketSecurity ignore` applies to them too. Very large sets are cut off before the comment reaches GitHub's size limit, with a link to the full report.
648648
- **Priority**: `--disable-blocking` takes precedence - if both flags are set, the build will always pass.
649649
- **First Scan**: On the very first scan of a repository, there are no "existing" violations, so behavior is identical to standard mode.

‎socketsecurity/core/__init__.py‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2549,8 +2549,8 @@ def add_existing_alerts_from_full_scan(
25492549
25502550
Skipped when any unchanged package already has alerts: the comparison then
25512551
came from an endpoint that includes them, such as the streaming fallback.
2552-
A failed fetch raises, because reporting existing alerts as absent would
2553-
let ``--strict-blocking`` pass a run it should fail.
2552+
A failed fetch or an unmatched package raises, because reporting existing
2553+
alerts as absent would let ``--strict-blocking`` pass a run it should fail.
25542554
"""
25552555
if any(package.alerts for package in unchanged_packages.values()):
25562556
log.debug("The comparison already includes alerts on unchanged packages")
@@ -2586,9 +2586,9 @@ def add_existing_alerts_from_full_scan(
25862586
f"unchanged packages from full scan {full_scan_id} in {time.time() - start:.2f}s"
25872587
)
25882588
if matched < len(unchanged_packages):
2589-
log.warning(
2590-
f"{len(unchanged_packages) - matched} unchanged packages were not found in "
2591-
f"full scan {full_scan_id}, so their existing alerts are not reported"
2589+
raise InfrastructureError(
2590+
f"{len(unchanged_packages) - matched} of {len(unchanged_packages)} unchanged packages "
2591+
f"were not found in full scan {full_scan_id}; unable to evaluate all existing alerts."
25922592
)
25932593

25942594
@staticmethod

‎socketsecurity/core/messages.py‎

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -620,14 +620,19 @@ def generate_uuid_from_alert_gitlab(alert: Issue) -> str:
620620
Generate deterministic UUID for vulnerability based on alert properties.
621621
This ensures consistent IDs across runs for the same vulnerability.
622622
"""
623-
# Create unique string from alert key properties
624-
unique_str = f"{alert.pkg_name}:{alert.pkg_version}:{alert.type}:{alert.severity}"
625-
# Every CVE of one severity on a package shares a type, so the advisory ID
626-
# keeps them apart. It's appended only when present, so other findings
627-
# keep the IDs GitLab already tracks them by.
623+
# Names alone collide across ecosystems and namespaces. Full scans and
624+
# comparisons use different PURL prefixes, so normalize those while
625+
# retaining the namespace and version in the package coordinate.
626+
ecosystem = getattr(alert, "pkg_type", "") or ""
627+
purl = getattr(alert, "purl", "") or f"{alert.pkg_name}@{alert.pkg_version}"
628+
coordinate = purl.removeprefix("pkg:").lstrip("/").removeprefix(f"{ecosystem}/")
629+
# Every CVE of one severity on a package shares a type, so keep the
630+
# advisory ID as well. Manifest details do not affect finding identity.
628631
advisory = alert.advisory_id() if hasattr(alert, "advisory_id") else ""
629-
if advisory:
630-
unique_str += f":{advisory}"
632+
unique_str = json.dumps(
633+
[ecosystem, coordinate, alert.type, alert.severity, advisory],
634+
separators=(",", ":"),
635+
)
631636

632637
# Generate UUID5 (deterministic) from namespace and unique string
633638
namespace = uuid.UUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8') # DNS namespace
@@ -1151,6 +1156,7 @@ def security_comment_template(diff: Diff, config=None) -> str:
11511156
# section is the open-ended part of the security comment, so it stops adding
11521157
# rows at this size and links to the full report for the rest.
11531158
SECURITY_COMMENT_SIZE_BUDGET = 60000
1159+
EXISTING_ALERTS_TRUNCATED_MARKER = "<!-- socket-existing-alerts-truncated -->"
11541160

11551161
@staticmethod
11561162
def existing_comment_alerts(diff: Diff, config) -> list:
@@ -1221,6 +1227,7 @@ def existing_alerts_section(
12211227
section += closing
12221228
if shown < len(alerts):
12231229
section += (
1230+
f"\n{Messages.EXISTING_ALERTS_TRUNCATED_MARKER}\n"
12241231
f"\n{len(alerts) - shown} more existing alert(s) are not shown here to keep "
12251232
f"this comment within GitHub's size limit. See the [full report]({view_report_url}?action=error%2Cwarn).\n"
12261233
)

‎socketsecurity/core/scm_comments.py‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,12 @@ def process_updated_security_comment(
230230
lines = []
231231
ignore_section = False
232232
kept_alert = False # Whether any alert row survived the ignore commands
233+
# Individual ignore commands only account for the rows we can see. A
234+
# truncated comment still has undisplayed findings unless ignore-all was
235+
# explicitly requested, even after its last visible row is removed.
236+
has_undisplayed_alerts = not ignore_all and any(
237+
Messages.EXISTING_ALERTS_TRUNCATED_MARKER in line for line in comment.body_list
238+
)
233239
pkg_name = pkg_version = "" # Track current package and version
234240

235241
# Loop through the comment lines
@@ -270,9 +276,8 @@ def process_updated_security_comment(
270276
elif not ignore_section:
271277
lines.append(line)
272278

273-
# Every row was ignored, so drop the table rather than leaving the caution
274-
# banner sitting above an empty one.
275-
if not kept_alert:
279+
# Drop a fully resolved table only when no undisplayed findings remain.
280+
if not kept_alert and not has_undisplayed_alerts:
276281
return Messages.security_comment_no_alerts_template(
277282
Comments.extract_report_url("\n".join(comment.body_list))
278283
)

‎tests/core/test_alert_consolidation.py‎

Lines changed: 57 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
"""
88
from unittest.mock import Mock
99

10+
import pytest
11+
1012
from socketsecurity.config import CliConfig
1113
from socketsecurity.core import Core
1214
from socketsecurity.core.classes import Diff, Issue
@@ -126,11 +128,60 @@ def test_gitlab_report_keeps_each_advisory_as_its_own_finding():
126128
assert len(set(ids)) == 2
127129

128130

129-
def test_gitlab_ids_for_findings_without_an_advisory_are_unchanged():
130-
"""GitLab tracks findings by ID across pipelines, so these must not move."""
131-
import uuid
131+
@pytest.mark.parametrize("advisory", ["", "GHSA-aaaa-aaaa-aaaa"])
132+
@pytest.mark.parametrize("coordinates", [
133+
(("npm", "lodash@4.17.20"), ("pypi", "lodash@4.17.20")),
134+
(("maven", "org.first/lodash@4.17.20"), ("maven", "org.second/lodash@4.17.20")),
135+
])
136+
def test_gitlab_report_keeps_distinct_package_coordinates(advisory, coordinates):
137+
alerts = []
138+
for index, (ecosystem, purl) in enumerate(coordinates):
139+
alert = _cve(advisory, pkg_type=ecosystem)
140+
alert.purl = purl
141+
alert.manifests = f"manifest-{index}.json"
142+
alerts.append(alert)
143+
diff = Diff(new_alerts=alerts[:1], unchanged_alerts=alerts[1:])
144+
145+
report = Messages.create_security_comment_gitlab(diff)
146+
147+
ids = {v["id"] for v in report["vulnerabilities"]}
148+
assert len(ids) == 2
149+
assert {f["path"] for f in report["dependency_files"]} == {"manifest-0.json", "manifest-1.json"}
150+
# IDs remain stable if either package is the only one present next time.
151+
for alert in alerts:
152+
single = Messages.create_security_comment_gitlab(Diff(new_alerts=[alert]))
153+
assert single["vulnerabilities"][0]["id"] in ids
154+
155+
156+
def test_gitlab_report_deduplicates_a_finding_listed_as_new_and_existing():
157+
first = _cve("GHSA-aaaa-aaaa-aaaa")
158+
repeat = _cve("GHSA-aaaa-aaaa-aaaa")
159+
diff = Diff(new_alerts=[first], unchanged_alerts=[repeat])
132160

133-
alert = Issue(pkg_name="a", pkg_version="1.0.0", type="malware", severity="critical", props={})
134-
expected = uuid.uuid5(uuid.UUID("6ba7b810-9dad-11d1-80b4-00c04fd430c8"), "a:1.0.0:malware:critical")
161+
report = Messages.create_security_comment_gitlab(diff)
162+
163+
assert len(report["vulnerabilities"]) == 1
164+
165+
166+
@pytest.mark.parametrize("purl", [
167+
"org.first/lodash@4.17.20", "maven/org.first/lodash@4.17.20",
168+
"pkg:maven/org.first/lodash@4.17.20",
169+
])
170+
def test_gitlab_ids_are_stable_across_full_scan_and_diff_purl_formats(purl):
171+
alert = _cve("GHSA-aaaa-aaaa-aaaa", pkg_type="maven")
172+
alert.purl = "org.first/lodash@4.17.20"
173+
expected = Messages.generate_uuid_from_alert_gitlab(alert)
174+
alert.purl = purl
175+
176+
assert Messages.generate_uuid_from_alert_gitlab(alert) == expected
177+
178+
179+
def test_gitlab_ids_for_findings_without_an_advisory_ignore_manifest_changes():
180+
alert = Issue(
181+
pkg_type="npm", pkg_name="a", pkg_version="1.0.0", purl="a@1.0.0",
182+
type="malware", severity="critical", props={}, manifests="package.json",
183+
)
184+
expected = Messages.generate_uuid_from_alert_gitlab(alert)
185+
alert.manifests = "nested/package.json"
135186

136-
assert Messages.generate_uuid_from_alert_gitlab(alert) == str(expected)
187+
assert Messages.generate_uuid_from_alert_gitlab(alert) == expected

‎tests/core/test_existing_alerts.py‎

Lines changed: 75 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
report and FOSSA-format output.
88
"""
99
import json
10+
import re
1011
from pathlib import Path
1112
from types import SimpleNamespace
1213
from unittest.mock import Mock
@@ -21,9 +22,11 @@
2122

2223
from socketsecurity.config import CliConfig
2324
from socketsecurity.core import Core
24-
from socketsecurity.core.classes import Diff, Issue
25+
from socketsecurity.core.classes import Comment, Diff, Issue
2526
from socketsecurity.core.messages import Messages
27+
from socketsecurity.core.scm_comments import Comments
2628
from socketsecurity.core.socket_config import SocketConfig
29+
from socketsecurity.exit_codes import InfrastructureError
2730
from socketsecurity.output import OutputHandler
2831

2932
BUCKETS = ("added", "removed", "unchanged", "replaced", "updated")
@@ -209,6 +212,39 @@ def test_failed_full_scan_fetch_fails_the_run(core):
209212
core.create_new_diff(["/repo"], params, explicit_files=["/repo/package.json"])
210213

211214

215+
@pytest.mark.parametrize("flags", [
216+
("--strict-blocking",), ("--enable-gitlab-security",), ("--legal-format", "fossa"),
217+
])
218+
@pytest.mark.parametrize("response_kind", ["missing", "malformed", "empty"])
219+
def test_incomplete_existing_alert_data_fails_the_run(core, flags, response_kind):
220+
"""A successful response can still omit packages, including SDK parse failures."""
221+
core.cli_config = CliConfig.from_args(["--api-token", "test", *flags])
222+
core.sdk.fullscans.stream_diff.return_value = _diff_response(unchanged=[
223+
_diff_artifact("unchanged", "u1", "gamma"),
224+
_diff_artifact("unchanged", "u2", "delta"),
225+
])
226+
artifacts = [_scan_artifact("u2", "delta", [])]
227+
if response_kind == "malformed":
228+
broken = _scan_artifact("u1", "gamma", [_alert("k3")])
229+
del broken["alerts"][0]["key"]
230+
artifacts.append(broken)
231+
elif response_kind == "empty":
232+
artifacts = []
233+
core.sdk.fullscans.stream.return_value = _scan_response(*artifacts)
234+
params = FullScanParams(repo="repo", branch="feature")
235+
params.include_license_details = True
236+
237+
with pytest.raises(InfrastructureError, match="unchanged packages.*full scan new"):
238+
core.create_new_diff(["/repo"], params, explicit_files=["/repo/package.json"])
239+
240+
241+
def test_matched_package_without_alerts_is_a_clean_result(core):
242+
diff = _run(core, "--strict-blocking", scan_alerts=[])
243+
244+
assert diff.unchanged_alerts == []
245+
core.sdk.fullscans.stream.assert_called_once()
246+
247+
212248
# --- PR comment ------------------------------------------------------------------------
213249

214250

@@ -293,6 +329,44 @@ def test_pr_comment_stays_within_the_size_budget(monkeypatch):
293329
assert "Existing alerts (20)" in comment
294330

295331

332+
@pytest.mark.parametrize("budget", [6000, 1])
333+
def test_ignoring_visible_alerts_keeps_the_truncation_warning(monkeypatch, budget):
334+
monkeypatch.setattr(Messages, "SECURITY_COMMENT_SIZE_BUDGET", budget)
335+
diff = _comment_diff(existing=[_issue(f"pkg{i}") for i in range(20)])
336+
body = Messages.security_comment_template(diff, _config())
337+
visible = re.findall(r"<!-- start-socket-alert-(.*?) -->", body)
338+
assert len(visible) < len(diff.unchanged_alerts)
339+
if budget > 1:
340+
assert visible
341+
comments = {"ignore": [
342+
Comment(body_list=[f"@SocketSecurity ignore npm/{package}"])
343+
for package in visible
344+
]}
345+
assert Comments.remove_alerts(comments, diff.unchanged_alerts)
346+
347+
updated = Comments.process_security_comment(Comment(body_list=body.splitlines()), comments)
348+
349+
assert "No dependency alerts to report" not in updated
350+
assert "more existing alert(s) are not shown" in updated
351+
assert "[full report](https://socket.dev/diff?action=error%2Cwarn)" in updated
352+
# Reprocessing the comment must not lose the undisplayed findings either.
353+
assert Comments.process_security_comment(Comment(body_list=updated.splitlines()), comments) == updated
354+
355+
356+
def test_ignore_all_clears_even_truncated_existing_alerts(monkeypatch):
357+
monkeypatch.setattr(Messages, "SECURITY_COMMENT_SIZE_BUDGET", 6000)
358+
diff = _comment_diff(existing=[_issue(f"pkg{i}") for i in range(20)])
359+
body = Messages.security_comment_template(diff, _config())
360+
assert "more existing alert(s) are not shown" in body
361+
comments = {"ignore": [Comment(body_list=["@SocketSecurity ignore-all"])]}
362+
363+
updated = Comments.process_security_comment(Comment(body_list=body.splitlines()), comments)
364+
365+
assert "No dependency alerts to report" in updated
366+
assert "more existing alert(s)" not in updated
367+
assert "[View full report](https://socket.dev/diff)" in updated
368+
369+
296370
def test_existing_license_violations_use_the_license_row():
297371
license_alert = _issue("gamma")
298372
license_alert.type = "licenseSpdxDisj"

‎tests/unit/test_disable_ignore.py‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,17 @@
11
"""Tests for the --disable-ignore flag."""
22

3+
import sys
4+
from contextlib import nullcontext
35
from dataclasses import dataclass
6+
from unittest.mock import MagicMock, Mock
47

8+
import pytest
9+
10+
from socketsecurity import socketcli
511
from socketsecurity.config import CliConfig
612
from socketsecurity.core.classes import Comment, Diff, Issue
713
from socketsecurity.core.messages import Messages
14+
from socketsecurity.core.scm.github import Github
815
from socketsecurity.core.scm_comments import Comments
916

1017
# --- CLI flag parsing tests ---
@@ -131,6 +138,74 @@ def test_ignore_all_suppresses_all_alerts(self):
131138
assert len(result) == 0
132139

133140

141+
@pytest.mark.parametrize("command", [
142+
"@SocketSecurity ignore npm/lodash@4.17.21", "@SocketSecurity ignore-all",
143+
])
144+
@pytest.mark.parametrize("authorized, disable_ignore, expected_exit", [
145+
(True, False, 0), (True, True, 1), (False, False, 1), (False, True, 1),
146+
])
147+
def test_cli_existing_blocker_respects_ignore_authorization_and_flag(
148+
monkeypatch, command, authorized, disable_ignore, expected_exit
149+
):
150+
"""Exercise the SCM CLI path with real ignore filtering and exit-code handling."""
151+
argv = [
152+
"socketcli", "--api-token", "test", "--scm", "github", "--strict-blocking",
153+
"--repo", "repo", "--branch", "feature", "--pr-number", "42",
154+
"--files", '["package.json"]',
155+
]
156+
if disable_ignore:
157+
argv.append("--disable-ignore")
158+
monkeypatch.setattr(sys, "argv", argv)
159+
for key, value in {
160+
"GH_API_TOKEN": "test", "GITHUB_EVENT_NAME": "pull_request",
161+
"EVENT_ACTION": "synchronize", "GITHUB_REPOSITORY": "acme/repo",
162+
"DEFAULT_BRANCH": "false",
163+
}.items():
164+
monkeypatch.setenv(key, value)
165+
166+
alert = _make_alert()
167+
diff = Diff(id="scan", new_alerts=[], unchanged_alerts=[alert])
168+
diff.diff_url = "https://socket.dev/diff"
169+
raw_comments = {
170+
1: _make_comment(command),
171+
2: _make_comment("<!-- socket-security-comment-actions -->", comment_id=2),
172+
}
173+
monkeypatch.setattr(Github, "get_comments_for_pr", lambda self: Comments.check_for_socket_comments(
174+
raw_comments, is_authorized=lambda comment: authorized,
175+
))
176+
posted = Mock()
177+
monkeypatch.setattr(Github, "add_socket_comments", posted)
178+
monkeypatch.setattr(Github, "handle_ignore_reactions", Mock())
179+
sdk = MagicMock()
180+
sdk.org.get.return_value = {"organizations": {"org-id": {"slug": "acme"}}}
181+
monkeypatch.setattr(socketcli, "build_socket_sdk", Mock(return_value=sdk))
182+
client = Mock()
183+
monkeypatch.setattr(socketcli, "CliClient", Mock(return_value=client))
184+
monkeypatch.setattr(socketcli, "StreamingLogs", lambda **kwargs: nullcontext(Mock()))
185+
monkeypatch.setattr(socketcli, "apply_git_context", lambda config: (False, None))
186+
scan = Mock(return_value=diff)
187+
monkeypatch.setattr(socketcli.Core, "create_new_diff", scan)
188+
monkeypatch.setattr(socketcli.Core, "has_manifest_files", Mock(return_value=True))
189+
monkeypatch.setattr(socketcli.OutputHandler, "handle_output", Mock())
190+
191+
with pytest.raises(SystemExit) as result:
192+
socketcli.cli()
193+
194+
assert result.value.code == expected_exit
195+
scan.assert_called_once()
196+
posted.assert_called_once()
197+
security_body = posted.call_args.args[0]
198+
if expected_exit == 0:
199+
assert diff.unchanged_alerts == []
200+
assert "No dependency alerts to report" in security_body
201+
events = client.post_telemetry_events.call_args.args[1]
202+
assert [event["artifact_purl"] for event in events] == [alert.purl]
203+
else:
204+
assert diff.unchanged_alerts == [alert]
205+
assert "Existing alerts (1)" in security_body
206+
client.post_telemetry_events.assert_not_called()
207+
208+
134209
# --- Comment output tests ---
135210

136211
@dataclass

0 commit comments

Comments
 (0)