Skip to content

Commit 4e28391

Browse files
dc-larsenlelia
andauthored
Report and enforce existing alerts under --strict-blocking (#459)
* 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. * 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. * 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. * Bump version to 2.13.3 2.13.2 was released from main, so this change needs the next patch version. * 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. * Lock the published Socket Python SDK 3.6.4 * Preserve blocking actions and advisory details in scan reports --------- Co-authored-by: lelia <2418071+lelia@users.noreply.github.com>
1 parent 9d976e7 commit 4e28391

10 files changed

Lines changed: 437 additions & 131 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,21 @@
11
# Changelog
22

3+
## 2.13.3
4+
5+
### Changed
6+
7+
- Updated the Socket Python SDK (`socketdev`) to 3.6.4. This can increase
8+
advisory counts in full-scan JSON, SARIF, and GitLab security reports, and
9+
in the existing findings shown in GitLab security and FOSSA diff reports.
10+
11+
### Fixed
12+
13+
- `--strict-blocking` counts distinct advisories on unchanged dependencies and
14+
lists findings that persist after a version change in the Existing alerts
15+
table. When a finding has both Warn and Block actions, Block takes precedence.
16+
- SARIF reports use advisory IDs to distinguish findings on the same package
17+
and manifest.
18+
319
## 2.13.2
420

521
### Added

‎docs/cli-reference.md‎

Lines changed: 7 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -604,19 +604,12 @@ Bot mode (`bot_configs` array items):
604604
605605
## Strict Blocking Mode
606606
607-
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.
607+
In a scan comparison, `--strict-blocking` fails the build on new and existing findings with a **Block** action.
608608
609609
### Standard vs Strict Blocking Behavior
610610
611-
**Standard Behavior (Default)**:
612-
- ✅ Passes if no NEW violations are introduced
613-
- ❌ Fails only on NEW violations from your changes
614-
- 🟡 Existing violations are ignored
615-
616-
**Strict Blocking Behavior (`--strict-blocking`)**:
617-
- ✅ Passes only if NO violations exist (new or existing)
618-
- ❌ Fails on ANY violation (new OR existing)
619-
- 🔴 Enforces zero-tolerance policy
611+
- **Default** fails on findings introduced by the change that have a **Block** action.
612+
- **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.
620613
621614
### Usage Examples
622615
@@ -668,8 +661,8 @@ Security issues detected by Socket Security:
668661
### Important Notes
669662
670663
- **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).
671-
- **Error-Level Only**: Only fails on `error=True` alerts (blocking severity), not warnings.
672-
- **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.
664+
- **Policy actions**. Warn findings are reported. If the same finding has both Warn and Block actions, Block takes precedence.
665+
- **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.
673666
- **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.
674667
- **Priority**: `--disable-blocking` takes precedence - if both flags are set, the build will always pass.
675668
- **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
899892
900893
| Output Format | Default Alerts | With `--strict-blocking` |
901894
|:---|:---|:---|
902-
| `--enable-gitlab-security` | **All** alerts (new + existing) | All alerts (same) |
895+
| `--enable-gitlab-security` | New alerts and existing alerts on unchanged dependencies | Also includes findings that persist after a version change |
903896
| `--enable-json` | New alerts only | New + existing alerts |
904897
| `--enable-sarif` (diff scope) | New alerts only | New + existing alerts |
905898
906-
**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.
907-
908-
> **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`.
899+
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.
909900
910901
### Alert Ignoring via PR/MR Comments
911902

‎docs/troubleshooting.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ Flags add:
123123
| `--reach` | `POST orgs/{org}/upload-manifest-files`, `POST tier1-reachability-scan/finalize` | `full-scans:create` |
124124
| `--generate-license` | `POST orgs/{org}/purl` | `packages:list` |
125125
| `--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` |
126-
| `--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` |
126+
| `--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` |
127127

128128
`--reach` also runs the analysis engine with the same token. The engine reports to the
129129
`tier1-reachability-scan/*` endpoints, which check `full-scans:create`.

‎pyproject.toml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ build-backend = "hatchling.build"
66

77
[project]
88
name = "socketsecurity"
9-
version = "2.13.2"
9+
version = "2.13.3"
1010
requires-python = ">= 3.11"
1111
license = {"file" = "LICENSE"}
1212
dependencies = [
@@ -16,7 +16,7 @@ dependencies = [
1616
"gitpython==3.2.1",
1717
"packaging==26.3",
1818
"python-dotenv==1.2.4",
19-
"socketdev==3.6.3",
19+
"socketdev==3.6.4",
2020
"beautifulsoup4==4.15.0",
2121
"markdown==3.11.3",
2222
"brotli==1.2.1; platform_python_implementation == 'CPython'",

‎socketsecurity/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
__author__ = 'socket.dev'
2-
__version__ = '2.13.2'
2+
__version__ = '2.13.3'
33
USER_AGENT_NAME = 'socket-python-cli'
44
USER_AGENT = f'{USER_AGENT_NAME}/{__version__}'

‎socketsecurity/core/__init__.py‎

Lines changed: 107 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,17 @@
1313
import time
1414
from dataclasses import asdict
1515
from pathlib import PurePath
16-
from typing import TYPE_CHECKING, Dict, Iterator, List, NamedTuple, Optional, Set, Tuple
16+
from typing import (
17+
TYPE_CHECKING,
18+
Dict,
19+
Iterable,
20+
Iterator,
21+
List,
22+
NamedTuple,
23+
Optional,
24+
Set,
25+
Tuple,
26+
)
1727

1828
if TYPE_CHECKING:
1929
from socketsecurity.config import CliConfig
@@ -1357,13 +1367,10 @@ def create_full_scan_with_report_url(
13571367
packages=packages
13581368
)
13591369

1360-
consolidated: Set[Tuple[str, str, str, str]] = set()
1361-
for alert_key, alerts in all_alerts_collection.items():
1362-
for alert in alerts:
1363-
finding_key = alert.consolidation_key()
1364-
if (alert.error or alert.warn) and finding_key not in consolidated:
1365-
diff.new_alerts.append(alert)
1366-
consolidated.add(finding_key)
1370+
findings = Core._consolidate_reportable_alerts(
1371+
alert for alerts in all_alerts_collection.values() for alert in alerts
1372+
)
1373+
diff.new_alerts = list(findings.values())
13671374
diff.alerts_fetched = True
13681375

13691376
sbom_end = time.time()
@@ -2400,6 +2407,7 @@ def create_new_diff(
24002407
# Resolve the baseline scan: --base-scan-id / --base-commit-sha override
24012408
# the repository's head scan (None only when the repo has no head scan yet).
24022409
head_full_scan_id = self.resolve_base_full_scan_id(params)
2410+
has_baseline = head_full_scan_id is not None
24032411

24042412
# If no head scan exists, create an empty baseline scan
24052413
if head_full_scan_id is None:
@@ -2499,10 +2507,31 @@ def create_new_diff(
24992507
)
25002508

25012509
unchanged_packages = Core.get_unchanged_packages(packages, added_packages, removed_packages)
2502-
if unchanged_packages and self._requires_unchanged_alerts():
2503-
self.add_existing_alerts_from_full_scan(unchanged_packages, new_full_scan.id)
2510+
existing_changed_packages = {}
2511+
if has_baseline and getattr(self.cli_config, "strict_blocking", False):
2512+
baseline_names = {
2513+
Core._package_identity(package.type, package.namespace, package.name, "")[:3]
2514+
for bucket in (removed_packages, unchanged_packages)
2515+
for package in bucket.values()
2516+
}
2517+
existing_changed_packages = {
2518+
package_id: copy.copy(package) for package_id, package in added_packages.items()
2519+
if package.diffType == "updated"
2520+
or Core._package_identity(package.type, package.namespace, package.name, "")[:3] in baseline_names
2521+
}
2522+
if self._requires_unchanged_alerts():
2523+
self.add_existing_alerts_from_full_scan(
2524+
unchanged_packages,
2525+
new_full_scan.id,
2526+
changed_packages=existing_changed_packages,
2527+
)
25042528

2505-
diff = self.create_diff_report(added_packages, removed_packages, unchanged_packages)
2529+
diff = self.create_diff_report(
2530+
added_packages,
2531+
removed_packages,
2532+
unchanged_packages,
2533+
existing_changed_packages=existing_changed_packages,
2534+
)
25062535
diff.packages = packages
25072536

25082537
base_socket = "https://socket.dev/dashboard/org"
@@ -2542,25 +2571,32 @@ def _requires_unchanged_alerts(self) -> bool:
25422571
)
25432572

25442573
def add_existing_alerts_from_full_scan(
2545-
self, unchanged_packages: Dict[str, Package], full_scan_id: str
2574+
self,
2575+
unchanged_packages: Dict[str, Package],
2576+
full_scan_id: str,
2577+
*,
2578+
changed_packages: Optional[Dict[str, Package]] = None,
25462579
) -> None:
2547-
"""Fill in the alerts on unchanged packages from the new full scan.
2580+
"""Load alerts for unchanged and optionally changed packages from the new full scan.
25482581
2549-
The cached diff-scans endpoint returns unchanged artifacts with an empty
2550-
``alerts`` list, because it keeps only the alerts it counts as new. The full
2551-
scan of the same commit carries every package's alerts with their policy
2552-
actions, so they are read from there. Packages are matched by artifact ID,
2553-
then by ecosystem, namespace, name and version.
2582+
The cached comparison keeps only new alerts, so it omits alerts that
2583+
persist across a version change as well as alerts on unchanged packages.
2584+
The full scan carries current alerts with their policy actions. Match
2585+
packages by artifact ID, then by ecosystem, namespace, name and version.
25542586
2555-
Skipped when any unchanged package already has alerts: the comparison then
2556-
came from an endpoint that includes them, such as the streaming fallback.
2557-
A failed fetch or an unmatched package raises, because reporting existing
2558-
alerts as absent would let ``--strict-blocking`` pass a run it should fail.
2587+
The streaming fallback can supply unchanged alerts itself. Changed
2588+
packages, when requested, always need the full scan. A failed fetch or
2589+
unmatched package raises so strict blocking can evaluate all existing alerts.
25592590
"""
2591+
packages_to_load = dict(changed_packages or {})
25602592
if any(package.alerts for package in unchanged_packages.values()):
25612593
log.debug("The comparison already includes alerts on unchanged packages")
2594+
else:
2595+
packages_to_load.update(unchanged_packages)
2596+
if not packages_to_load:
25622597
return
25632598

2599+
package_kind = "current" if changed_packages else "unchanged"
25642600
start = time.time()
25652601
by_id: Dict[str, List[dict]] = {}
25662602
by_identity: Dict[Tuple[str, str, str, str], List[dict]] = {}
@@ -2574,7 +2610,7 @@ def add_existing_alerts_from_full_scan(
25742610

25752611
matched = 0
25762612
alert_count = 0
2577-
for package in unchanged_packages.values():
2613+
for package in packages_to_load.values():
25782614
alerts = by_id.get(package.id)
25792615
if alerts is None:
25802616
alerts = by_identity.get(Core._package_identity(
@@ -2587,12 +2623,12 @@ def add_existing_alerts_from_full_scan(
25872623
alert_count += len(alerts)
25882624

25892625
log.info(
2590-
f"Loaded {alert_count} alerts for {matched} of {len(unchanged_packages)} "
2591-
f"unchanged packages from full scan {full_scan_id} in {time.time() - start:.2f}s"
2626+
f"Loaded {alert_count} alerts for {matched} of {len(packages_to_load)} "
2627+
f"{package_kind} packages from full scan {full_scan_id} in {time.time() - start:.2f}s"
25922628
)
2593-
if matched < len(unchanged_packages):
2629+
if matched < len(packages_to_load):
25942630
raise InfrastructureError(
2595-
f"{len(unchanged_packages) - matched} of {len(unchanged_packages)} unchanged packages "
2631+
f"{len(packages_to_load) - matched} of {len(packages_to_load)} {package_kind} packages "
25962632
f"were not found in full scan {full_scan_id}; unable to evaluate all existing alerts."
25972633
)
25982634

@@ -2628,7 +2664,9 @@ def create_diff_report(
26282664
added_packages: Dict[str, Package],
26292665
removed_packages: Dict[str, Package],
26302666
unchanged_packages: Optional[Dict[str, Package]] = None,
2631-
direct_only: bool = True
2667+
direct_only: bool = True,
2668+
*,
2669+
existing_changed_packages: Optional[Dict[str, Package]] = None,
26322670
) -> Diff:
26332671
"""
26342672
Creates a diff report comparing two sets of packages.
@@ -2637,14 +2675,15 @@ def create_diff_report(
26372675
1. Records new/removed packages (direct only by default)
26382676
2. Collects alerts from both sets of packages
26392677
3. Determines new capabilities introduced
2640-
4. Optionally collects alerts from unchanged packages for --strict-blocking
2678+
4. Optionally collects existing alerts for --strict-blocking
26412679
26422680
Args:
26432681
added_packages: Dict of packages added in new scan
26442682
removed_packages: Dict of packages removed in new scan
26452683
unchanged_packages: Dict of packages that didn't change (for --strict-blocking)
26462684
direct_only: If True, only direct dependencies are included in new/removed lists
26472685
(but alerts are still processed for all packages)
2686+
existing_changed_packages: Added/updated packages with alerts from the new full scan
26482687
26492688
Returns:
26502689
Diff object containing the comparison results
@@ -2654,6 +2693,7 @@ def create_diff_report(
26542693
alerts_in_added_packages: Dict[str, List[Issue]] = {}
26552694
alerts_in_removed_packages: Dict[str, List[Issue]] = {}
26562695
alerts_in_unchanged_packages: Dict[str, List[Issue]] = {}
2696+
current_packages = {**(unchanged_packages or {}), **added_packages}
26572697

26582698
seen_packages = {
26592699
"added": set(),
@@ -2712,10 +2752,25 @@ def create_diff_report(
27122752
alerts_in_removed_packages
27132753
)
27142754

2715-
# Get unchanged alerts (for --strict-blocking mode)
27162755
diff.unchanged_alerts = Core.get_unchanged_alerts(
27172756
alerts_in_unchanged_packages
27182757
)
2758+
if existing_changed_packages:
2759+
current_changed_alerts: Dict[str, List[Issue]] = {}
2760+
for package in existing_changed_packages.values():
2761+
self.add_package_alerts_to_collection(
2762+
package=package,
2763+
alerts_collection=current_changed_alerts,
2764+
packages=current_packages,
2765+
)
2766+
current_findings = Core._consolidate_reportable_alerts(
2767+
alert
2768+
for group in (diff.new_alerts, diff.unchanged_alerts, *current_changed_alerts.values())
2769+
for alert in group
2770+
)
2771+
# Keep the comparison's classification when a finding also appears in the full scan.
2772+
diff.new_alerts = [current_findings.pop(alert.consolidation_key()) for alert in diff.new_alerts]
2773+
diff.unchanged_alerts = list(current_findings.values())
27192774

27202775
# Get removed alerts (for completeness)
27212776
diff.removed_alerts = Core.get_removed_alerts(
@@ -2965,36 +3020,13 @@ def get_new_alerts(
29653020
Returns:
29663021
List of newly found alerts
29673022
"""
2968-
alerts: List[Issue] = []
2969-
consolidated_alerts = set()
2970-
2971-
for alert_key in added_package_alerts:
2972-
if alert_key not in removed_package_alerts:
2973-
new_alerts = added_package_alerts[alert_key]
2974-
for alert in new_alerts:
2975-
finding_key = alert.consolidation_key()
2976-
2977-
if alert.error or alert.warn:
2978-
if finding_key not in consolidated_alerts:
2979-
alerts.append(alert)
2980-
consolidated_alerts.add(finding_key)
2981-
else:
2982-
new_alerts = added_package_alerts[alert_key]
2983-
removed_alerts = removed_package_alerts[alert_key]
2984-
2985-
for alert in new_alerts:
2986-
finding_key = alert.consolidation_key()
2987-
2988-
# Only add if:
2989-
# 1. Alert isn't in removed packages (or we're not ignoring readded alerts)
2990-
# 2. We haven't already recorded this alert
2991-
# 3. It's an error or warning
2992-
if (not ignore_readded or alert not in removed_alerts) and finding_key not in consolidated_alerts:
2993-
if alert.error or alert.warn:
2994-
alerts.append(alert)
2995-
consolidated_alerts.add(finding_key)
2996-
2997-
return alerts
3023+
findings = Core._consolidate_reportable_alerts(
3024+
alert
3025+
for key, alerts in added_package_alerts.items()
3026+
for alert in alerts
3027+
if not ignore_readded or alert not in removed_package_alerts.get(key, ())
3028+
)
3029+
return list(findings.values())
29983030

29993031
@staticmethod
30003032
def get_unchanged_alerts(
@@ -3012,19 +3044,22 @@ def get_unchanged_alerts(
30123044
Returns:
30133045
List of all error/warning alerts from unchanged packages
30143046
"""
3015-
alerts: List[Issue] = []
3016-
consolidated_alerts = set()
3017-
3018-
for alert_key in unchanged_package_alerts:
3019-
for alert in unchanged_package_alerts[alert_key]:
3020-
finding_key = alert.consolidation_key()
3021-
3022-
# Only include error or warning alerts
3023-
if (alert.error or alert.warn) and finding_key not in consolidated_alerts:
3024-
alerts.append(alert)
3025-
consolidated_alerts.add(finding_key)
3047+
findings = Core._consolidate_reportable_alerts(
3048+
alert for alerts in unchanged_package_alerts.values() for alert in alerts
3049+
)
3050+
return list(findings.values())
30263051

3027-
return alerts
3052+
@staticmethod
3053+
def _consolidate_reportable_alerts(alerts: Iterable[Issue]) -> Dict[Tuple[str, str, str, str], Issue]:
3054+
"""Keep the strongest reportable action for each finding across manifests and scan results."""
3055+
findings: Dict[Tuple[str, str, str, str], Issue] = {}
3056+
for alert in alerts:
3057+
if alert.error or alert.warn:
3058+
key = alert.consolidation_key()
3059+
previous = findings.get(key)
3060+
if previous is None or (alert.error and not previous.error):
3061+
findings[key] = alert
3062+
return findings
30283063

30293064
@staticmethod
30303065
def get_removed_alerts(

0 commit comments

Comments
 (0)