Skip to content

Commit f19dc3f

Browse files
committed
Check existing alerts under --strict-blocking when no manifest changed
Without --ignore-commit-files, the CLI reads the changed files to decide whether to compare. When none is a supported manifest it sets force_api_mode, creates a full scan of the target path, and turns blocking off because a full scan has no baseline. That fallback exists so a change that cannot alter dependencies doesn't post a comment or block on alerts it didn't introduce. Under --strict-blocking it also skipped the check the flag exists for: a code-only pull request passed with a warning that --strict-blocking needs diff mode, even when the repository had existing blocking alerts. With --strict-blocking, a change that touches no manifest now runs the comparison over every manifest in the target path, the same way --ignore-commit-files does. Existing alerts are loaded from the new full scan and fail the run, and PR/MR comments list them. Failures reading them keep the infrastructure-error code. Runs without --strict-blocking keep the full-scan fallback, and SCM branch pipelines still create a full scan.
1 parent ef5a7fb commit f19dc3f

9 files changed

Lines changed: 263 additions & 11 deletions

File tree

‎CHANGELOG.md‎

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

3+
## 2.13.1
4+
5+
### Fixed
6+
7+
- `--strict-blocking` fails on existing blocking alerts when the change touches no
8+
manifest. Without `--ignore-commit-files`, such a change used to get a full scan
9+
with blocking turned off, so code-only pull requests passed. The comparison now
10+
runs over every manifest in the target path, and PR/MR comments list the existing
11+
alerts.
12+
313
## 2.13.0
414

515
### Upgrade notes

‎docs/ci-cd.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -510,7 +510,9 @@ A full scan has no baseline, so it cannot tell a newly introduced alert from one
510510
that was already there. Rather than block on a number that would mean something
511511
different depending on which output format was enabled, those runs behave as if
512512
`--disable-blocking` was supplied and report through the Dashboard instead. This
513-
matches how the CLI already treats a run with no supported manifest files.
513+
matches how the CLI treats a change with no supported manifest files, except under
514+
`--strict-blocking`: there a pull request or merge request that touches no manifest
515+
still gets the comparison, so existing blocking alerts fail it.
514516

515517
The event type is authoritative once `--scm` is set: `--enable-diff` and
516518
`--ignore-commit-files` do not turn a branch pipeline into a comparison. To diff

