diff --git a/CHANGELOG.md b/CHANGELOG.md index 49751340..4bdc33ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ ## 2.14.0 +### Upgrade notes + +- Without a GitHub or GitLab SCM adapter, `--strict-blocking` now compares scans + even when no manifest changed. This includes default-branch pushes and scans of + non-git paths. These runs can now fail on Block findings or comparison errors + and need the [API token scopes for comparison runs](docs/troubleshooting.md#api-token-permissions). + ### Changed - Updated the Socket Python SDK (`socketdev`) to 3.6.4. This can increase @@ -18,6 +25,9 @@ - Comparisons with missing or invalid package lists fail with exit `3` by default. `--exit-code-on-api-error` can remap the code, and `--disable-blocking` takes precedence. +- `--strict-blocking` checks existing Block findings on code-only changes. + GitHub and GitLab pull request comments show those findings under Existing + alerts. ## 2.13.2 diff --git a/docs/ci-cd.md b/docs/ci-cd.md index bd772b3c..7eb26af9 100644 --- a/docs/ci-cd.md +++ b/docs/ci-cd.md @@ -500,23 +500,26 @@ pipelines: ## Scan type by pipeline -With `--scm github` or `--scm gitlab`, the detected event decides the scan type: +With `--scm github` or `--scm gitlab`, the adapter uses the event and PR/MR +context to select the scan type. A push given a PR/MR number can use the +comparison path. | Event | Scan | Blocks the build | |:------|:-----|:-----------------| | Pull request / merge request | Diff scan against the repository's baseline | Yes, on new blocking alerts; also existing blockers with `--strict-blocking` | | Any other pipeline, including default-branch pushes | Full scan | No | -A full scan has no baseline, so it cannot tell a newly introduced alert from one -that was already there. Rather than block on a number that would mean something -different depending on which output format was enabled, those runs behave as if -`--disable-blocking` was supplied and report through the Dashboard instead. This -matches how the CLI already treats a run with no supported manifest files. - -The event type is authoritative once `--scm` is set: `--enable-diff` and -`--ignore-commit-files` do not turn a branch pipeline into a comparison. To diff -a branch build, drop `--scm` and use `--enable-diff` with `--integration`, which -runs the comparison without the PR comment adapter. +With changed-file detection, a PR/MR with no supported manifest change runs a +full scan by default. Use `--strict-blocking` or `--ignore-commit-files` to +compare it. Full scans report through the Dashboard. A branch pipeline without +PR/MR context stays in full-scan mode even with `--enable-diff`, +`--ignore-commit-files`, or `--strict-blocking`. + +Without a GitHub or GitLab SCM adapter, `--strict-blocking` runs a comparison +even when no supported manifest changed. This includes default-branch pushes and +scans of non-git paths. A Block finding exits `1`. A comparison infrastructure +error exits `3` by default. Check the [API token scopes for comparison runs](troubleshooting.md#api-token-permissions) +when upgrading a pipeline that previously ran only full scans. `--generate-license` and `--legal-format fossa` work on both paths; a full scan fetches the package list for them. diff --git a/docs/cli-reference.md b/docs/cli-reference.md index cd16ac4a..3824cb24 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -461,12 +461,12 @@ The CLI runs a pinned version of the Coana CLI, the analysis engine; it does **n #### Advanced Configuration | Parameter | Required | Default | Description | |:-------------------------|:---------|:--------|:----------------------------------------------------------------------| -| `--ignore-commit-files` | False | False | Compare regardless of which files changed, scanning every manifest | +| `--ignore-commit-files` | False | False | Skip the changed-file check for comparisons eligible under the SCM event rules. | | `--exit-code-on-api-error` | False | 3 | Remap infrastructure failures, including missing tokens, setup failures, incomplete scan data and unexpected runtime errors. Findings (`1`), usage errors (`2`) and Ctrl+C (`130`) are unaffected. `--disable-blocking` takes precedence. | | `--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`. | | `--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). | | `--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). | -| `--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. | +| `--strict-blocking` | False | False | Fail on new and existing Block findings, including on changes that touch no manifest. See [Strict Blocking Mode](#strict-blocking-mode). | | `--enable-diff` | False | False | Enable diff mode even when using `--integration api` (forces diff mode without SCM integration) | | `--scm` | False | api | Source control management type | | `--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. | @@ -660,7 +660,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). +- **Scan scope**. Strict mode compares the configured scan scope even when no supported manifest changed. Scan options such as `--sub-path` and `--reach-use-only-pregenerated-sboms` still control what the CLI submits. With `--scm`, GitHub and GitLab branch pipelines without PR/MR context perform non-blocking full scans. See [Scan type by pipeline](ci-cd.md#scan-type-by-pipeline). +- **With `--reach`**. With no explicit baseline, the CLI looks for a default-branch head scan with reachability enabled. If none exists, the CLI compares against an empty baseline and classifies all findings as new. Scan the default branch with `--reach` too. - **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. @@ -762,25 +763,26 @@ The CLI determines which files to scan based on the following logic: 2. **`--files` Parameter Override**: When specified, this parameter takes precedence over git commit detection. It accepts a JSON array of file paths to check for manifest files. -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. +3. **`--ignore-commit-files` Flag**: Skip the changed-file check for comparisons, subject to the SCM event type. -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. +4. **Automatic Fallback**: When the changed-file check finds no supported manifest, the CLI normally runs a full scan. Strict mode compares scans so it can evaluate existing findings. See [Scan type by pipeline](ci-cd.md#scan-type-by-pipeline) for SCM event rules. -> **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. +The changed-file list and `--files` select the scan type. Manifest discovery +uses the configured scan scope, including any `--sub-path` restrictions. ### Scanning Modes - **Differential Mode**: When manifest files are detected in changes, performs a diff scan with PR/MR comment integration -- **API Mode**: When no manifest files are in changes, creates a full scan report without PR comments but still scans the entire repository -- **Force Mode**: With `--ignore-commit-files`, always runs a comparison regardless of which files changed, over every manifest in the target path +- **Full Scan**: Reports findings to the Dashboard. SCM branch pipelines without PR/MR context use this mode. +- **Force Mode**: With `--ignore-commit-files`, compares regardless of which files changed on pipelines eligible for comparison. - **Forced Diff Mode**: With `--enable-diff`, forces differential mode even when using `--integration api` (without SCM integration) ### Examples - **Commit with manifest file**: If your commit includes changes to `package.json`, a differential scan will be triggered automatically with PR comment integration. -- **Commit without manifest files**: If your commit only changes non-manifest files (like `.github/workflows/socket.yaml`), the CLI automatically switches to API mode and performs a full repository scan. +- **Code-only commit**: The CLI runs a full scan by default. `--strict-blocking` selects a comparison on pipelines eligible for comparison. - **Using `--files`**: If you specify `--files '["package.json"]'`, the CLI will check if this file exists and is a manifest file before determining scan type. -- **Using `--ignore-commit-files`**: This runs the comparison regardless of what's in your commit, over all manifest files in the target path. Use it when the changed-file check would otherwise skip a comparison you need. +- **Using `--ignore-commit-files`**: Compare the configured scan scope regardless of which files changed when the pipeline supports comparison. - **Using `--enable-diff`**: Forces diff mode without SCM integration - useful when you want differential scanning but are using `--integration api`. For example: `socketcli --integration api --enable-diff --target-path /path/to/repo` - **Auto-detection**: Most CI/CD scenarios now work with just `socketcli --target-path /path/to/repo --scm github --pr-number $PR_NUM` diff --git a/socketsecurity/config.py b/socketsecurity/config.py index a11ad252..d2a8322a 100644 --- a/socketsecurity/config.py +++ b/socketsecurity/config.py @@ -1058,7 +1058,8 @@ def create_argument_parser() -> argparse.ArgumentParser: "--strict-blocking", dest="strict_blocking", action="store_true", - help="Fail on ANY security policy violations (blocking severity), not just new ones. Only works in diff mode." + help="Fail on new and existing Block findings. Compare even when no manifest changed. " + "With --scm, branch pipelines without PR/MR context run non-blocking full scans." ) advanced_group.add_argument( "--enable-diff", diff --git a/socketsecurity/socketcli.py b/socketsecurity/socketcli.py index 1a05a302..ce48e226 100644 --- a/socketsecurity/socketcli.py +++ b/socketsecurity/socketcli.py @@ -658,7 +658,14 @@ def main_code(config: Optional[CliConfig] = None): log.debug(f"Error finding files in scan paths: {e}") discovered_scan_files = None has_supported_files = False - + + # Strict blocking needs a comparison even when file selection finds no manifest. + strict_forced_comparison = ( + config.strict_blocking and not has_supported_files and not force_diff_mode + ) + if strict_forced_comparison: + force_diff_mode = True + # Case 3: If no supported files or files are empty, force API mode (no PR comments) # BUT: Don't force API mode if we're in force_diff_mode 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}") @@ -762,6 +769,11 @@ def _is_unprocessed(c): return True scm_event_type = scm.check_event_type() if scm is not None else None + if strict_forced_comparison and scm_event_type in (None, "diff"): + log.info( + "No supported manifest triggered a comparison. " + "--strict-blocking compares the configured scan scope to check existing alerts." + ) # Every branch below except the SCM full-scan one produces a comparison, or # is already covered by force_api_mode. See the blocking guard after the # scan for why this is tracked. @@ -979,8 +991,6 @@ def _is_unprocessed(c): output_handler.handle_output(diff) elif (config.enable_diff or force_diff_mode) and force_api_mode: - # User requested diff mode but no manifest files were detected - this should not happen with new logic - # but keeping as a safety net log.warning("--enable-diff was specified but no supported manifest files were detected in the changed files. Falling back to full scan mode.") _log_scan_mode_fallback( "diff", diff --git a/tests/core/test_strict_blocking_no_manifest_change.py b/tests/core/test_strict_blocking_no_manifest_change.py new file mode 100644 index 00000000..d2ab41bc --- /dev/null +++ b/tests/core/test_strict_blocking_no_manifest_change.py @@ -0,0 +1,398 @@ +"""Scan routing and policy enforcement when no supported manifest changed.""" + +import sys +from contextlib import nullcontext +from types import SimpleNamespace +from unittest.mock import MagicMock, Mock + +import pytest + +from socketsecurity import socketcli +from socketsecurity.core import Core +from socketsecurity.core.classes import Diff, Issue +from socketsecurity.core.scm.github import Github +from socketsecurity.core.scm.gitlab import Gitlab +from tests.core.test_existing_alerts import ( + BUCKETS, + HANDLEBARS_CRITICAL_ADVISORIES, + _cve_alert, + _diff_artifact, + _scan_artifact, + _stream_through_sdk, +) + +TOKEN_VARS = ( + "SOCKET_SECURITY_API_KEY", + "SOCKET_SECURITY_API_TOKEN", + "SOCKET_API_KEY", + "SOCKET_API_TOKEN", + "GH_API_TOKEN", + "GITLAB_TOKEN", + "CI_JOB_TOKEN", + "CI_MERGE_REQUEST_IID", +) +STRICT_COMPARISON_LOG = "--strict-blocking compares the configured scan scope" +POLICIES = [ + pytest.param([], 3, id="default"), + pytest.param(["--exit-code-on-api-error", "100"], 100, id="remap"), + pytest.param(["--disable-blocking"], 0, id="nonblocking"), +] +MODES = [ + pytest.param(["--enable-diff"], True, id="enable-diff"), + pytest.param([], True, id="api-default"), + pytest.param(["--files", '["src/index.js"]'], True, id="files-without-manifest"), + pytest.param([], False, id="not-a-git-repo"), +] + + +def _existing_blocker() -> Issue: + return Issue( + pkg_name="handlebars", + pkg_version="4.0.11", + pkg_type="npm", + severity="critical", + title="Critical CVE", + description="Prototype pollution", + type="criticalCVE", + url="https://socket.dev/npm/package/handlebars/overview/4.0.11", + manifests="package-lock.json", + props={"ghsaId": "GHSA-w457-6q6x-cgp9"}, + key="existing-key", + purl="pkg:npm/handlebars@4.0.11", + error=True, + warn=False, + ignore=False, + monitor=False, + suggestion="Upgrade handlebars", + next_step_title="Next steps", + ) + + +@pytest.fixture +def cli_runtime(monkeypatch): + for name in TOKEN_VARS: + monkeypatch.delenv(name, raising=False) + monkeypatch.setenv("BUILDKITE", "false") + sdk = MagicMock() + monkeypatch.setattr(socketcli, "build_socket_sdk", Mock(return_value=sdk)) + monkeypatch.setattr(socketcli, "CliClient", Mock()) + monkeypatch.setattr( + socketcli, "StreamingLogs", lambda **kwargs: nullcontext(Mock()) + ) + git_repo = SimpleNamespace( + changed_files=["README.md"], is_default_branch=False, remote_url=None + ) + in_git_repo = {"value": True} + + def apply_git_context(config): + if not in_git_repo["value"]: + config.ignore_commit_files = True + return False, None + return True, git_repo + + monkeypatch.setattr(socketcli, "apply_git_context", apply_git_context) + monkeypatch.setattr( + Core, + "has_manifest_files", + lambda self, files: any( + f.endswith(("package.json", "package-lock.json")) for f in files + ), + ) + monkeypatch.setattr(Core, "find_files", Mock(return_value=["package.json"])) + diff = Diff(id="compared") + create_new_diff = Core.create_new_diff + compare = Mock(return_value=diff) + full_scan = Mock(return_value=Diff(id="full", report_url="", diff_url="")) + monkeypatch.setattr(Core, "create_new_diff", compare) + monkeypatch.setattr(Core, "create_full_scan_with_report_url", full_scan) + monkeypatch.setattr(socketcli.OutputHandler, "handle_output", Mock()) + + def run(flags=(), *, git=True): + in_git_repo["value"] = git + argv = [ + "socketcli", + "--api-token", + "test", + "--repo", + "repo", + "--branch", + "feature", + "--integration", + "api", + *flags, + ] + monkeypatch.setattr(sys, "argv", argv) + with pytest.raises(SystemExit) as result: + socketcli.cli() + return result.value.code + + return SimpleNamespace( + sdk=sdk, + git_repo=git_repo, + diff=diff, + create_new_diff=create_new_diff, + compare=compare, + full_scan=full_scan, + run=run, + ) + + +@pytest.mark.parametrize("mode, git", MODES) +def test_existing_blocker_fails_a_change_without_manifests(cli_runtime, mode, git): + cli_runtime.diff.unchanged_alerts = [_existing_blocker()] + + assert cli_runtime.run([*mode, "--strict-blocking"], git=git) == 1 + cli_runtime.compare.assert_called_once() + cli_runtime.full_scan.assert_not_called() + + +@pytest.mark.parametrize("mode, git", MODES) +def test_no_existing_blocker_passes_a_change_without_manifests(cli_runtime, mode, git): + cli_runtime.diff.unchanged_alerts = [Issue(error=False, warn=True)] + + assert cli_runtime.run([*mode, "--strict-blocking"], git=git) == 0 + cli_runtime.compare.assert_called_once() + cli_runtime.full_scan.assert_not_called() + + +def test_disable_blocking_still_wins(cli_runtime): + cli_runtime.diff.unchanged_alerts = [_existing_blocker()] + + assert ( + cli_runtime.run(["--enable-diff", "--strict-blocking", "--disable-blocking"]) + == 0 + ) + cli_runtime.compare.assert_called_once() + + +@pytest.mark.parametrize("mode, git", MODES) +def test_without_strict_blocking_the_full_scan_fallback_is_unchanged( + cli_runtime, mode, git +): + cli_runtime.full_scan.return_value = Diff( + id="full", report_url="", diff_url="", new_alerts=[_existing_blocker()] + ) + + assert cli_runtime.run(mode, git=git) == 0 + cli_runtime.full_scan.assert_called_once() + cli_runtime.compare.assert_not_called() + + +def test_no_fallback_warning_under_strict_blocking(cli_runtime, caplog): + cli_runtime.diff.unchanged_alerts = [_existing_blocker()] + + cli_runtime.run(["--enable-diff", "--strict-blocking"]) + + assert "Falling back to full scan mode" not in caplog.text + assert "only supported in diff mode" not in caplog.text + + +def test_changed_manifest_still_compares(cli_runtime): + cli_runtime.git_repo.changed_files = ["package.json"] + cli_runtime.diff.unchanged_alerts = [_existing_blocker()] + + assert cli_runtime.run(["--enable-diff", "--strict-blocking"]) == 1 + assert cli_runtime.run(["--enable-diff"]) == 0 + assert cli_runtime.compare.call_count == 2 + cli_runtime.full_scan.assert_not_called() + + +@pytest.fixture +def comparison(cli_runtime, monkeypatch): + monkeypatch.setattr(Core, "create_new_diff", cli_runtime.create_new_diff) + monkeypatch.setattr(Core, "get_org_id_slug", Mock(return_value=("org-id", "acme"))) + monkeypatch.setattr( + Core, "resolve_base_full_scan_id", Mock(return_value="baseline") + ) + upload = Mock(return_value=SimpleNamespace(id="head")) + monkeypatch.setattr(Core, "create_full_scan", upload) + monkeypatch.setattr( + Core, "find_files", Mock(return_value=["package.json", "package-lock.json"]) + ) + cli_runtime.sdk.diffscans.create_from_ids.return_value = { + "diff_scan": {"id": "comparison"} + } + cli_runtime.sdk.diffscans.get.return_value = { + "diff_scan": { + "artifacts": { + **{bucket: [] for bucket in BUCKETS}, + "unchanged": [_diff_artifact("unchanged", "u1", "handlebars")], + } + } + } + return upload + + +@pytest.fixture +def github_pull_request(cli_runtime, monkeypatch): + monkeypatch.setenv("GH_API_TOKEN", "test") + monkeypatch.setenv("GITHUB_EVENT_NAME", "pull_request") + monkeypatch.setenv("EVENT_ACTION", "synchronize") + monkeypatch.setenv("GITHUB_REPOSITORY", "acme/repo") + monkeypatch.setenv("PR_NUMBER", "7") + monkeypatch.setattr(Github, "get_comments_for_pr", Mock(return_value={})) + add_comments = Mock() + monkeypatch.setattr(Github, "add_socket_comments", add_comments) + return add_comments + + +@pytest.mark.parametrize( + "event, extra", + [ + pytest.param("pull_request", [], id="pull-request"), + pytest.param( + "pull_request", ["--ignore-commit-files"], id="ignore-commit-files" + ), + pytest.param("push", [], id="push-with-pr-number"), + ], +) +def test_code_only_scan_with_pr_context_comments_on_each_existing_blocker( + cli_runtime, github_pull_request, comparison, monkeypatch, event, extra +): + monkeypatch.setenv("GITHUB_EVENT_NAME", event) + resolved, *blocking = HANDLEBARS_CRITICAL_ADVISORIES[:3] + alerts = [_cve_alert(*resolved, action="ignore")] + alerts.extend(_cve_alert(ghsa, cve) for ghsa, cve in blocking) + _stream_through_sdk(cli_runtime, _scan_artifact("u1", "handlebars", alerts)) + + assert cli_runtime.run(["--scm", "github", "--strict-blocking", *extra]) == 1 + assert comparison.call_args.args[0] == ["package.json", "package-lock.json"] + compare_params = cli_runtime.sdk.diffscans.create_from_ids.call_args.args[1] + assert (compare_params["before"], compare_params["after"]) == ("baseline", "head") + cli_runtime.sdk.fullscans.stream.assert_called_once() + cli_runtime.full_scan.assert_not_called() + github_pull_request.assert_called_once() + security_comment, _, _, post_security, _ = github_pull_request.call_args.args + assert post_security is True + assert "Existing alerts (2)" in security_comment + assert resolved[0].upper() not in security_comment + for ghsa, _ in blocking: + assert ghsa.upper() in security_comment + + +@pytest.mark.parametrize("policy, infrastructure_code", POLICIES) +@pytest.mark.parametrize("failure", ["incomplete-comparison", "missing-package"]) +def test_code_only_pull_request_maps_comparison_failures( + cli_runtime, github_pull_request, comparison, policy, infrastructure_code, failure +): + if failure == "incomplete-comparison": + cli_runtime.sdk.diffscans.get.return_value = {"diff_scan": {"incomplete": True}} + else: + cli_runtime.sdk.fullscans.stream.return_value = SimpleNamespace( + success=True, artifacts={} + ) + + assert ( + cli_runtime.run(["--scm", "github", "--strict-blocking", *policy]) + == infrastructure_code + ) + comparison.assert_called_once() + cli_runtime.sdk.fullscans.stream_diff.assert_not_called() + github_pull_request.assert_not_called() + + +def test_code_only_pull_request_without_strict_blocking_skips_the_comment( + cli_runtime, github_pull_request +): + assert cli_runtime.run(["--scm", "github"]) == 0 + cli_runtime.full_scan.assert_called_once() + cli_runtime.compare.assert_not_called() + github_pull_request.assert_not_called() + + +def test_branch_pipeline_still_creates_a_full_scan(cli_runtime, monkeypatch, caplog): + monkeypatch.setenv("GH_API_TOKEN", "test") + monkeypatch.setenv("GITHUB_EVENT_NAME", "push") + monkeypatch.setenv("GITHUB_REPOSITORY", "acme/repo") + monkeypatch.delenv("PR_NUMBER", raising=False) + cli_runtime.full_scan.return_value = Diff( + id="full", report_url="", diff_url="", new_alerts=[_existing_blocker()] + ) + + assert ( + cli_runtime.run(["--scm", "github", "--pr-number", "0", "--strict-blocking"]) + == 0 + ) + cli_runtime.full_scan.assert_called_once() + cli_runtime.compare.assert_not_called() + assert STRICT_COMPARISON_LOG not in caplog.text + + +def test_api_mode_default_branch_push_compares(cli_runtime): + cli_runtime.git_repo.is_default_branch = True + cli_runtime.diff.unchanged_alerts = [_existing_blocker()] + + assert cli_runtime.run(["--default-branch", "--strict-blocking"]) == 1 + cli_runtime.compare.assert_called_once() + assert cli_runtime.compare.call_args.args[1].make_default_branch is True + cli_runtime.full_scan.assert_not_called() + + +def test_comparison_is_logged_when_it_runs(cli_runtime, caplog): + cli_runtime.diff.unchanged_alerts = [_existing_blocker()] + + cli_runtime.run(["--strict-blocking"]) + + assert STRICT_COMPARISON_LOG in caplog.text + + +def test_skipped_pull_request_event_logs_no_comparison( + cli_runtime, monkeypatch, caplog +): + monkeypatch.setenv("GH_API_TOKEN", "test") + monkeypatch.setenv("GITHUB_EVENT_NAME", "pull_request") + monkeypatch.setenv("EVENT_ACTION", "closed") + monkeypatch.setenv("GITHUB_REPOSITORY", "acme/repo") + monkeypatch.setenv("PR_NUMBER", "7") + + assert cli_runtime.run(["--scm", "github", "--strict-blocking"]) == 0 + cli_runtime.compare.assert_not_called() + cli_runtime.full_scan.assert_not_called() + assert STRICT_COMPARISON_LOG not in caplog.text + + +@pytest.fixture +def gitlab_pipeline(cli_runtime, monkeypatch): + monkeypatch.setenv("GITLAB_TOKEN", "glpat-test") + monkeypatch.setenv("CI_PROJECT_NAME", "repo") + monkeypatch.setenv("CI_DEFAULT_BRANCH", "main") + monkeypatch.setenv("CI_API_V4_URL", "https://gitlab.example.com/api/v4") + monkeypatch.setenv("CI_PROJECT_URL", "https://gitlab.example.com/acme/repo") + monkeypatch.setattr(Gitlab, "get_comments_for_pr", Mock(return_value={})) + add_comments = Mock() + monkeypatch.setattr(Gitlab, "add_socket_comments", add_comments) + return add_comments + + +def test_code_only_merge_request_comments_on_existing_blockers( + cli_runtime, gitlab_pipeline, monkeypatch +): + monkeypatch.setenv("CI_PIPELINE_SOURCE", "merge_request_event") + monkeypatch.setenv("CI_MERGE_REQUEST_IID", "7") + monkeypatch.setenv("CI_MERGE_REQUEST_PROJECT_ID", "42") + monkeypatch.setenv("CI_MERGE_REQUEST_SOURCE_BRANCH_NAME", "feature") + cli_runtime.diff.unchanged_alerts = [_existing_blocker()] + + assert cli_runtime.run(["--scm", "gitlab", "--strict-blocking"]) == 1 + cli_runtime.compare.assert_called_once() + cli_runtime.full_scan.assert_not_called() + gitlab_pipeline.assert_called_once() + security_comment, _, _, post_security, _ = gitlab_pipeline.call_args.args + assert post_security is True + assert "handlebars@4.0.11" in security_comment + assert "Existing alerts" in security_comment + + +def test_gitlab_branch_pipeline_still_creates_a_full_scan( + cli_runtime, gitlab_pipeline, monkeypatch, caplog +): + monkeypatch.setenv("CI_PIPELINE_SOURCE", "push") + cli_runtime.full_scan.return_value = Diff( + id="full", report_url="", diff_url="", new_alerts=[_existing_blocker()] + ) + + assert cli_runtime.run(["--scm", "gitlab", "--strict-blocking"]) == 0 + cli_runtime.full_scan.assert_called_once() + cli_runtime.compare.assert_not_called() + gitlab_pipeline.assert_not_called() + assert STRICT_COMPARISON_LOG not in caplog.text