From 6872a4115439ba5ecec8148f8baccef23d2aa3ed Mon Sep 17 00:00:00 2001 From: David Larsen Date: Fri, 20 Nov 2026 14:59:05 -0500 Subject: [PATCH 1/7] List every existing advisory under --strict-blocking Existing alerts for --strict-blocking are read from the new full scan through socketdev's fullscans.stream(). socketdev 3.6.2 merged alerts that share a type and severity on a package, so only the first CVE of each severity reached the CLI. The Existing alerts table and the EXISTING blocking issues count undercounted (3 instead of 8 in the repro), and when the first CVE of a group was resolved or triaged to monitor or ignore, the Block CVEs behind it were dropped and the run passed. socketdev 3.6.3 keys merged alerts on the advisory ID and keeps the most severe action. Pin it. The CLI's own consolidation already keeps the advisory ID (Issue.consolidation_key) and filters on error/warn before it dedupes, so no CLI logic changes. The new tests run the real FullScans.stream() over a canned response, so they fail if the pinned SDK collapses advisories again. Bumps the version to 2.13.1. uv.lock needs `uv lock` once socketdev 3.6.3 is published. --- CHANGELOG.md | 12 +++++ pyproject.toml | 4 +- socketsecurity/__init__.py | 2 +- tests/core/test_existing_alerts.py | 81 ++++++++++++++++++++++++++++++ 4 files changed, 96 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ff28e721..86307178 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +## 2.13.1 + +### Fixed + +- `--strict-blocking` lists and counts every advisory on an unchanged package. + Existing alerts are read through the SDK, which kept one alert per alert type + and severity, so a package with six Critical CVEs showed one, and the + "EXISTING blocking issues" count was too low. Requires `socketdev` 3.6.3. +- A Block-action CVE on an unchanged package now fails the run even when + another CVE of the same severity on that package is triaged to monitor or + ignore. Before, the triaged CVE could stand in for both and the run passed. + ## 2.13.0 ### Upgrade notes diff --git a/pyproject.toml b/pyproject.toml index 0924672a..c21b4ecb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ build-backend = "hatchling.build" [project] name = "socketsecurity" -version = "2.13.0" +version = "2.13.1" requires-python = ">= 3.11" license = {"file" = "LICENSE"} dependencies = [ @@ -16,7 +16,7 @@ dependencies = [ "gitpython==3.2.1", "packaging==26.3", "python-dotenv==1.2.4", - "socketdev==3.6.2", + "socketdev==3.6.3", "beautifulsoup4==4.15.0", "markdown==3.11.3", "brotli==1.2.1; platform_python_implementation == 'CPython'", diff --git a/socketsecurity/__init__.py b/socketsecurity/__init__.py index 08835ec8..a3c8f69d 100644 --- a/socketsecurity/__init__.py +++ b/socketsecurity/__init__.py @@ -1,4 +1,4 @@ __author__ = 'socket.dev' -__version__ = '2.13.0' +__version__ = '2.13.1' USER_AGENT_NAME = 'socket-python-cli' USER_AGENT = f'{USER_AGENT_NAME}/{__version__}' diff --git a/tests/core/test_existing_alerts.py b/tests/core/test_existing_alerts.py index 139577dd..b404e148 100644 --- a/tests/core/test_existing_alerts.py +++ b/tests/core/test_existing_alerts.py @@ -16,6 +16,7 @@ from socketdev.exceptions import APIFailure from socketdev.fullscans import ( FullScanParams, + FullScans, FullScanStreamResponse, StreamDiffResponse, ) @@ -245,6 +246,86 @@ def test_matched_package_without_alerts_is_a_clean_result(core): core.sdk.fullscans.stream.assert_called_once() +# --- Existing advisories read through the SDK's full-scan stream ------------------------ +# +# The tests above stub ``fullscans.stream``. These run the real SDK method over a canned +# HTTP response, so they also cover the SDK's merging of duplicate alerts: socketdev +# 3.6.2 kept one alert per type and severity, which dropped every other CVE of that +# severity on a package, along with any Block action it carried. + +HANDLEBARS_CRITICAL_ADVISORIES = [ + ("GHSA-8r5x-fm3f-whwj", ""), + ("GHSA-p8wg-vrv2-v86f", ""), + ("GHSA-2w6w-674q-4c4q", ""), + ("GHSA-w457-6q6x-cgp9", "CVE-2019-19919"), + ("GHSA-765h-qjxv-5f44", "CVE-2021-23383"), + ("GHSA-f2jv-r9rf-7988", "CVE-2021-23369"), +] + + +def _cve_alert(ghsa_id, cve_id, action="error"): + return { + "key": f"key-{ghsa_id}", + "type": "criticalCVE", + "severity": "critical", + "category": "vulnerability", + "props": {"ghsaId": ghsa_id, "cveId": cve_id, "title": f"Advisory {ghsa_id}"}, + "action": action, + } + + +def _stream_through_sdk(core, *artifacts): + """Serve ``artifacts`` as the full-scan NDJSON body and parse it with the real SDK.""" + response = Mock(status_code=200, text="\n".join(json.dumps(a) for a in artifacts)) + api = Mock(request_timeout=30) + api.do_request.return_value = response + core.sdk.fullscans.stream.side_effect = FullScans(api).stream + + +def _existing_only_diff(core, *scan_artifacts): + core.cli_config = CliConfig.from_args(["--api-token", "test", "--strict-blocking"]) + core.sdk.fullscans.stream_diff.return_value = _diff_response(unchanged=[ + _diff_artifact("unchanged", artifact["id"], artifact["name"]) for artifact in scan_artifacts + ]) + _stream_through_sdk(core, *scan_artifacts) + params = FullScanParams(repo="repo", branch="feature") + params.include_license_details = True + return core.create_new_diff(["/repo"], params, explicit_files=["/repo/package.json"]) + + +def test_every_same_severity_advisory_on_an_unchanged_package_is_kept(core, caplog): + alerts = [_cve_alert(ghsa, cve) for ghsa, cve in HANDLEBARS_CRITICAL_ADVISORIES] + + with caplog.at_level("INFO"): + diff = _existing_only_diff(core, _scan_artifact("u1", "handlebars", alerts)) + + assert sorted(a.advisory_id() for a in diff.unchanged_alerts) == sorted( + ghsa.upper() for ghsa, _ in HANDLEBARS_CRITICAL_ADVISORIES + ) + assert all(a.error for a in diff.unchanged_alerts) + assert "Loaded 6 alerts for 1 of 1 unchanged packages" in caplog.text + assert not _handler(strict_blocking=True).report_pass(diff) + + comment = Messages.security_comment_template(diff, _config()) + assert "Existing alerts (6)" in comment + for ghsa, _ in HANDLEBARS_CRITICAL_ADVISORIES: + assert ghsa.upper() in comment + + +@pytest.mark.parametrize("triaged_action", ["ignore", "monitor"]) +def test_a_triaged_advisory_does_not_hide_a_blocking_one_on_the_same_package(core, triaged_action): + """The triaged advisory comes first in the stream; the Block one must still fail the run.""" + alerts = [ + _cve_alert("GHSA-w457-6q6x-cgp9", "CVE-2019-19919", action=triaged_action), + _cve_alert("GHSA-765h-qjxv-5f44", "CVE-2021-23383", action="error"), + ] + + diff = _existing_only_diff(core, _scan_artifact("u1", "handlebars", alerts)) + + assert [(a.advisory_id(), a.error) for a in diff.unchanged_alerts] == [("GHSA-765H-QJXV-5F44", True)] + assert not _handler(strict_blocking=True).report_pass(diff) + + # --- PR comment ------------------------------------------------------------------------ From 4a4354f75980f88b772d17aa3028a8f753985ee2 Mon Sep 17 00:00:00 2001 From: David Larsen Date: Fri, 20 Nov 2026 17:06:22 -0500 Subject: [PATCH 2/7] Note the report output change in the changelog Full-scan mode with --enable-json, --enable-sarif or --enable-gitlab-security reads alerts through the same SDK stream, so those reports now list every advisory on a package too. Diff mode's existing alerts in the GitLab and FOSSA-format output change the same way. --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 86307178..da621678 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,12 @@ - A Block-action CVE on an unchanged package now fails the run even when another CVE of the same severity on that package is triaged to monitor or ignore. Before, the triaged CVE could stand in for both and the run passed. +- In full-scan mode, the `--enable-json`, `--enable-sarif` and + `--enable-gitlab-security` reports now list every advisory on a package. + Before, they listed one per alert type and severity, so expect more alerts, + and more with a Block action, in these reports. In diff mode the same + applies to existing alerts in the `--enable-gitlab-security` and + `--legal-format fossa` output. ## 2.13.0 From 803024ac11aac34166aea05d3c0a00cbccde1b12 Mon Sep 17 00:00:00 2001 From: David Larsen Date: Fri, 20 Nov 2026 17:21:42 -0500 Subject: [PATCH 3/7] Pin socketdev 3.6.4 socketdev 3.6.3 was released without the advisory dedupe fix, which now ships as 3.6.4. uv.lock still needs `uv lock` once 3.6.4 is published. --- CHANGELOG.md | 2 +- pyproject.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index da621678..9cf59783 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ - `--strict-blocking` lists and counts every advisory on an unchanged package. Existing alerts are read through the SDK, which kept one alert per alert type and severity, so a package with six Critical CVEs showed one, and the - "EXISTING blocking issues" count was too low. Requires `socketdev` 3.6.3. + "EXISTING blocking issues" count was too low. Requires `socketdev` 3.6.4. - A Block-action CVE on an unchanged package now fails the run even when another CVE of the same severity on that package is triaged to monitor or ignore. Before, the triaged CVE could stand in for both and the run passed. diff --git a/pyproject.toml b/pyproject.toml index c21b4ecb..e8d335b1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -16,7 +16,7 @@ dependencies = [ "gitpython==3.2.1", "packaging==26.3", "python-dotenv==1.2.4", - "socketdev==3.6.3", + "socketdev==3.6.4", "beautifulsoup4==4.15.0", "markdown==3.11.3", "brotli==1.2.1; platform_python_implementation == 'CPython'", From 79177a5bfa3eac2b810da42d1f3cb29574f797ed Mon Sep 17 00:00:00 2001 From: David Larsen Date: Fri, 20 Nov 2026 18:08:17 -0500 Subject: [PATCH 4/7] Bump version to 2.13.3 2.13.2 was released from main, so this change needs the next patch version. --- pyproject.toml | 2 +- socketsecurity/__init__.py | 2 +- uv.lock | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 4846aca9..b7578c83 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ build-backend = "hatchling.build" [project] name = "socketsecurity" -version = "2.13.2" +version = "2.13.3" requires-python = ">= 3.11" license = {"file" = "LICENSE"} dependencies = [ diff --git a/socketsecurity/__init__.py b/socketsecurity/__init__.py index 7ba49e1b..0871adeb 100644 --- a/socketsecurity/__init__.py +++ b/socketsecurity/__init__.py @@ -1,4 +1,4 @@ __author__ = 'socket.dev' -__version__ = '2.13.2' +__version__ = '2.13.3' USER_AGENT_NAME = 'socket-python-cli' USER_AGENT = f'{USER_AGENT_NAME}/{__version__}' diff --git a/uv.lock b/uv.lock index 196ae3c8..b3681e40 100644 --- a/uv.lock +++ b/uv.lock @@ -1334,7 +1334,7 @@ wheels = [ [[package]] name = "socketsecurity" -version = "2.13.2" +version = "2.13.3" source = { editable = "." } dependencies = [ { name = "beautifulsoup4" }, From 12b3b45cc95e2626c1b7e819e8ba094737724cd4 Mon Sep 17 00:00:00 2001 From: lelia <2418071+lelia@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:06:49 -0500 Subject: [PATCH 5/7] Keep persistent alerts across dependency version changes Load current alerts for added and updated packages in strict diff mode. Report findings omitted by the comparison as existing so a Block advisory that survives a version change still fails the run. --- CHANGELOG.md | 2 + docs/cli-reference.md | 2 +- docs/troubleshooting.md | 2 +- socketsecurity/core/__init__.py | 85 +++++++++--- socketsecurity/core/messages.py | 6 +- tests/core/test_existing_alerts.py | 125 +++++++++++++++--- tests/core/test_strict_blocking_duplicates.py | 10 +- 7 files changed, 184 insertions(+), 48 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fdf09f55..0438ee7b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,8 @@ - A Block-action CVE on an unchanged package now fails the run even when another CVE of the same severity on that package is triaged to monitor or ignore. Before, the triaged CVE could stand in for both and the run passed. +- `--strict-blocking` fails on Block alerts that persist across a dependency + version change and lists them in the Existing alerts table. - In full-scan mode, the `--enable-json`, `--enable-sarif` and `--enable-gitlab-security` reports now list every advisory on a package. Before, they listed one per alert type and severity, so expect more alerts, diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 3a9ebab6..6a887245 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -669,7 +669,7 @@ Security issues detected by Socket Security: - **Diff Mode Only**: The flag applies when a scan comparison runs, with or without SCM integration. A full scan logs a warning and does not evaluate existing violations; see [Scan type by pipeline](ci-cd.md#scan-type-by-pipeline). - **Error-Level Only**: Only fails on `error=True` alerts (blocking severity), not warnings. -- **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. +- **Existing alerts come from the full scan**. The CLI reads alerts on unchanged packages and findings that persist across dependency version changes from the new full scan. This takes up to one additional full-scan fetch. A failed fetch or a missing package in that response triggers the infrastructure-error exit code. - **PR/MR comments**: Existing alerts are listed in their own table after the new ones, blocking first, with license violations grouped per package. `@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. Ignoring every displayed alert preserves the warning about omitted findings; `ignore-all` also clears omitted findings. - **Priority**: `--disable-blocking` takes precedence - if both flags are set, the build will always pass. - **First Scan**: On the very first scan of a repository, there are no "existing" violations, so behavior is identical to standard mode. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index f26b1581..e9162364 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -123,7 +123,7 @@ Flags add: | `--reach` | `POST orgs/{org}/upload-manifest-files`, `POST tier1-reachability-scan/finalize` | `full-scans:create` | | `--generate-license` | `POST orgs/{org}/purl` | `packages:list` | | `--enable-json`, `--enable-sarif`, `--enable-gitlab-security` or `--generate-license` on a full scan | `GET orgs/{org}/full-scans/{id}` (scan contents) | `full-scans:list` | -| `--strict-blocking`, `--enable-gitlab-security` or `--legal-format fossa` on a run that compares scans | `GET orgs/{org}/full-scans/{id}` (alerts on unchanged packages) | `full-scans:list` | +| `--strict-blocking`, `--enable-gitlab-security` or `--legal-format fossa` on a run that compares scans | `GET orgs/{org}/full-scans/{id}` (existing alerts) | `full-scans:list` | `--reach` also runs the analysis engine with the same token. The engine reports to the `tier1-reachability-scan/*` endpoints, which check `full-scans:create`. diff --git a/socketsecurity/core/__init__.py b/socketsecurity/core/__init__.py index 92172084..44efdbb7 100644 --- a/socketsecurity/core/__init__.py +++ b/socketsecurity/core/__init__.py @@ -2400,6 +2400,7 @@ def create_new_diff( # Resolve the baseline scan: --base-scan-id / --base-commit-sha override # the repository's head scan (None only when the repo has no head scan yet). head_full_scan_id = self.resolve_base_full_scan_id(params) + has_baseline = head_full_scan_id is not None # If no head scan exists, create an empty baseline scan if head_full_scan_id is None: @@ -2499,10 +2500,25 @@ def create_new_diff( ) unchanged_packages = Core.get_unchanged_packages(packages, added_packages, removed_packages) - if unchanged_packages and self._requires_unchanged_alerts(): - self.add_existing_alerts_from_full_scan(unchanged_packages, new_full_scan.id) + existing_changed_packages = {} + if has_baseline and getattr(self.cli_config, "strict_blocking", False): + # Keep the comparison's alerts intact for new-finding classification. + existing_changed_packages = { + package_id: copy.copy(package) for package_id, package in added_packages.items() + } + if self._requires_unchanged_alerts(): + self.add_existing_alerts_from_full_scan( + unchanged_packages, + new_full_scan.id, + changed_packages=existing_changed_packages, + ) - diff = self.create_diff_report(added_packages, removed_packages, unchanged_packages) + diff = self.create_diff_report( + added_packages, + removed_packages, + unchanged_packages, + existing_changed_packages=existing_changed_packages, + ) diff.packages = packages base_socket = "https://socket.dev/dashboard/org" @@ -2542,25 +2558,32 @@ def _requires_unchanged_alerts(self) -> bool: ) def add_existing_alerts_from_full_scan( - self, unchanged_packages: Dict[str, Package], full_scan_id: str + self, + unchanged_packages: Dict[str, Package], + full_scan_id: str, + *, + changed_packages: Optional[Dict[str, Package]] = None, ) -> None: - """Fill in the alerts on unchanged packages from the new full scan. + """Load alerts for unchanged and optionally changed packages from the new full scan. - The cached diff-scans endpoint returns unchanged artifacts with an empty - ``alerts`` list, because it keeps only the alerts it counts as new. The full - scan of the same commit carries every package's alerts with their policy - actions, so they are read from there. Packages are matched by artifact ID, - then by ecosystem, namespace, name and version. + The cached comparison keeps only new alerts, so it omits alerts that + persist across a version change as well as alerts on unchanged packages. + The full scan carries current alerts with their policy actions. Match + packages by artifact ID, then by ecosystem, namespace, name and version. - Skipped when any unchanged package already has alerts: the comparison then - came from an endpoint that includes them, such as the streaming fallback. - A failed fetch or an unmatched package raises, because reporting existing - alerts as absent would let ``--strict-blocking`` pass a run it should fail. + The streaming fallback can supply unchanged alerts itself. Changed + packages, when requested, always need the full scan. A failed fetch or + unmatched package raises so strict blocking can evaluate all existing alerts. """ + packages_to_load = dict(changed_packages or {}) if any(package.alerts for package in unchanged_packages.values()): log.debug("The comparison already includes alerts on unchanged packages") + else: + packages_to_load.update(unchanged_packages) + if not packages_to_load: return + package_kind = "current" if changed_packages else "unchanged" start = time.time() by_id: Dict[str, List[dict]] = {} by_identity: Dict[Tuple[str, str, str, str], List[dict]] = {} @@ -2574,7 +2597,7 @@ def add_existing_alerts_from_full_scan( matched = 0 alert_count = 0 - for package in unchanged_packages.values(): + for package in packages_to_load.values(): alerts = by_id.get(package.id) if alerts is None: alerts = by_identity.get(Core._package_identity( @@ -2587,12 +2610,12 @@ def add_existing_alerts_from_full_scan( alert_count += len(alerts) log.info( - f"Loaded {alert_count} alerts for {matched} of {len(unchanged_packages)} " - f"unchanged packages from full scan {full_scan_id} in {time.time() - start:.2f}s" + f"Loaded {alert_count} alerts for {matched} of {len(packages_to_load)} " + f"{package_kind} packages from full scan {full_scan_id} in {time.time() - start:.2f}s" ) - if matched < len(unchanged_packages): + if matched < len(packages_to_load): raise InfrastructureError( - f"{len(unchanged_packages) - matched} of {len(unchanged_packages)} unchanged packages " + f"{len(packages_to_load) - matched} of {len(packages_to_load)} {package_kind} packages " f"were not found in full scan {full_scan_id}; unable to evaluate all existing alerts." ) @@ -2628,7 +2651,9 @@ def create_diff_report( added_packages: Dict[str, Package], removed_packages: Dict[str, Package], unchanged_packages: Optional[Dict[str, Package]] = None, - direct_only: bool = True + direct_only: bool = True, + *, + existing_changed_packages: Optional[Dict[str, Package]] = None, ) -> Diff: """ Creates a diff report comparing two sets of packages. @@ -2637,7 +2662,7 @@ def create_diff_report( 1. Records new/removed packages (direct only by default) 2. Collects alerts from both sets of packages 3. Determines new capabilities introduced - 4. Optionally collects alerts from unchanged packages for --strict-blocking + 4. Optionally collects existing alerts for --strict-blocking Args: added_packages: Dict of packages added in new scan @@ -2645,6 +2670,7 @@ def create_diff_report( unchanged_packages: Dict of packages that didn't change (for --strict-blocking) direct_only: If True, only direct dependencies are included in new/removed lists (but alerts are still processed for all packages) + existing_changed_packages: Added/updated packages with alerts from the new full scan Returns: Diff object containing the comparison results @@ -2712,10 +2738,25 @@ def create_diff_report( alerts_in_removed_packages ) - # Get unchanged alerts (for --strict-blocking mode) + # Existing findings can also persist on a changed version. diff.unchanged_alerts = Core.get_unchanged_alerts( alerts_in_unchanged_packages ) + if existing_changed_packages: + current_changed_alerts: Dict[str, List[Issue]] = {} + for package in existing_changed_packages.values(): + self.add_package_alerts_to_collection( + package=package, + alerts_collection=current_changed_alerts, + packages=added_packages, + ) + reported_findings = { + alert.consolidation_key() for alert in (*diff.new_alerts, *diff.unchanged_alerts) + } + diff.unchanged_alerts.extend( + alert for alert in Core.get_unchanged_alerts(current_changed_alerts) + if alert.consolidation_key() not in reported_findings + ) # Get removed alerts (for completeness) diff.removed_alerts = Core.get_removed_alerts( diff --git a/socketsecurity/core/messages.py b/socketsecurity/core/messages.py index 33dfa9bd..39807474 100644 --- a/socketsecurity/core/messages.py +++ b/socketsecurity/core/messages.py @@ -1183,7 +1183,7 @@ def security_comment_template(diff: Diff, config=None) -> str: @staticmethod def existing_comment_alerts(diff: Diff, config) -> list: - """Alerts on unchanged packages to show in the PR comment. + """Existing alerts to show in the PR comment. Only under --strict-blocking, where they fail the run: without it they don't affect the result, and listing them would bury the new ones. @@ -1200,7 +1200,7 @@ def existing_comment_alerts(diff: Diff, config) -> list: def existing_alerts_section( alerts: list, diff: Diff, config, show_ignore: bool, view_report_url: str, size_so_far: int ) -> str: - """Table of alerts on packages this change didn't touch, blocking ones first. + """Table of existing alerts, with blocking alerts first. License policy violations are grouped per package, as in the table of new alerts. @@ -1221,7 +1221,7 @@ def existing_alerts_section( blocking = sum(1 for alert in alerts if alert.error) section = f""" -**Existing alerts ({len(alerts)}).** These are on dependencies this change didn't add or update. `--strict-blocking` fails the run on the {blocking} with a **Block** action. +**Existing alerts ({len(alerts)}).** The baseline also contains these findings. `--strict-blocking` fails the run on the {blocking} with a **Block** action. diff --git a/tests/core/test_existing_alerts.py b/tests/core/test_existing_alerts.py index b404e148..b35026cf 100644 --- a/tests/core/test_existing_alerts.py +++ b/tests/core/test_existing_alerts.py @@ -1,11 +1,4 @@ -"""Alerts on unchanged packages come from the full scan when the comparison omits them. - -The cached diff-scans endpoint returns unchanged artifacts with an empty -``alerts`` list, so ``--strict-blocking`` had nothing to block on and passed. -The new full scan carries every package's alerts, so the CLI reads them from -there whenever an output needs them: ``--strict-blocking``, the GitLab security -report and FOSSA-format output. -""" +"""The full scan supplies current alerts omitted by the comparison.""" import json import re from pathlib import Path @@ -44,7 +37,7 @@ def _alert(key, action="error", alert_type="malware"): } -def _diff_artifact(diff_type, artifact_id, name, alerts=None): +def _diff_artifact(diff_type, artifact_id, name, alerts=None, *, version="1.0.0"): ref = { "direct": True, "manifestFiles": [{"file": "package.json", "start": 0, "end": 0}], @@ -54,10 +47,10 @@ def _diff_artifact(diff_type, artifact_id, name, alerts=None): "diffType": diff_type, "type": "npm", "name": name, - "version": "1.0.0", + "version": version, "id": artifact_id, - "head": [ref], - "base": [], + "head": [] if diff_type in ("removed", "replaced") else [ref], + "base": [ref] if diff_type in ("removed", "replaced") else [], "license": "MIT", "licenseDetails": [], "author": [], @@ -67,11 +60,11 @@ def _diff_artifact(diff_type, artifact_id, name, alerts=None): } -def _scan_artifact(artifact_id, name, alerts): +def _scan_artifact(artifact_id, name, alerts, *, version="1.0.0"): return { "type": "npm", "name": name, - "version": "1.0.0", + "version": version, "id": artifact_id, "direct": True, "manifestFiles": [{"file": "package.json", "start": 0, "end": 0}], @@ -114,11 +107,11 @@ def core(mock_sdk_with_responses): return core -def _run(core, *flags, unchanged_alerts=None, scan_alerts=None, scan_id="u1"): +def _run(core, *flags, scan_alerts=None, scan_id="u1"): core.cli_config = CliConfig.from_args(["--api-token", "test", *flags]) core.sdk.fullscans.stream_diff.return_value = _diff_response( added=[_diff_artifact("added", "a1", "alpha", [_alert("k1")])], - unchanged=[_diff_artifact("unchanged", "u1", "gamma", unchanged_alerts)], + unchanged=[_diff_artifact("unchanged", "u1", "gamma")], ) core.sdk.fullscans.stream.return_value = _scan_response( _scan_artifact("a1", "alpha", [_alert("k1")]), @@ -160,6 +153,95 @@ def test_strict_blocking_fails_on_an_existing_blocking_alert(core): assert not _handler(strict_blocking=True).report_pass(diff) +@pytest.mark.parametrize("change_type", ["added", "updated"]) +@pytest.mark.parametrize("strict", [True, False]) +def test_blocking_cve_persists_across_a_version_change(core, change_type, strict): + flags = ["--strict-blocking"] if strict else [] + core.cli_config = CliConfig.from_args(["--api-token", "test", *flags]) + 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])], + }, + }, + } + _stream_through_sdk( + core, + _scan_artifact("a2", "alpha", [alert], version="2.0.0"), + ) + params = FullScanParams(repo="repo", branch="feature") + params.include_license_details = True + + diff = core.create_new_diff(["/repo"], params, explicit_files=["/repo/package.json"]) + + assert diff.new_alerts == [] + assert _handler(strict_blocking=strict).report_pass(diff) is (not strict) + if strict: + assert [(a.purl, a.advisory_id()) for a in diff.unchanged_alerts] == [ + ("alpha@2.0.0", "CVE-2025-12345"), + ] + comment = Messages.security_comment_template(diff, _config()) + existing_table = comment.split("")[1] + assert "alpha@2.0.0" in existing_table + assert "CVE-2025-12345" in existing_table + core.sdk.fullscans.stream.assert_called_once_with(core.config.org_slug, "new", use_types=True) + else: + assert diff.unchanged_alerts == [] + core.sdk.fullscans.stream.assert_not_called() + + +def test_strict_blocking_loads_unchanged_and_updated_alerts_once(core): + core.cli_config = CliConfig.from_args(["--api-token", "test", "--strict-blocking"]) + new_alert = {**_alert("new", alert_type="criticalCVE"), "props": {"cveId": "CVE-2025-12345"}} + existing_alert = {**_alert("existing", alert_type="criticalCVE"), "props": {"cveId": "CVE-2025-54321"}} + updated = _diff_artifact("updated", "a2", "alpha", [new_alert], version="2.0.0") + replaced = _diff_artifact("replaced", "a1", "alpha", [ + {**existing_alert, "action": "warn"}, _alert("resolved"), + ]) + updated["namespace"] = replaced["namespace"] = "@team" + core.sdk.fullscans.stream_diff.return_value = _diff_response( + updated=[updated], + replaced=[replaced], + unchanged=[_diff_artifact("unchanged", "u1", "gamma")], + ) + scanned = _scan_artifact("head-a2", "alpha", [new_alert, existing_alert], version="2.0.0") + scanned["namespace"] = "@team" + core.sdk.fullscans.stream.return_value = _scan_response( + scanned, + _scan_artifact("u1", "gamma", [_alert("unchanged")]), + ) + params = FullScanParams(repo="repo", branch="feature") + params.include_license_details = True + + diff = core.create_new_diff(["/repo"], params, explicit_files=["/repo/package.json"]) + + assert [a.key for a in diff.new_alerts] == ["new"] + assert {(a.purl, a.key, a.error) for a in diff.unchanged_alerts} == { + ("@team/alpha@2.0.0", "existing", True), + ("gamma@1.0.0", "unchanged", True), + } + core.sdk.fullscans.stream.assert_called_once() + + +def test_strict_blocking_fails_if_changed_package_is_missing_from_full_scan(core): + core.cli_config = CliConfig.from_args(["--api-token", "test", "--strict-blocking"]) + core.sdk.fullscans.stream_diff.return_value = _diff_response( + updated=[_diff_artifact("updated", "a2", "alpha", version="2.0.0")], + ) + core.sdk.fullscans.stream.return_value = _scan_response( + _scan_artifact("a1", "alpha", []), + ) + params = FullScanParams(repo="repo", branch="feature") + params.include_license_details = True + + with pytest.raises(InfrastructureError, match="current packages.*full scan new"): + core.create_new_diff(["/repo"], params, explicit_files=["/repo/package.json"]) + + def test_existing_alerts_match_by_package_when_artifact_ids_differ(core): diff = _run(core, "--strict-blocking", scan_id="other-id") @@ -190,8 +272,15 @@ def test_no_extra_fetch_when_no_output_reads_existing_alerts(core): def test_no_extra_fetch_when_the_comparison_already_has_existing_alerts(core): - """The streaming comparison includes them, and so will diff-scans once the API does.""" - diff = _run(core, "--strict-blocking", unchanged_alerts=[_alert("k3")]) + """An unchanged-only comparison can already have all the alerts it needs.""" + core.cli_config = CliConfig.from_args(["--api-token", "test", "--strict-blocking"]) + core.sdk.fullscans.stream_diff.return_value = _diff_response( + unchanged=[_diff_artifact("unchanged", "u1", "gamma", [_alert("k3")])], + ) + params = FullScanParams(repo="repo", branch="feature") + params.include_license_details = True + + diff = core.create_new_diff(["/repo"], params, explicit_files=["/repo/package.json"]) core.sdk.fullscans.stream.assert_not_called() assert [a.pkg_name for a in diff.unchanged_alerts] == ["gamma"] diff --git a/tests/core/test_strict_blocking_duplicates.py b/tests/core/test_strict_blocking_duplicates.py index a37f67cc..da6a7a53 100644 --- a/tests/core/test_strict_blocking_duplicates.py +++ b/tests/core/test_strict_blocking_duplicates.py @@ -79,11 +79,13 @@ def _diff_response(**buckets): }) -def _build_diff(core, response): +def _build_diff(core, response, *, baseline="head"): """Run Core.create_new_diff with the upload mocked out and `response` as the diff.""" core.sdk.fullscans.stream_diff.return_value = response - core.resolve_base_full_scan_id = Mock(return_value="head") + core.resolve_base_full_scan_id = Mock(return_value=baseline) core.create_full_scan = Mock(return_value=SimpleNamespace(id="new")) + if baseline is None: + core.create_full_scan.side_effect = [SimpleNamespace(id="empty"), SimpleNamespace(id="new")] params = FullScanParams(repo="repo", branch="feature") params.include_license_details = True return core.create_new_diff( @@ -105,13 +107,15 @@ def _handler(strict_blocking=True): def test_empty_baseline_lists_added_alerts_once(core): """Against an empty baseline every package is added and none is unchanged.""" + core.cli_config = CliConfig.from_args(["--api-token", "test", "--strict-blocking"]) diff = _build_diff(core, _diff_response(added=[ _artifact("added", "a1", "alpha", [_blocking_alert("k1")]), _artifact("added", "a2", "beta", [_blocking_alert("k2")]), - ])) + ]), baseline=None) assert len(diff.new_alerts) == 2 assert diff.unchanged_alerts == [] + core.sdk.fullscans.stream.assert_not_called() handler = _handler() report = handler.build_json_report(diff) From 21fa6634a0242ed27e09094d855fab6c1cce7f7f Mon Sep 17 00:00:00 2001 From: lelia <2418071+lelia@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:08:39 -0500 Subject: [PATCH 6/7] Lock the published Socket Python SDK 3.6.4 --- uv.lock | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/uv.lock b/uv.lock index b3681e40..57c8b444 100644 --- a/uv.lock +++ b/uv.lock @@ -1320,16 +1320,16 @@ wheels = [ [[package]] name = "socketdev" -version = "3.6.3" +version = "3.6.4" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "certifi" }, { name = "requests" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/3b/94/1ac6e7da44a86571b2b91538e750a854d91f8f225da6bc324e433e9df222/socketdev-3.6.3.tar.gz", hash = "sha256:71a6dc6d1e0359f5f215e6da8c63bf479038ae07dd0ce29ec6c9fc8bf88054b0", size = 189957, upload-time = "2026-11-20T22:12:29.769Z" } +sdist = { url = "https://files.pythonhosted.org/packages/3b/7e/34312e7aa26c13debbff255005bfd26c86348e13aeee80c039d652859aee/socketdev-3.6.4.tar.gz", hash = "sha256:882c2e525158da361f9399b6958758b071bdea126c9a03bc2bc7413d3b7348da", size = 193162, upload-time = "2026-11-24T02:08:03.349Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/da/39/775de959c64847fde70599bc67c4dcf9057ad540657c46157971f564f69c/socketdev-3.6.3-py3-none-any.whl", hash = "sha256:ba5fb7bbce566ddd7c9ecdfbc37389708f5115f9edbb42eeff14ce7dc2278be8", size = 78954, upload-time = "2026-11-20T22:12:28.453Z" }, + { url = "https://files.pythonhosted.org/packages/88/43/8391d09646b50955c151137fa61b0ff85284d1098300c30ec23f580b609a/socketdev-3.6.4-py3-none-any.whl", hash = "sha256:01facf828a77916d31012e5a3a77c0fa8655036c61b009966073e42edda279eb", size = 79728, upload-time = "2026-11-24T02:08:01.842Z" }, ] [[package]] @@ -1393,7 +1393,7 @@ requires-dist = [ { name = "python-dotenv", specifier = "==1.2.4" }, { name = "requests", specifier = "==2.34.2" }, { name = "ruff", marker = "extra == 'dev'", specifier = "==0.17.5" }, - { name = "socketdev", specifier = "==3.6.3" }, + { name = "socketdev", specifier = "==3.6.4" }, { name = "twine", marker = "extra == 'dev'", specifier = "==7.0.0" }, { name = "uv", marker = "extra == 'dev'", specifier = "==0.13.8" }, ] From 0bf1e330550ae8fb1579a8af781531a4167dd298 Mon Sep 17 00:00:00 2001 From: lelia <2418071+lelia@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:20:18 -0500 Subject: [PATCH 7/7] Preserve blocking actions and advisory details in scan reports --- CHANGELOG.md | 26 +++---- docs/cli-reference.md | 23 ++---- socketsecurity/core/__init__.py | 112 ++++++++++++++--------------- socketsecurity/core/messages.py | 21 +++--- tests/core/test_existing_alerts.py | 103 ++++++++++++++++++++++++-- 5 files changed, 175 insertions(+), 110 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0438ee7b..a680fd59 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,27 +4,17 @@ ### Changed -- Bumped the pinned Socket Python SDK (`socketdev`) from `3.6.3` to `3.6.4`. - The release keeps each advisory as its own alert instead of one per alert - type and severity, which changes what the CLI reports; see Fixed below. +- Updated the Socket Python SDK (`socketdev`) to 3.6.4. This can increase + advisory counts in full-scan JSON, SARIF, and GitLab security reports, and + in the existing findings shown in GitLab security and FOSSA diff reports. ### Fixed -- `--strict-blocking` lists and counts every advisory on an unchanged package. - Existing alerts are read through the SDK, which kept one alert per alert type - and severity, so a package with six Critical CVEs showed one, and the - "EXISTING blocking issues" count was too low. Requires `socketdev` 3.6.4. -- A Block-action CVE on an unchanged package now fails the run even when - another CVE of the same severity on that package is triaged to monitor or - ignore. Before, the triaged CVE could stand in for both and the run passed. -- `--strict-blocking` fails on Block alerts that persist across a dependency - version change and lists them in the Existing alerts table. -- In full-scan mode, the `--enable-json`, `--enable-sarif` and - `--enable-gitlab-security` reports now list every advisory on a package. - Before, they listed one per alert type and severity, so expect more alerts, - and more with a Block action, in these reports. In diff mode the same - applies to existing alerts in the `--enable-gitlab-security` and - `--legal-format fossa` output. +- `--strict-blocking` counts distinct advisories on unchanged dependencies and + lists findings that persist after a version change in the Existing alerts + 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. ## 2.13.2 diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 6a887245..cd16ac4a 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -604,19 +604,12 @@ Bot mode (`bot_configs` array items): ## Strict Blocking Mode -The `--strict-blocking` flag enforces a zero-tolerance security policy by failing builds when **ANY** security violations with blocking severity exist, not just new ones introduced in the current changes. +In a scan comparison, `--strict-blocking` fails the build on new and existing findings with a **Block** action. ### Standard vs Strict Blocking Behavior -**Standard Behavior (Default)**: -- ✅ Passes if no NEW violations are introduced -- ❌ Fails only on NEW violations from your changes -- 🟡 Existing violations are ignored - -**Strict Blocking Behavior (`--strict-blocking`)**: -- ✅ Passes only if NO violations exist (new or existing) -- ❌ Fails on ANY violation (new OR existing) -- 🔴 Enforces zero-tolerance policy +- **Default** fails on findings introduced by the change that have a **Block** action. +- **Strict blocking** also checks unchanged dependencies and findings that persist after a version change. For example, if an upgrade leaves a blocking advisory unresolved, the run still fails and the advisory appears under **Existing alerts** at the new version. ### Usage Examples @@ -668,8 +661,8 @@ Security issues detected by Socket Security: ### Important Notes - **Diff Mode Only**: The flag applies when a scan comparison runs, with or without SCM integration. A full scan logs a warning and does not evaluate existing violations; see [Scan type by pipeline](ci-cd.md#scan-type-by-pipeline). -- **Error-Level Only**: Only fails on `error=True` alerts (blocking severity), not warnings. -- **Existing alerts come from the full scan**. The CLI reads alerts on unchanged packages and findings that persist across dependency version changes from the new full scan. This takes up to one additional full-scan fetch. A failed fetch or a missing package in that response triggers the infrastructure-error exit code. +- **Policy actions**. Warn findings are reported. If the same finding has both Warn and Block actions, Block takes precedence. +- **Existing alerts come from the full scan**. The CLI fetches the current full scan when the comparison leaves out alerts on unchanged packages or when a dependency version changes. A failed fetch or a missing package in that response triggers the infrastructure-error exit code. - **PR/MR comments**: Existing alerts are listed in their own table after the new ones, blocking first, with license violations grouped per package. `@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. Ignoring every displayed alert preserves the warning about omitted findings; `ignore-all` also clears omitted findings. - **Priority**: `--disable-blocking` takes precedence - if both flags are set, the build will always pass. - **First Scan**: On the very first scan of a repository, there are no "existing" violations, so behavior is identical to standard mode. @@ -899,13 +892,11 @@ The GitLab Security Dashboard report and the JSON/SARIF diff outputs use differe | Output Format | Default Alerts | With `--strict-blocking` | |:---|:---|:---| -| `--enable-gitlab-security` | **All** alerts (new + existing) | All alerts (same) | +| `--enable-gitlab-security` | New alerts and existing alerts on unchanged dependencies | Also includes findings that persist after a version change | | `--enable-json` | New alerts only | New + existing alerts | | `--enable-sarif` (diff scope) | New alerts only | New + existing alerts | -**Why the difference?** GitLab's Security Dashboard is designed to present the full security posture of a project. An empty dashboard on a scan with no dependency changes would be misleading -- the vulnerabilities still exist, they just didn't change. By contrast, JSON and SARIF in diff scope are designed to answer "what changed?" and only include existing alerts when `--strict-blocking` explicitly requests it. - -> **Tip:** If you use `--enable-json` alongside `--enable-gitlab-security`, the GitLab report may contain more vulnerabilities than the JSON output. This is expected. To make JSON output match, add `--strict-blocking`. +Enable `--strict-blocking` to include existing findings in JSON and diff-scope SARIF. Scan-based SARIF includes the advisory ID in the rule ID when available, so separate advisories on the same package and manifest remain distinguishable. ### Alert Ignoring via PR/MR Comments diff --git a/socketsecurity/core/__init__.py b/socketsecurity/core/__init__.py index 44efdbb7..e3f27835 100644 --- a/socketsecurity/core/__init__.py +++ b/socketsecurity/core/__init__.py @@ -13,7 +13,17 @@ import time from dataclasses import asdict from pathlib import PurePath -from typing import TYPE_CHECKING, Dict, Iterator, List, NamedTuple, Optional, Set, Tuple +from typing import ( + TYPE_CHECKING, + Dict, + Iterable, + Iterator, + List, + NamedTuple, + Optional, + Set, + Tuple, +) if TYPE_CHECKING: from socketsecurity.config import CliConfig @@ -1357,13 +1367,10 @@ def create_full_scan_with_report_url( packages=packages ) - consolidated: Set[Tuple[str, str, str, str]] = set() - for alert_key, alerts in all_alerts_collection.items(): - for alert in alerts: - finding_key = alert.consolidation_key() - if (alert.error or alert.warn) and finding_key not in consolidated: - diff.new_alerts.append(alert) - consolidated.add(finding_key) + findings = Core._consolidate_reportable_alerts( + alert for alerts in all_alerts_collection.values() for alert in alerts + ) + diff.new_alerts = list(findings.values()) diff.alerts_fetched = True sbom_end = time.time() @@ -2502,9 +2509,15 @@ def create_new_diff( unchanged_packages = Core.get_unchanged_packages(packages, added_packages, removed_packages) existing_changed_packages = {} if has_baseline and getattr(self.cli_config, "strict_blocking", False): - # Keep the comparison's alerts intact for new-finding classification. + baseline_names = { + Core._package_identity(package.type, package.namespace, package.name, "")[:3] + for bucket in (removed_packages, unchanged_packages) + for package in bucket.values() + } existing_changed_packages = { package_id: copy.copy(package) for package_id, package in added_packages.items() + if package.diffType == "updated" + or Core._package_identity(package.type, package.namespace, package.name, "")[:3] in baseline_names } if self._requires_unchanged_alerts(): self.add_existing_alerts_from_full_scan( @@ -2680,6 +2693,7 @@ def create_diff_report( alerts_in_added_packages: Dict[str, List[Issue]] = {} alerts_in_removed_packages: Dict[str, List[Issue]] = {} alerts_in_unchanged_packages: Dict[str, List[Issue]] = {} + current_packages = {**(unchanged_packages or {}), **added_packages} seen_packages = { "added": set(), @@ -2738,7 +2752,6 @@ def create_diff_report( alerts_in_removed_packages ) - # Existing findings can also persist on a changed version. diff.unchanged_alerts = Core.get_unchanged_alerts( alerts_in_unchanged_packages ) @@ -2748,15 +2761,16 @@ def create_diff_report( self.add_package_alerts_to_collection( package=package, alerts_collection=current_changed_alerts, - packages=added_packages, + packages=current_packages, ) - reported_findings = { - alert.consolidation_key() for alert in (*diff.new_alerts, *diff.unchanged_alerts) - } - diff.unchanged_alerts.extend( - alert for alert in Core.get_unchanged_alerts(current_changed_alerts) - if alert.consolidation_key() not in reported_findings + current_findings = Core._consolidate_reportable_alerts( + alert + for group in (diff.new_alerts, diff.unchanged_alerts, *current_changed_alerts.values()) + for alert in group ) + # Keep the comparison's classification when a finding also appears in the full scan. + diff.new_alerts = [current_findings.pop(alert.consolidation_key()) for alert in diff.new_alerts] + diff.unchanged_alerts = list(current_findings.values()) # Get removed alerts (for completeness) diff.removed_alerts = Core.get_removed_alerts( @@ -3006,36 +3020,13 @@ def get_new_alerts( Returns: List of newly found alerts """ - alerts: List[Issue] = [] - consolidated_alerts = set() - - for alert_key in added_package_alerts: - if alert_key not in removed_package_alerts: - new_alerts = added_package_alerts[alert_key] - for alert in new_alerts: - finding_key = alert.consolidation_key() - - if alert.error or alert.warn: - if finding_key not in consolidated_alerts: - alerts.append(alert) - consolidated_alerts.add(finding_key) - else: - new_alerts = added_package_alerts[alert_key] - removed_alerts = removed_package_alerts[alert_key] - - for alert in new_alerts: - finding_key = alert.consolidation_key() - - # Only add if: - # 1. Alert isn't in removed packages (or we're not ignoring readded alerts) - # 2. We haven't already recorded this alert - # 3. It's an error or warning - if (not ignore_readded or alert not in removed_alerts) and finding_key not in consolidated_alerts: - if alert.error or alert.warn: - alerts.append(alert) - consolidated_alerts.add(finding_key) - - return alerts + findings = Core._consolidate_reportable_alerts( + alert + for key, alerts in added_package_alerts.items() + for alert in alerts + if not ignore_readded or alert not in removed_package_alerts.get(key, ()) + ) + return list(findings.values()) @staticmethod def get_unchanged_alerts( @@ -3053,19 +3044,22 @@ def get_unchanged_alerts( Returns: List of all error/warning alerts from unchanged packages """ - alerts: List[Issue] = [] - consolidated_alerts = set() - - for alert_key in unchanged_package_alerts: - for alert in unchanged_package_alerts[alert_key]: - finding_key = alert.consolidation_key() - - # Only include error or warning alerts - if (alert.error or alert.warn) and finding_key not in consolidated_alerts: - alerts.append(alert) - consolidated_alerts.add(finding_key) + findings = Core._consolidate_reportable_alerts( + alert for alerts in unchanged_package_alerts.values() for alert in alerts + ) + return list(findings.values()) - return alerts + @staticmethod + def _consolidate_reportable_alerts(alerts: Iterable[Issue]) -> Dict[Tuple[str, str, str, str], Issue]: + """Keep the strongest reportable action for each finding across manifests and scan results.""" + findings: Dict[Tuple[str, str, str, str], Issue] = {} + for alert in alerts: + if alert.error or alert.warn: + key = alert.consolidation_key() + previous = findings.get(key) + if previous is None or (alert.error and not previous.error): + findings[key] = alert + return findings @staticmethod def get_removed_alerts( diff --git a/socketsecurity/core/messages.py b/socketsecurity/core/messages.py index 39807474..ee0e3824 100644 --- a/socketsecurity/core/messages.py +++ b/socketsecurity/core/messages.py @@ -232,16 +232,7 @@ def get_manifest_type_url(manifest_file: str, pkg_name: str, pkg_version: str) - @staticmethod def create_security_comment_sarif(diff) -> dict: """ - Create SARIF-compliant output from the diff report, including dynamic URL generation - based on manifest type and improved
formatting for GitHub SARIF display. - - This function now: - - Processes every alert in diff.new_alerts. - - For alerts with multiple manifest files, generates an individual SARIF result for each file. - - Appends the manifest file name to the rule ID and name to make each result unique. - - Does NOT fall back to 'requirements.txt' if no manifest file is provided. - - Adds detailed log to validate our assumptions. - + Render each alert at its known manifest locations and identify advisory rules by advisory ID. """ if len(diff.new_alerts) == 0: for alert in diff.new_alerts: @@ -270,6 +261,9 @@ def create_security_comment_sarif(diff) -> dict: pkg_name = alert.pkg_name pkg_version = alert.pkg_version base_rule_id = f"{pkg_name}=={pkg_version}" + advisory_id = alert.advisory_id() + if advisory_id: + base_rule_id = f"{base_rule_id} {advisory_id}" severity = alert.severity log.debug("Alert %s - introduced_by: %s, manifests: %s", base_rule_id, alert.introduced_by, getattr(alert, 'manifests', None)) @@ -283,6 +277,11 @@ def create_security_comment_sarif(diff) -> dict: manifest_files.extend([m.strip() for m in entry.split(";") if m.strip()]) elif hasattr(alert, 'manifests') and alert.manifests: manifest_files = [mf.strip() for mf in alert.manifests.split(";") if mf.strip()] + if not manifest_files: + manifest_files = [ + entry["file"] for entry in getattr(alert, "manifest_files", []) + if isinstance(entry, dict) and entry.get("file") + ] log.debug("Alert %s - extracted manifest_files: %s", base_rule_id, manifest_files) if not manifest_files: @@ -317,6 +316,8 @@ def create_security_comment_sarif(diff) -> dict: description = alert.description short_desc = (f"{props.get('note', '')}

Suggested Action:
{suggestion}" f"
{socket_url}") + if advisory_id: + short_desc = f"{advisory_id}
{short_desc}" full_desc = "{} - {}".format(alert_title, description.replace('\r\n', '
')) if unique_rule_id not in rules_map: diff --git a/tests/core/test_existing_alerts.py b/tests/core/test_existing_alerts.py index b35026cf..c11255e8 100644 --- a/tests/core/test_existing_alerts.py +++ b/tests/core/test_existing_alerts.py @@ -227,6 +227,73 @@ def test_strict_blocking_loads_unchanged_and_updated_alerts_once(core): core.sdk.fullscans.stream.assert_called_once() +@pytest.mark.parametrize("reported_as_new", [True, False]) +def test_block_action_takes_precedence_over_warning_for_the_same_advisory(core, reported_as_new): + core.cli_config = CliConfig.from_args(["--api-token", "test", "--strict-blocking"]) + warning = _cve_alert("GHSA-w457-6q6x-cgp9", "CVE-2019-19919", action="warn") + blocking = {**warning, "action": "error", "key": "block", "file": "repo/second/package.json"} + core.sdk.fullscans.stream_diff.return_value = _diff_response( + updated=[_diff_artifact("updated", "a2", "alpha", [warning] if reported_as_new else [], version="2.0.0")], + replaced=[_diff_artifact("replaced", "a1", "alpha", [] if reported_as_new else [blocking])], + ) + scan_alerts = [blocking] if reported_as_new else [{**warning, "file": "repo/first/package.json"}, blocking] + _stream_through_sdk(core, _scan_artifact("a2", "alpha", scan_alerts, version="2.0.0")) + params = FullScanParams(repo="repo", branch="feature") + params.include_license_details = True + + diff = core.create_new_diff(["/repo"], params, explicit_files=["/repo/package.json"]) + + assert len(diff.new_alerts) == int(reported_as_new) + assert len(diff.unchanged_alerts) == int(not reported_as_new) + assert (diff.new_alerts or diff.unchanged_alerts)[0].error + assert not _handler().report_pass(diff) + + +def test_existing_transitive_alert_includes_its_unchanged_ancestor_in_the_pr_comment(core): + core.cli_config = CliConfig.from_args(["--api-token", "test", "--strict-blocking"]) + updated = _diff_artifact("updated", "child2", "child", version="2.0.0") + updated["head"] = [{"direct": False, "manifestFiles": [], "topLevelAncestors": ["parent"]}] + parent = _diff_artifact("unchanged", "parent", "parent") + parent["namespace"] = "@team" + alert = _alert("persistent") + core.sdk.fullscans.stream_diff.return_value = _diff_response( + updated=[updated], + replaced=[_diff_artifact("replaced", "child1", "child", [alert])], + unchanged=[parent], + ) + _stream_through_sdk( + core, + _scan_artifact("child2", "child", [alert], version="2.0.0"), + {**_scan_artifact("parent", "parent", []), "namespace": "@team"}, + ) + params = FullScanParams(repo="repo", branch="feature") + params.include_license_details = True + + diff = core.create_new_diff(["/repo"], params, explicit_files=["/repo/package.json"]) + + ancestor = "npm/@team/parent@1.0.0" + assert diff.unchanged_alerts[0].introduced_by == [(ancestor, "package.json")] + comment = Messages.security_comment_template(diff, _config()) + existing_table = comment.split("")[1] + assert f"Introduced by:{ancestor}" in existing_table + + +def test_strict_blocking_skips_full_scan_fetch_for_a_new_dependency(core): + core.cli_config = CliConfig.from_args(["--api-token", "test", "--strict-blocking"]) + core.sdk.fullscans.stream_diff.return_value = _diff_response( + added=[_diff_artifact("added", "a1", "alpha", [_alert("introduced")])], + removed=[_diff_artifact("removed", "b1", "beta")], + ) + params = FullScanParams(repo="repo", branch="feature") + params.include_license_details = True + + diff = core.create_new_diff(["/repo"], params, explicit_files=["/repo/package.json"]) + + core.sdk.fullscans.stream.assert_not_called() + assert [alert.key for alert in diff.new_alerts] == ["introduced"] + assert diff.unchanged_alerts == [] + + def test_strict_blocking_fails_if_changed_package_is_missing_from_full_scan(core): core.cli_config = CliConfig.from_args(["--api-token", "test", "--strict-blocking"]) core.sdk.fullscans.stream_diff.return_value = _diff_response( @@ -335,13 +402,6 @@ def test_matched_package_without_alerts_is_a_clean_result(core): core.sdk.fullscans.stream.assert_called_once() -# --- Existing advisories read through the SDK's full-scan stream ------------------------ -# -# The tests above stub ``fullscans.stream``. These run the real SDK method over a canned -# HTTP response, so they also cover the SDK's merging of duplicate alerts: socketdev -# 3.6.2 kept one alert per type and severity, which dropped every other CVE of that -# severity on a package, along with any Block action it carried. - HANDLEBARS_CRITICAL_ADVISORIES = [ ("GHSA-8r5x-fm3f-whwj", ""), ("GHSA-p8wg-vrv2-v86f", ""), @@ -415,6 +475,35 @@ def test_a_triaged_advisory_does_not_hide_a_blocking_one_on_the_same_package(cor assert not _handler(strict_blocking=True).report_pass(diff) +@pytest.mark.parametrize("direct", [True, False]) +def test_full_scan_reports_distinguish_advisories_on_the_same_manifest(core, direct): + core.cli_config = CliConfig.from_args([ + "--api-token", "test", "--enable-json", "--enable-sarif", "--enable-gitlab-security", + ]) + advisories = HANDLEBARS_CRITICAL_ADVISORIES[:2] + alerts = [_cve_alert(ghsa, cve) for ghsa, cve in advisories] + artifact = _scan_artifact("u1", "handlebars", alerts) + artifact["direct"] = direct + _stream_through_sdk(core, artifact) + params = FullScanParams(repo="repo", branch="feature") + + diff = core.create_full_scan_with_report_url(["/repo"], params, explicit_files=["/repo/package.json"]) + + expected_ids = {ghsa.upper() for ghsa, _ in advisories} + report = OutputHandler(core.cli_config, core.sdk).build_json_report(diff) + assert {alert["props"]["ghsaId"].upper() for alert in report["new_alerts"]} == expected_ids + sarif = Messages.create_security_comment_sarif(diff)["runs"][0] + assert len(sarif["tool"]["driver"]["rules"]) == 2 + assert len(sarif["results"]) == 2 + assert {result["ruleId"].split()[1] for result in sarif["results"]} == expected_ids + assert {result["message"]["text"].split("
")[0] for result in sarif["results"]} == expected_ids + assert { + result["locations"][0]["physicalLocation"]["artifactLocation"]["uri"] for result in sarif["results"] + } == {"package.json"} + gitlab = Messages.create_security_comment_gitlab(diff) + assert len({finding["id"] for finding in gitlab["vulnerabilities"]}) == 2 + + # --- PR comment ------------------------------------------------------------------------