diff --git a/CHANGELOG.md b/CHANGELOG.md index 165e42c5..a680fd59 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,21 @@ # Changelog +## 2.13.3 + +### Changed + +- 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` 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 ### Added diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 3a9ebab6..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 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. +- **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/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/pyproject.toml b/pyproject.toml index 5c88c152..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 = [ @@ -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'", 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/socketsecurity/core/__init__.py b/socketsecurity/core/__init__.py index 92172084..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() @@ -2400,6 +2407,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 +2507,31 @@ 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): + 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( + 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 +2571,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 +2610,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 +2623,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 +2664,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 +2675,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 +2683,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 @@ -2654,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(), @@ -2712,10 +2752,25 @@ def create_diff_report( alerts_in_removed_packages ) - # Get unchanged alerts (for --strict-blocking mode) 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=current_packages, + ) + 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( @@ -2965,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( @@ -3012,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 33dfa9bd..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: @@ -1183,7 +1184,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 +1201,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 +1222,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 139577dd..c11255e8 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 @@ -16,6 +9,7 @@ from socketdev.exceptions import APIFailure from socketdev.fullscans import ( FullScanParams, + FullScans, FullScanStreamResponse, StreamDiffResponse, ) @@ -43,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}], @@ -53,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": [], @@ -66,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}], @@ -113,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")]), @@ -159,6 +153,162 @@ 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() + + +@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( + 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") @@ -189,8 +339,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"] @@ -245,6 +402,108 @@ def test_matched_package_without_alerts_is_a_clean_result(core): core.sdk.fullscans.stream.assert_called_once() +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) + + +@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 ------------------------------------------------------------------------ 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) diff --git a/uv.lock b/uv.lock index 196ae3c8..57c8b444 100644 --- a/uv.lock +++ b/uv.lock @@ -1320,21 +1320,21 @@ 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]] name = "socketsecurity" -version = "2.13.2" +version = "2.13.3" source = { editable = "." } dependencies = [ { name = "beautifulsoup4" }, @@ -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" }, ]