‎docs/cli-reference.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -450,7 +450,7 @@ The CLI runs a pinned version of the Coana CLI, the analysis engine; it does **n
450450
| `--disable-blocking` | False | False | Non-blocking CI mode: the CLI exits **0** even when blocking alerts are present (including with `--strict-blocking`). Also exits 0 on infrastructure errors (missing API or SCM token, Socket API failures, uncaught runtime errors) and interrupts, so the job is treated as successful while findings and errors are still logged. Invalid flags still exit **2**. Takes precedence over `--strict-blocking`. |
451451
| `--disable-ignore` | False | False | Disable support for `@SocketSecurity ignore` commands in PR comments. When set, alerts cannot be suppressed via comments and ignore instructions are hidden from comment output. See [Who can ignore an alert](#who-can-ignore-an-alert). |
452452
| `--ignore-authorization` | False | enforce | Who may suppress alerts with `@SocketSecurity ignore`. `enforce` requires write access and honors the command with a warning when the provider cannot report it; `strict` rejects it in that case; `off` honors any commenter. See [Who can ignore an alert](#who-can-ignore-an-alert). |
453-
| `--strict-blocking` | False | False | Fail on ANY security policy violations (blocking severity), not just new ones. Only works in diff mode. See [Strict Blocking Mode](#strict-blocking-mode) for details. |
453+
| `--strict-blocking` | False | False | Fail on ANY security policy violations (blocking severity), not just new ones. Runs a comparison even when no manifest changed. See [Strict Blocking Mode](#strict-blocking-mode) for details. |
454454
| `--enable-diff` | False | False | Enable diff mode even when using `--integration api` (forces diff mode without SCM integration) |
455455
| `--scm` | False | api | Source control management type |
456456
| `--timeout` | False | 1200 | Positive integer timeout in seconds for each API request. This is not a total CLI runtime limit and does not limit local discovery, Git, or reachability analysis. |
@@ -652,6 +652,7 @@ Security issues detected by Socket Security:
652652
### Important Notes
653653
654654
- **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).
655+
- **No manifest changed**: When the changed files include no supported manifest, the CLI still runs the comparison over every manifest in the target path, as with `--ignore-commit-files`, instead of falling back to a full scan. Code-only pull requests fail on existing blocking alerts and list them in the PR/MR comment. This adds the comparison and existing-alert requests to those runs.
655656
- **Error-Level Only**: Only fails on `error=True` alerts (blocking severity), not warnings.
656657
- **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.
657658
- **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.
@@ -755,14 +756,14 @@ The CLI determines which files to scan based on the following logic:
755756
756757
3. **`--ignore-commit-files` Flag**: When set, the changed-file check is skipped entirely. The CLI runs the comparison regardless of what changed, and scans every manifest file in the target directory.
757758
758-
4. **Automatic Fallback**: If no manifest files are found in git commit changes and no `--files` are specified, the CLI automatically switches to "API mode" and performs a full repository scan.
759+
4. **Automatic Fallback**: If no manifest files are found in git commit changes and no `--files` are specified, the CLI automatically switches to "API mode" and performs a full repository scan. With `--strict-blocking`, it runs the comparison instead, as `--ignore-commit-files` does, so existing blocking alerts are still checked.
759760
760761
> **Important**: The CLI doesn't scan only the specified files - it uses them to determine whether a scan should be performed and what type of scan to run. When triggered, it searches the entire `--target-path` for all supported manifest files.
761762
762763
### Scanning Modes
763764
764765
- **Differential Mode**: When manifest files are detected in changes, performs a diff scan with PR/MR comment integration
765-
- **API Mode**: When no manifest files are in changes, creates a full scan report without PR comments but still scans the entire repository
766+
- **API Mode**: When no manifest files are in changes, creates a full scan report without PR comments but still scans the entire repository. Not used with `--strict-blocking`
766767
- **Force Mode**: With `--ignore-commit-files`, always runs a comparison regardless of which files changed, over every manifest in the target path
767768
- **Forced Diff Mode**: With `--enable-diff`, forces differential mode even when using `--integration api` (without SCM integration)
768769

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
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.0"
9+
version = "2.13.1"
1010
requires-python = ">= 3.11"
1111
license = {"file" = "LICENSE"}
1212
dependencies = [

‎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.0'
2+
__version__ = '2.13.1'
33
USER_AGENT_NAME = 'socket-python-cli'
44
USER_AGENT = f'{USER_AGENT_NAME}/{__version__}'

‎socketsecurity/config.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1058,7 +1058,8 @@ def create_argument_parser() -> argparse.ArgumentParser:
10581058
"--strict-blocking",
10591059
dest="strict_blocking",
10601060
action="store_true",
1061-
help="Fail on ANY security policy violations (blocking severity), not just new ones. Only works in diff mode."
1061+
help="Fail on ANY security policy violations (blocking severity), not just new ones. Runs a comparison even "
1062+
"when no manifest changed. SCM branch (non-PR/MR) pipelines create a full scan and do not block."
10621063
)
10631064
advanced_group.add_argument(
10641065
"--enable-diff",

‎socketsecurity/socketcli.py‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -658,7 +658,18 @@ def main_code(config: Optional[CliConfig] = None):
658658
log.debug(f"Error finding files in scan paths: {e}")
659659
discovered_scan_files = None
660660
has_supported_files = False
661-
661+
662+
# --strict-blocking fails on existing blocking alerts, and only a comparison
663+
# against the baseline reports them. A change that touches no manifest would
664+
# otherwise get a full scan with blocking turned off and pass every time, so
665+
# run the comparison over the whole target path, as --ignore-commit-files does.
666+
if config.strict_blocking and not has_supported_files and not force_diff_mode:
667+
force_diff_mode = True
668+
log.info(
669+
"No supported manifest in the changed files; --strict-blocking compares "
670+
"every manifest in the target path against the baseline to check existing alerts"
671+
)
672+
662673
# Case 3: If no supported files or files are empty, force API mode (no PR comments)
663674
# BUT: Don't force API mode if we're in force_diff_mode
664675
log.debug(f"files_to_check={files_to_check}, has_supported_files={has_supported_files}, force_diff_mode={force_diff_mode}, config.enable_diff={config.enable_diff}")
@@ -979,8 +990,9 @@ def _is_unprocessed(c):
979990
output_handler.handle_output(diff)
980991

981992
elif (config.enable_diff or force_diff_mode) and force_api_mode:
982-
# User requested diff mode but no manifest files were detected - this should not happen with new logic
983-
# but keeping as a safety net
993+
# --enable-diff without --ignore-commit-files, and the change touched no
994+
# manifest. --strict-blocking never reaches this branch: it sets
995+
# force_diff_mode above so existing alerts are still evaluated.
984996
log.warning("--enable-diff was specified but no supported manifest files were detected in the changed files. Falling back to full scan mode.")
985997
_log_scan_mode_fallback(
986998
"diff",
Lines changed: 226 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,226 @@
1+
"""`--strict-blocking` on a change that touches no manifest.
2+
3+
Without `--ignore-commit-files`, the CLI reads the changed files to decide whether
4+
to compare. When none is a supported manifest it used to create a full scan, turn
5+
blocking off and warn that `--strict-blocking` needs diff mode, so a code-only pull
6+
request passed even with existing blocking alerts. Under `--strict-blocking` the
7+
comparison now runs anyway, the way `--ignore-commit-files` runs it. Runs without
8+
the flag keep the full-scan fallback.
9+
"""
10+
11+
import sys
12+
from contextlib import nullcontext
13+
from types import SimpleNamespace
14+
from unittest.mock import MagicMock, Mock
15+
16+
import pytest
17+
18+
from socketsecurity import socketcli
19+
from socketsecurity.core import Core
20+
from socketsecurity.core.classes import Diff, Issue, Package
21+
from socketsecurity.core.scm.github import Github
22+
23+
TOKEN_VARS = (
24+
"SOCKET_SECURITY_API_KEY", "SOCKET_SECURITY_API_TOKEN", "SOCKET_API_KEY", "SOCKET_API_TOKEN",
25+
"GH_API_TOKEN", "GITLAB_TOKEN",
26+
)
27+
POLICIES = [
28+
pytest.param([], 3, id="default"),
29+
pytest.param(["--exit-code-on-api-error", "100"], 100, id="remap"),
30+
pytest.param(["--disable-blocking"], 0, id="nonblocking"),
31+
]
32+
# Each mode reaches the no-manifest fallback by a different path.
33+
MODES = [
34+
pytest.param(["--enable-diff"], True, id="enable-diff"),
35+
pytest.param([], True, id="api-default"),
36+
pytest.param(["--files", '["src/index.js"]'], True, id="files-without-manifest"),
37+
pytest.param([], False, id="not-a-git-repo"),
38+
]
39+
40+
41+
def _existing_blocker() -> Issue:
42+
return Issue(
43+
pkg_name="handlebars",
44+
pkg_version="4.0.11",
45+
pkg_type="npm",
46+
severity="critical",
47+
title="Critical CVE",
48+
description="Prototype pollution",
49+
type="criticalCVE",
50+
url="https://socket.dev/npm/package/handlebars/overview/4.0.11",
51+
manifests="package-lock.json",
52+
props={"ghsaId": "GHSA-w457-6q6x-cgp9"},
53+
key="existing-key",
54+
purl="pkg:npm/handlebars@4.0.11",
55+
error=True,
56+
warn=False,
57+
ignore=False,
58+
monitor=False,
59+
suggestion="Upgrade handlebars",
60+
next_step_title="Next steps",
61+
)
62+
63+
64+
@pytest.fixture
65+
def cli_runtime(monkeypatch):
66+
for name in TOKEN_VARS:
67+
monkeypatch.delenv(name, raising=False)
68+
monkeypatch.setenv("BUILDKITE", "false")
69+
sdk = MagicMock()
70+
monkeypatch.setattr(socketcli, "build_socket_sdk", Mock(return_value=sdk))
71+
monkeypatch.setattr(socketcli, "CliClient", Mock())
72+
monkeypatch.setattr(socketcli, "StreamingLogs", lambda **kwargs: nullcontext(Mock()))
73+
git_repo = SimpleNamespace(changed_files=["README.md"], is_default_branch=False, remote_url=None)
74+
in_git_repo = {"value": True}
75+
76+
def apply_git_context(config):
77+
if not in_git_repo["value"]:
78+
config.ignore_commit_files = True
79+
return False, None
80+
return True, git_repo
81+
82+
monkeypatch.setattr(socketcli, "apply_git_context", apply_git_context)
83+
monkeypatch.setattr(
84+
Core,
85+
"has_manifest_files",
86+
lambda self, files: any(f.endswith(("package.json", "package-lock.json")) for f in files),
87+
)
88+
monkeypatch.setattr(Core, "find_files", Mock(return_value=["package.json"]))
89+
diff = Diff(id="compared")
90+
compare = Mock(return_value=diff)
91+
full_scan = Mock(return_value=Diff(id="full", report_url="", diff_url=""))
92+
monkeypatch.setattr(Core, "create_new_diff", compare)
93+
monkeypatch.setattr(Core, "create_full_scan_with_report_url", full_scan)
94+
monkeypatch.setattr(socketcli.OutputHandler, "handle_output", Mock())
95+
96+
def run(flags=(), *, git=True):
97+
in_git_repo["value"] = git
98+
argv = [
99+
"socketcli", "--api-token", "test", "--repo", "repo", "--branch", "feature",
100+
"--integration", "api", *flags,
101+
]
102+
monkeypatch.setattr(sys, "argv", argv)
103+
with pytest.raises(SystemExit) as result:
104+
socketcli.cli()
105+
return result.value.code
106+
107+
return SimpleNamespace(
108+
sdk=sdk, git_repo=git_repo, diff=diff, compare=compare, full_scan=full_scan, run=run,
109+
)
110+
111+
112+
@pytest.mark.parametrize("mode, git", MODES)
113+
def test_existing_blocker_fails_a_change_without_manifests(cli_runtime, mode, git):
114+
cli_runtime.diff.unchanged_alerts = [_existing_blocker()]
115+
116+
assert cli_runtime.run([*mode, "--strict-blocking"], git=git) == 1
117+
cli_runtime.compare.assert_called_once()
118+
cli_runtime.full_scan.assert_not_called()
119+
120+
121+
@pytest.mark.parametrize("mode, git", MODES)
122+
def test_no_existing_blocker_passes_a_change_without_manifests(cli_runtime, mode, git):
123+
cli_runtime.diff.unchanged_alerts = [Issue(error=False, warn=True)]
124+
125+
assert cli_runtime.run([*mode, "--strict-blocking"], git=git) == 0
126+
cli_runtime.compare.assert_called_once()
127+
cli_runtime.full_scan.assert_not_called()
128+
129+
130+
def test_disable_blocking_still_wins(cli_runtime):
131+
cli_runtime.diff.unchanged_alerts = [_existing_blocker()]
132+
133+
assert cli_runtime.run(["--enable-diff", "--strict-blocking", "--disable-blocking"]) == 0
134+
cli_runtime.compare.assert_called_once()
135+
136+
137+
@pytest.mark.parametrize("mode, git", MODES)
138+
def test_without_strict_blocking_the_full_scan_fallback_is_unchanged(cli_runtime, mode, git):
139+
cli_runtime.full_scan.return_value = Diff(
140+
id="full", report_url="", diff_url="", new_alerts=[_existing_blocker()]
141+
)
142+
143+
assert cli_runtime.run(mode, git=git) == 0
144+
cli_runtime.full_scan.assert_called_once()
145+
cli_runtime.compare.assert_not_called()
146+
147+
148+
def test_no_fallback_warning_under_strict_blocking(cli_runtime, caplog):
149+
cli_runtime.diff.unchanged_alerts = [_existing_blocker()]
150+
151+
cli_runtime.run(["--enable-diff", "--strict-blocking"])
152+
153+
assert "Falling back to full scan mode" not in caplog.text
154+
assert "only supported in diff mode" not in caplog.text
155+
156+
157+
def test_changed_manifest_still_compares(cli_runtime):
158+
cli_runtime.git_repo.changed_files = ["package.json"]
159+
cli_runtime.diff.unchanged_alerts = [_existing_blocker()]
160+
161+
assert cli_runtime.run(["--enable-diff", "--strict-blocking"]) == 1
162+
assert cli_runtime.run(["--enable-diff"]) == 0
163+
assert cli_runtime.compare.call_count == 2
164+
cli_runtime.full_scan.assert_not_called()
165+
166+
167+
@pytest.mark.parametrize("policy, infrastructure_code", POLICIES)
168+
def test_unreadable_existing_alerts_use_the_infrastructure_code(cli_runtime, policy, infrastructure_code):
169+
package = Package(id="pkg", type="npm", name="pkg", version="1", score={}, alerts=[])
170+
cli_runtime.sdk.fullscans.stream.return_value = SimpleNamespace(success=True, artifacts={})
171+
172+
def compare(*args, **kwargs):
173+
core = Core.__new__(Core)
174+
core.sdk = cli_runtime.sdk
175+
core.config = SimpleNamespace(org_slug="acme")
176+
core.add_existing_alerts_from_full_scan({package.id: package}, "new")
177+
178+
cli_runtime.compare.side_effect = compare
179+
180+
assert cli_runtime.run(["--enable-diff", "--strict-blocking", *policy]) == infrastructure_code
181+
182+
183+
@pytest.fixture
184+
def github_pull_request(cli_runtime, monkeypatch):
185+
monkeypatch.setenv("GH_API_TOKEN", "test")
186+
monkeypatch.setenv("GITHUB_EVENT_NAME", "pull_request")
187+
monkeypatch.setenv("EVENT_ACTION", "synchronize")
188+
monkeypatch.setenv("GITHUB_REPOSITORY", "acme/repo")
189+
monkeypatch.setenv("PR_NUMBER", "7")
190+
monkeypatch.setattr(Github, "get_comments_for_pr", Mock(return_value={}))
191+
add_comments = Mock()
192+
monkeypatch.setattr(Github, "add_socket_comments", add_comments)
193+
return add_comments
194+
195+
196+
def test_code_only_pull_request_comments_on_existing_blockers(cli_runtime, github_pull_request):
197+
cli_runtime.diff.unchanged_alerts = [_existing_blocker()]
198+
199+
assert cli_runtime.run(["--scm", "github", "--strict-blocking"]) == 1
200+
cli_runtime.compare.assert_called_once()
201+
github_pull_request.assert_called_once()
202+
security_comment, _, _, post_security, _ = github_pull_request.call_args.args
203+
assert post_security is True
204+
assert "handlebars@4.0.11" in security_comment
205+
assert "Existing alerts" in security_comment
206+
207+
208+
def test_code_only_pull_request_without_strict_blocking_skips_the_comment(
209+
cli_runtime, github_pull_request
210+
):
211+
assert cli_runtime.run(["--scm", "github"]) == 0
212+
cli_runtime.full_scan.assert_called_once()
213+
cli_runtime.compare.assert_not_called()
214+
github_pull_request.assert_not_called()
215+
216+
217+
def test_branch_pipeline_still_creates_a_full_scan(cli_runtime, monkeypatch):
218+
# Non-PR SCM pipelines have no baseline; --strict-blocking does not change that.
219+
monkeypatch.setenv("GH_API_TOKEN", "test")
220+
monkeypatch.setenv("GITHUB_EVENT_NAME", "push")
221+
monkeypatch.setenv("GITHUB_REPOSITORY", "acme/repo")
222+
monkeypatch.delenv("PR_NUMBER", raising=False)
223+
224+
assert cli_runtime.run(["--scm", "github", "--pr-number", "0", "--strict-blocking"]) == 0
225+
cli_runtime.full_scan.assert_called_once()
226+
cli_runtime.compare.assert_not_called()

‎uv.lock‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)