Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
23 changes: 7 additions & 16 deletions docs/cli-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion docs/troubleshooting.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand All @@ -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'",
Expand Down
2 changes: 1 addition & 1 deletion socketsecurity/__init__.py
Original file line number Diff line number Diff line change
@@ -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__}'
179 changes: 107 additions & 72 deletions socketsecurity/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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]] = {}
Expand All @@ -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(
Expand All @@ -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."
)

Expand Down Expand Up @@ -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.
Expand All @@ -2637,14 +2675,15 @@ 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
removed_packages: Dict of packages removed in new scan
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
Expand All @@ -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(),
Expand Down Expand Up @@ -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,
)
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
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(
Expand Down Expand Up @@ -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(
Expand All @@ -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(
Expand Down
Loading