From 988cda1ec452ea8ce615350e492b352cdeefe350 Mon Sep 17 00:00:00 2001 From: David Larsen Date: Fri, 20 Nov 2026 15:00:28 -0500 Subject: [PATCH 1/6] Scan reopened pull requests instead of passing them unscanned With --scm github, a pull_request run whose action was not opened or synchronize logged "Pull Request Action reopened is not a supported type" and exited 0 without scanning. The example workflow subscribes to reopened, and a required check takes the latest run on the head commit, so reopening a pull request could replace a failed Socket check with a pass on the same commit. reopened and ready_for_review now run the same comparison as opened and synchronize. Other actions and unhandled events are still skipped with exit 0, as the exit-code contract documents, but log a warning that no scan ran. pull_request_target gets its own message because it runs against the base branch, so it is not treated as pull_request. GitLab's unhandled pipeline sources log the same warning. --- CHANGELOG.md | 12 +++ docs/ci-cd.md | 19 +++- pyproject.toml | 2 +- socketsecurity/__init__.py | 2 +- socketsecurity/core/scm/github.py | 41 ++++++-- socketsecurity/core/scm/gitlab.py | 7 +- tests/core/test_cli_exit_contract.py | 12 ++- tests/unit/test_github_event_filter.py | 132 +++++++++++++++++++++++++ uv.lock | 2 +- workflows/github-actions.yml | 3 + 10 files changed, 217 insertions(+), 15 deletions(-) create mode 100644 tests/unit/test_github_event_filter.py diff --git a/CHANGELOG.md b/CHANGELOG.md index ff28e721..ed4f8d81 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +## 2.13.1 + +### Fixed + +- With `--scm github`, `pull_request` runs with the `reopened` or + `ready_for_review` action now scan the pull request. They exited `0` without + scanning, so a reopened pull request could pass a required check on a commit an + earlier run failed. +- Skipped GitHub events and actions, and skipped GitLab pipeline sources, log a + warning that no scan ran. `pull_request_target` gets its own message. Exit codes + are unchanged. + ## 2.13.0 ### Upgrade notes diff --git a/docs/ci-cd.md b/docs/ci-cd.md index 88210ed1..4e19b40b 100644 --- a/docs/ci-cd.md +++ b/docs/ci-cd.md @@ -84,8 +84,9 @@ they also hide findings and usage errors. Even with exit `0`, a setup/API failur does not mean a clean scan; check the logs for a completed report. Findings block only when a [diff comparison runs](#scan-type-by-pipeline). -SCM event filters can also skip unsupported events with exit `0`; confirm a report -was created when validating a new workflow. +SCM event filters can also skip unsupported events with exit `0` and a warning +(see [Skipped events](#skipped-events)); confirm a report was created when +validating a new workflow. `--strict-blocking` also checks existing blocking alerts; an incomplete comparison or incomplete existing-alert data is an infrastructure failure. See the [2.13.0 migration table](../README.md#upgrading-to-2130) when updating existing CI rules. @@ -512,6 +513,20 @@ 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. +### Skipped events + +With `--scm github`, `pull_request` runs scan on the `opened`, `synchronize`, +`reopened` and `ready_for_review` actions. Other actions (`closed`, `labeled`, +`edited`, ...) and events the CLI does not handle (`pull_request_target`, +`merge_group`, `schedule`, ...) are skipped: no scan runs, the CLI logs a warning +and exits `0`. With `--scm gitlab`, pipeline sources other than `web`, +`merge_request_event`, `push`, `api`, `pipeline` and the comment flow are skipped +the same way. + +A required check takes the latest run on the head commit, so a skipped run that +passes can replace an earlier failure. Subscribe the Socket job only to events and +actions the CLI scans. + 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 diff --git a/pyproject.toml b/pyproject.toml index 0924672a..2ba92fb3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ build-backend = "hatchling.build" [project] name = "socketsecurity" -version = "2.13.0" +version = "2.13.1" requires-python = ">= 3.11" license = {"file" = "LICENSE"} dependencies = [ diff --git a/socketsecurity/__init__.py b/socketsecurity/__init__.py index 08835ec8..a3c8f69d 100644 --- a/socketsecurity/__init__.py +++ b/socketsecurity/__init__.py @@ -1,4 +1,4 @@ __author__ = 'socket.dev' -__version__ = '2.13.0' +__version__ = '2.13.1' USER_AGENT_NAME = 'socket-python-cli' USER_AGENT = f'{USER_AGENT_NAME}/{__version__}' diff --git a/socketsecurity/core/scm/github.py b/socketsecurity/core/scm/github.py index 5248fc87..9b9476a4 100644 --- a/socketsecurity/core/scm/github.py +++ b/socketsecurity/core/scm/github.py @@ -14,6 +14,13 @@ from socketsecurity.exit_codes import InfrastructureError from socketsecurity.socketcli import CliClient +# pull_request actions that can leave a PR head without a current Socket result: +# new commits (opened, synchronize) and a PR coming back after it was closed or +# drafted (reopened, ready_for_review). A required check takes the latest run on the +# head commit, so a skipped run that exits 0 on one of these would replace an earlier +# failure. Other actions (closed, labeled, edited, ...) are skipped with a warning. +PULL_REQUEST_SCAN_ACTIONS = ("opened", "synchronize", "reopened", "ready_for_review") + @dataclass class GithubConfig: @@ -175,19 +182,41 @@ def __init__( raise InfrastructureError("Unable to get Github API Token") def check_event_type(self) -> str: - if self.config.event_name.lower() in ["push", "workflow_dispatch"]: + event_name = self.config.event_name.lower() + if event_name in ["push", "workflow_dispatch"]: if not self.config.pr_number: return "main" return "diff" - elif self.config.event_name.lower() == "pull_request": - if self.config.event_action and self.config.event_action.lower() in ['opened', 'synchronize']: + elif event_name == "pull_request": + action = (self.config.event_action or "").lower() + if action in PULL_REQUEST_SCAN_ACTIONS: return "diff" - log.info(f"Pull Request Action {self.config.event_action} is not a supported type") + log.warning( + f"Pull request action '{self.config.event_action}' is not scanned " + f"(scanned actions: {', '.join(PULL_REQUEST_SCAN_ACTIONS)}). No scan ran; " + "exiting 0. If this job is a required check, its success here does not " + "reflect a scan: remove this action from the workflow's pull_request types." + ) sys.exit(0) - elif self.config.event_name.lower() == "issue_comment": + elif event_name == "issue_comment": return "comment" + elif event_name == "pull_request_target": + # Not treated as pull_request on purpose: GITHUB_SHA and GITHUB_REF point at + # the base branch and the default checkout is the base branch, so a "PR scan" + # here would compare the base against itself and pass. + log.warning( + "GitHub event 'pull_request_target' is not scanned: it runs against the " + "base branch, not the pull request head. No scan ran; exiting 0. Trigger " + "the Socket job on pull_request instead." + ) + sys.exit(0) - log.error(f"Unknown event type {self.config.event_name}") + log.warning( + f"GitHub event '{self.config.event_name}' is not scanned (scanned events: " + "push, workflow_dispatch, pull_request, issue_comment). No scan ran; " + "exiting 0. If this job is a required check, its success here does not " + "reflect a scan." + ) sys.exit(0) def post_comment(self, body: str) -> None: diff --git a/socketsecurity/core/scm/gitlab.py b/socketsecurity/core/scm/gitlab.py index a7b2bd3a..d49ad1ea 100644 --- a/socketsecurity/core/scm/gitlab.py +++ b/socketsecurity/core/scm/gitlab.py @@ -214,7 +214,12 @@ def check_event_type(self) -> str: elif pipeline_source == "issue_comment": return "comment" else: - log.error(f"Unknown event type {pipeline_source}") + log.warning( + f"GitLab pipeline source '{self.config.pipeline_source}' is not scanned " + "(scanned sources: web, merge_request_event, push, api, pipeline, " + "issue_comment). No scan ran; exiting 0. If this job gates merges, its " + "success here does not reflect a scan." + ) sys.exit(0) def post_comment(self, body: str) -> None: diff --git a/tests/core/test_cli_exit_contract.py b/tests/core/test_cli_exit_contract.py index d3988f91..74c4ceef 100644 --- a/tests/core/test_cli_exit_contract.py +++ b/tests/core/test_cli_exit_contract.py @@ -275,14 +275,20 @@ def test_branch_full_scan_does_not_gate_on_findings(cli_runtime, monkeypatch, ou @pytest.mark.parametrize("scm, event, action", [ ("github", "pull_request", "closed"), ("github", "unsupported", ""), - ("gitlab", "unsupported", ""), + ("github", "pull_request_target", "opened"), ("gitlab", "unsupported", ""), ]) -def test_scm_event_filters_skip_without_scanning(cli_runtime, monkeypatch, scm, event, action): +def test_scm_event_filters_skip_without_scanning(cli_runtime, monkeypatch, caplog, scm, event, action): monkeypatch.setenv("GH_API_TOKEN", "test") monkeypatch.setenv("GITLAB_TOKEN", "test") monkeypatch.setenv("GITHUB_EVENT_NAME", event) monkeypatch.setenv("EVENT_ACTION", action) monkeypatch.setenv("CI_PIPELINE_SOURCE", event) - assert cli_runtime.run(["--scm", scm]) == 0 + with caplog.at_level("INFO", logger="socketdev"): + assert cli_runtime.run(["--scm", scm]) == 0 cli_runtime.scan.assert_not_called() + # A skipped run passes, so it has to say so where a required-check owner looks. + assert any( + record.levelname == "WARNING" and "No scan ran" in record.getMessage() + for record in caplog.records + ) diff --git a/tests/unit/test_github_event_filter.py b/tests/unit/test_github_event_filter.py new file mode 100644 index 00000000..54790ff2 --- /dev/null +++ b/tests/unit/test_github_event_filter.py @@ -0,0 +1,132 @@ +"""Which GitHub events and pull_request actions run a scan. + +A skipped run exits 0, and a required check takes the latest run on the head +commit, so skipping an action that a workflow subscribes to can replace an +earlier failure with a pass that never scanned anything. +""" + +import logging +import sys +from contextlib import nullcontext +from unittest.mock import MagicMock, Mock + +import pytest + +from socketsecurity import socketcli +from socketsecurity.core.classes import Diff, Issue +from socketsecurity.core.scm.github import ( + PULL_REQUEST_SCAN_ACTIONS, + Github, + GithubConfig, +) +from socketsecurity.core.scm_comments import Comments + +CONTEXT_VARIABLES = ( + "BUILDKITE", "BUILDKITE_PULL_REQUEST", "DEFAULT_BRANCH", "EVENT_ACTION", + "GITHUB_EVENT_NAME", "GITHUB_EVENT_PATH", "GITHUB_REPOSITORY", "PR_NUMBER", + "SOCKET_SECURITY_API_KEY", "SOCKET_SECURITY_API_TOKEN", "SOCKET_API_KEY", "SOCKET_API_TOKEN", +) + + +@pytest.fixture(autouse=True) +def clear_context(monkeypatch): + for variable in CONTEXT_VARIABLES: + monkeypatch.delenv(variable, raising=False) + monkeypatch.setenv("GH_API_TOKEN", "test-token") + monkeypatch.setenv("GITHUB_REPOSITORY", "acme/repo") + + +def _github(monkeypatch, event_name, action=None): + monkeypatch.setenv("GITHUB_EVENT_NAME", event_name) + if action is not None: + monkeypatch.setenv("EVENT_ACTION", action) + return Github(client=object(), config=GithubConfig.from_env(pr_number="7")) + + +@pytest.mark.parametrize("action", ["opened", "synchronize", "reopened", "ready_for_review", "Reopened"]) +def test_pull_request_actions_that_change_the_head_result_are_scanned(monkeypatch, action): + assert _github(monkeypatch, "pull_request", action).check_event_type() == "diff" + + +def test_scanned_actions_are_the_documented_set(): + assert PULL_REQUEST_SCAN_ACTIONS == ("opened", "synchronize", "reopened", "ready_for_review") + + +@pytest.mark.parametrize("action", ["closed", "labeled", "edited", None]) +def test_other_pull_request_actions_skip_with_a_warning(monkeypatch, caplog, action): + github = _github(monkeypatch, "pull_request", action) + + with caplog.at_level(logging.INFO, logger="socketdev"), pytest.raises(SystemExit) as result: + github.check_event_type() + + assert result.value.code == 0 + warning = next(r for r in caplog.records if r.levelno == logging.WARNING) + assert f"'{action}' is not scanned" in warning.getMessage() + assert "No scan ran" in warning.getMessage() + + +@pytest.mark.parametrize("event_name, expected", [ + ("pull_request_target", "runs against the base branch"), + ("merge_group", "'merge_group' is not scanned"), + ("schedule", "'schedule' is not scanned"), +]) +def test_unscanned_events_skip_with_a_warning(monkeypatch, caplog, event_name, expected): + github = _github(monkeypatch, event_name, "opened") + + with caplog.at_level(logging.INFO, logger="socketdev"), pytest.raises(SystemExit) as result: + github.check_event_type() + + assert result.value.code == 0 + warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING] + assert any(expected in message and "No scan ran" in message for message in warnings) + + +def _blocking_alert() -> Issue: + return Issue( + pkg_name="lodash", pkg_version="4.17.11", pkg_type="npm", severity="critical", + title="Critical CVE", description="", type="criticalCVE", url="https://socket.dev/test", + manifests="package.json", props={}, key="key", purl="pkg:npm/lodash@4.17.11", + error=True, warn=False, ignore=False, monitor=False, + ) + + +@pytest.mark.parametrize("action, scanned, expected_exit", [ + ("reopened", True, 1), + ("ready_for_review", True, 1), + ("synchronize", True, 1), + ("closed", False, 0), +]) +def test_reopened_pull_request_blocks_like_synchronize(monkeypatch, action, scanned, expected_exit): + """A reopened PR with an existing blocker fails instead of passing unscanned.""" + monkeypatch.setattr(sys, "argv", [ + "socketcli", "--api-token", "test", "--scm", "github", "--strict-blocking", + "--repo", "repo", "--branch", "feature", "--pr-number", "7", + "--files", '["package.json"]', + ]) + monkeypatch.setenv("GITHUB_EVENT_NAME", "pull_request") + monkeypatch.setenv("EVENT_ACTION", action) + monkeypatch.setenv("DEFAULT_BRANCH", "false") + + diff = Diff(id="scan", new_alerts=[], unchanged_alerts=[_blocking_alert()]) + diff.diff_url = "https://socket.dev/diff" + monkeypatch.setattr(Github, "get_comments_for_pr", lambda self: Comments.check_for_socket_comments({})) + posted = Mock() + monkeypatch.setattr(Github, "add_socket_comments", posted) + monkeypatch.setattr(Github, "handle_ignore_reactions", Mock()) + sdk = MagicMock() + sdk.org.get.return_value = {"organizations": {"org-id": {"slug": "acme"}}} + monkeypatch.setattr(socketcli, "build_socket_sdk", Mock(return_value=sdk)) + monkeypatch.setattr(socketcli, "CliClient", Mock(return_value=Mock())) + monkeypatch.setattr(socketcli, "StreamingLogs", lambda **kwargs: nullcontext(Mock())) + monkeypatch.setattr(socketcli, "apply_git_context", lambda config: (False, None)) + scan = Mock(return_value=diff) + monkeypatch.setattr(socketcli.Core, "create_new_diff", scan) + monkeypatch.setattr(socketcli.Core, "has_manifest_files", Mock(return_value=True)) + monkeypatch.setattr(socketcli.OutputHandler, "handle_output", Mock()) + + with pytest.raises(SystemExit) as result: + socketcli.cli() + + assert result.value.code == expected_exit + assert scan.called is scanned + assert posted.called is scanned diff --git a/uv.lock b/uv.lock index a6271a3d..aea1ca6b 100644 --- a/uv.lock +++ b/uv.lock @@ -1334,7 +1334,7 @@ wheels = [ [[package]] name = "socketsecurity" -version = "2.13.0" +version = "2.13.1" source = { editable = "." } dependencies = [ { name = "beautifulsoup4" }, diff --git a/workflows/github-actions.yml b/workflows/github-actions.yml index 422eb253..577ad24c 100644 --- a/workflows/github-actions.yml +++ b/workflows/github-actions.yml @@ -9,6 +9,9 @@ on: push: branches: ['**'] # Run on all branches, all commits pull_request: + # Every listed action runs a scan. Don't add actions the CLI skips (closed, + # labeled, edited, ...): a skipped run exits 0, and on a required check it can + # replace an earlier failure on the same commit. types: [opened, synchronize, reopened] issue_comment: types: [created] From 8aa89ea5bea8c3305807da1a871b6962f584ba84 Mon Sep 17 00:00:00 2001 From: David Larsen Date: Fri, 20 Nov 2026 17:05:19 -0500 Subject: [PATCH 2/6] Say when the event or action is missing, and that issue_comment doesn't scan A missing pull_request action or GITHUB_EVENT_NAME (or CI_PIPELINE_SOURCE on GitLab) now gets its own warning instead of "action 'None' is not scanned", whose advice to drop the action from the workflow didn't apply. The skip warnings list issue_comment as handling ignore commands, not as a scanned event. Tests pin push, workflow_dispatch and issue_comment routing. --- socketsecurity/core/scm/github.py | 33 +++- socketsecurity/core/scm/gitlab.py | 13 +- tests/unit/test_github_event_filter.py | 225 +++++++++++++++++++------ 3 files changed, 212 insertions(+), 59 deletions(-) diff --git a/socketsecurity/core/scm/github.py b/socketsecurity/core/scm/github.py index 9b9476a4..7e0f06d2 100644 --- a/socketsecurity/core/scm/github.py +++ b/socketsecurity/core/scm/github.py @@ -16,10 +16,15 @@ # pull_request actions that can leave a PR head without a current Socket result: # new commits (opened, synchronize) and a PR coming back after it was closed or -# drafted (reopened, ready_for_review). A required check takes the latest run on the -# head commit, so a skipped run that exits 0 on one of these would replace an earlier -# failure. Other actions (closed, labeled, edited, ...) are skipped with a warning. +# drafted (reopened, ready_for_review). A skipped run exits 0, and GitHub doesn't +# define which run a required check uses when the same job runs more than once on a +# commit, so a skipped run on one of these could satisfy the check in place of an +# earlier failure. Other actions (closed, labeled, edited, ...) are skipped with a +# warning. PULL_REQUEST_SCAN_ACTIONS = ("opened", "synchronize", "reopened", "ready_for_review") +HANDLED_EVENTS = ( + "push, workflow_dispatch and pull_request (scan); issue_comment (ignore commands)" +) @dataclass @@ -191,6 +196,14 @@ def check_event_type(self) -> str: action = (self.config.event_action or "").lower() if action in PULL_REQUEST_SCAN_ACTIONS: return "diff" + if not action: + log.warning( + "Could not determine the pull_request action: EVENT_ACTION is not set " + "and GITHUB_EVENT_PATH has no 'action'. No scan ran; exiting 0. Set " + "EVENT_ACTION (or GITHUB_EVENT_PATH) when running with --scm github " + "outside GitHub Actions." + ) + sys.exit(0) log.warning( f"Pull request action '{self.config.event_action}' is not scanned " f"(scanned actions: {', '.join(PULL_REQUEST_SCAN_ACTIONS)}). No scan ran; " @@ -211,11 +224,17 @@ def check_event_type(self) -> str: ) sys.exit(0) + if not event_name: + log.warning( + "Could not determine the GitHub event: GITHUB_EVENT_NAME is not set. " + "No scan ran; exiting 0. Set GITHUB_EVENT_NAME when running with " + "--scm github outside GitHub Actions." + ) + sys.exit(0) log.warning( - f"GitHub event '{self.config.event_name}' is not scanned (scanned events: " - "push, workflow_dispatch, pull_request, issue_comment). No scan ran; " - "exiting 0. If this job is a required check, its success here does not " - "reflect a scan." + f"GitHub event '{self.config.event_name}' is not scanned (handled events: " + f"{HANDLED_EVENTS}). No scan ran; exiting 0. If this job is a required " + "check, its success here does not reflect a scan." ) sys.exit(0) diff --git a/socketsecurity/core/scm/gitlab.py b/socketsecurity/core/scm/gitlab.py index d49ad1ea..4c9cdbf6 100644 --- a/socketsecurity/core/scm/gitlab.py +++ b/socketsecurity/core/scm/gitlab.py @@ -213,12 +213,19 @@ def check_event_type(self) -> str: return "diff" elif pipeline_source == "issue_comment": return "comment" + elif not pipeline_source: + log.warning( + "Could not determine the GitLab pipeline source: CI_PIPELINE_SOURCE is " + "not set. No scan ran; exiting 0. Set CI_PIPELINE_SOURCE when running " + "with --scm gitlab outside GitLab CI." + ) + sys.exit(0) else: log.warning( f"GitLab pipeline source '{self.config.pipeline_source}' is not scanned " - "(scanned sources: web, merge_request_event, push, api, pipeline, " - "issue_comment). No scan ran; exiting 0. If this job gates merges, its " - "success here does not reflect a scan." + "(handled sources: web, merge_request_event, push, api and pipeline " + "(scan); issue_comment (ignore commands)). No scan ran; exiting 0. If " + "this job gates merges, its success here does not reflect a scan." ) sys.exit(0) diff --git a/tests/unit/test_github_event_filter.py b/tests/unit/test_github_event_filter.py index 54790ff2..5973673c 100644 --- a/tests/unit/test_github_event_filter.py +++ b/tests/unit/test_github_event_filter.py @@ -1,8 +1,9 @@ """Which GitHub events and pull_request actions run a scan. -A skipped run exits 0, and a required check takes the latest run on the head -commit, so skipping an action that a workflow subscribes to can replace an -earlier failure with a pass that never scanned anything. +A skipped run exits 0, and GitHub doesn't define which run a required check uses +when the same job runs more than once on a commit, so skipping an action that a +workflow subscribes to can satisfy the check with a pass that never scanned +anything. """ import logging @@ -19,12 +20,24 @@ Github, GithubConfig, ) +from socketsecurity.core.scm.gitlab import Gitlab, GitlabConfig from socketsecurity.core.scm_comments import Comments CONTEXT_VARIABLES = ( - "BUILDKITE", "BUILDKITE_PULL_REQUEST", "DEFAULT_BRANCH", "EVENT_ACTION", - "GITHUB_EVENT_NAME", "GITHUB_EVENT_PATH", "GITHUB_REPOSITORY", "PR_NUMBER", - "SOCKET_SECURITY_API_KEY", "SOCKET_SECURITY_API_TOKEN", "SOCKET_API_KEY", "SOCKET_API_TOKEN", + "BUILDKITE", + "BUILDKITE_PULL_REQUEST", + "DEFAULT_BRANCH", + "EVENT_ACTION", + "CI_MERGE_REQUEST_IID", + "CI_PIPELINE_SOURCE", + "GITHUB_EVENT_NAME", + "GITHUB_EVENT_PATH", + "GITHUB_REPOSITORY", + "PR_NUMBER", + "SOCKET_SECURITY_API_KEY", + "SOCKET_SECURITY_API_TOKEN", + "SOCKET_API_KEY", + "SOCKET_API_TOKEN", ) @@ -36,80 +49,192 @@ def clear_context(monkeypatch): monkeypatch.setenv("GITHUB_REPOSITORY", "acme/repo") -def _github(monkeypatch, event_name, action=None): - monkeypatch.setenv("GITHUB_EVENT_NAME", event_name) +def _github(monkeypatch, event_name, action=None, pr_number="7"): + if event_name is not None: + monkeypatch.setenv("GITHUB_EVENT_NAME", event_name) if action is not None: monkeypatch.setenv("EVENT_ACTION", action) - return Github(client=object(), config=GithubConfig.from_env(pr_number="7")) + return Github(client=object(), config=GithubConfig.from_env(pr_number=pr_number)) -@pytest.mark.parametrize("action", ["opened", "synchronize", "reopened", "ready_for_review", "Reopened"]) -def test_pull_request_actions_that_change_the_head_result_are_scanned(monkeypatch, action): +def _skip_warnings(scm, caplog) -> list[str]: + with ( + caplog.at_level(logging.INFO, logger="socketdev"), + pytest.raises(SystemExit) as result, + ): + scm.check_event_type() + assert result.value.code == 0 + return [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING] + + +@pytest.mark.parametrize( + "action", ["opened", "synchronize", "reopened", "ready_for_review", "Reopened"] +) +def test_pull_request_actions_that_change_the_head_result_are_scanned( + monkeypatch, action +): assert _github(monkeypatch, "pull_request", action).check_event_type() == "diff" def test_scanned_actions_are_the_documented_set(): - assert PULL_REQUEST_SCAN_ACTIONS == ("opened", "synchronize", "reopened", "ready_for_review") + assert PULL_REQUEST_SCAN_ACTIONS == ( + "opened", + "synchronize", + "reopened", + "ready_for_review", + ) + + +@pytest.mark.parametrize( + "event_name, pr_number, expected", + [ + ("push", None, "main"), + ("push", "7", "diff"), + ("workflow_dispatch", None, "main"), + ("workflow_dispatch", "7", "diff"), + ("issue_comment", "7", "comment"), + ], +) +def test_other_handled_events_are_unchanged( + monkeypatch, event_name, pr_number, expected +): + github = _github(monkeypatch, event_name, pr_number=pr_number) + assert github.check_event_type() == expected -@pytest.mark.parametrize("action", ["closed", "labeled", "edited", None]) +@pytest.mark.parametrize("action", ["closed", "labeled", "edited"]) def test_other_pull_request_actions_skip_with_a_warning(monkeypatch, caplog, action): - github = _github(monkeypatch, "pull_request", action) + warnings = _skip_warnings(_github(monkeypatch, "pull_request", action), caplog) - with caplog.at_level(logging.INFO, logger="socketdev"), pytest.raises(SystemExit) as result: - github.check_event_type() + assert any( + f"'{action}' is not scanned" in m and "No scan ran" in m for m in warnings + ) - assert result.value.code == 0 - warning = next(r for r in caplog.records if r.levelno == logging.WARNING) - assert f"'{action}' is not scanned" in warning.getMessage() - assert "No scan ran" in warning.getMessage() +def test_missing_pull_request_action_says_it_could_not_be_determined( + monkeypatch, caplog +): + warnings = _skip_warnings(_github(monkeypatch, "pull_request"), caplog) -@pytest.mark.parametrize("event_name, expected", [ - ("pull_request_target", "runs against the base branch"), - ("merge_group", "'merge_group' is not scanned"), - ("schedule", "'schedule' is not scanned"), -]) -def test_unscanned_events_skip_with_a_warning(monkeypatch, caplog, event_name, expected): - github = _github(monkeypatch, event_name, "opened") + assert any( + "Could not determine the pull_request action" in m and "No scan ran" in m + for m in warnings + ) + assert not any("is not scanned" in m for m in warnings) - with caplog.at_level(logging.INFO, logger="socketdev"), pytest.raises(SystemExit) as result: - github.check_event_type() - assert result.value.code == 0 - warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING] +def test_missing_event_name_says_it_could_not_be_determined(monkeypatch, caplog): + warnings = _skip_warnings(_github(monkeypatch, None), caplog) + + assert any( + "GITHUB_EVENT_NAME is not set" in m and "No scan ran" in m for m in warnings + ) + + +@pytest.mark.parametrize( + "event_name, expected", + [ + ("pull_request_target", "runs against the base branch"), + ("merge_group", "'merge_group' is not scanned"), + ("schedule", "'schedule' is not scanned"), + ], +) +def test_unscanned_events_skip_with_a_warning( + monkeypatch, caplog, event_name, expected +): + warnings = _skip_warnings(_github(monkeypatch, event_name, "opened"), caplog) + + assert any(expected in message and "No scan ran" in message for message in warnings) + # issue_comment is handled, but it runs the ignore-command flow, not a scan. + if event_name != "pull_request_target": + assert any("issue_comment (ignore commands)" in message for message in warnings) + + +def _gitlab(monkeypatch, pipeline_source): + monkeypatch.setenv("GITLAB_TOKEN", "test-token") + if pipeline_source is not None: + monkeypatch.setenv("CI_PIPELINE_SOURCE", pipeline_source) + return Gitlab(client=object(), config=GitlabConfig.from_env()) + + +@pytest.mark.parametrize( + "pipeline_source, expected", + [ + ("schedule", "'schedule' is not scanned"), + (None, "CI_PIPELINE_SOURCE is not set"), + ], +) +def test_gitlab_skipped_sources_warn(monkeypatch, caplog, pipeline_source, expected): + warnings = _skip_warnings(_gitlab(monkeypatch, pipeline_source), caplog) + assert any(expected in message and "No scan ran" in message for message in warnings) def _blocking_alert() -> Issue: return Issue( - pkg_name="lodash", pkg_version="4.17.11", pkg_type="npm", severity="critical", - title="Critical CVE", description="", type="criticalCVE", url="https://socket.dev/test", - manifests="package.json", props={}, key="key", purl="pkg:npm/lodash@4.17.11", - error=True, warn=False, ignore=False, monitor=False, + pkg_name="lodash", + pkg_version="4.17.11", + pkg_type="npm", + severity="critical", + title="Critical CVE", + description="", + type="criticalCVE", + url="https://socket.dev/test", + manifests="package.json", + props={}, + key="key", + purl="pkg:npm/lodash@4.17.11", + error=True, + warn=False, + ignore=False, + monitor=False, ) -@pytest.mark.parametrize("action, scanned, expected_exit", [ - ("reopened", True, 1), - ("ready_for_review", True, 1), - ("synchronize", True, 1), - ("closed", False, 0), -]) -def test_reopened_pull_request_blocks_like_synchronize(monkeypatch, action, scanned, expected_exit): +@pytest.mark.parametrize( + "action, scanned, expected_exit", + [ + ("reopened", True, 1), + ("ready_for_review", True, 1), + ("synchronize", True, 1), + ("closed", False, 0), + ], +) +def test_reopened_pull_request_blocks_like_synchronize( + monkeypatch, action, scanned, expected_exit +): """A reopened PR with an existing blocker fails instead of passing unscanned.""" - monkeypatch.setattr(sys, "argv", [ - "socketcli", "--api-token", "test", "--scm", "github", "--strict-blocking", - "--repo", "repo", "--branch", "feature", "--pr-number", "7", - "--files", '["package.json"]', - ]) + monkeypatch.setattr( + sys, + "argv", + [ + "socketcli", + "--api-token", + "test", + "--scm", + "github", + "--strict-blocking", + "--repo", + "repo", + "--branch", + "feature", + "--pr-number", + "7", + "--files", + '["package.json"]', + ], + ) monkeypatch.setenv("GITHUB_EVENT_NAME", "pull_request") monkeypatch.setenv("EVENT_ACTION", action) monkeypatch.setenv("DEFAULT_BRANCH", "false") diff = Diff(id="scan", new_alerts=[], unchanged_alerts=[_blocking_alert()]) diff.diff_url = "https://socket.dev/diff" - monkeypatch.setattr(Github, "get_comments_for_pr", lambda self: Comments.check_for_socket_comments({})) + monkeypatch.setattr( + Github, + "get_comments_for_pr", + lambda self: Comments.check_for_socket_comments({}), + ) posted = Mock() monkeypatch.setattr(Github, "add_socket_comments", posted) monkeypatch.setattr(Github, "handle_ignore_reactions", Mock()) @@ -117,7 +242,9 @@ def test_reopened_pull_request_blocks_like_synchronize(monkeypatch, action, scan sdk.org.get.return_value = {"organizations": {"org-id": {"slug": "acme"}}} monkeypatch.setattr(socketcli, "build_socket_sdk", Mock(return_value=sdk)) monkeypatch.setattr(socketcli, "CliClient", Mock(return_value=Mock())) - monkeypatch.setattr(socketcli, "StreamingLogs", lambda **kwargs: nullcontext(Mock())) + monkeypatch.setattr( + socketcli, "StreamingLogs", lambda **kwargs: nullcontext(Mock()) + ) monkeypatch.setattr(socketcli, "apply_git_context", lambda config: (False, None)) scan = Mock(return_value=diff) monkeypatch.setattr(socketcli.Core, "create_new_diff", scan) From e899af896e232acd2e49e570071ed1eb32baf717 Mon Sep 17 00:00:00 2001 From: David Larsen Date: Fri, 20 Nov 2026 17:05:19 -0500 Subject: [PATCH 3/6] Document the push/pull_request overlap in the example workflow Move the Skipped events section below the scan-type paragraphs it had split. State the required-check risk without claiming which run GitHub picks. Explain that push on every branch also runs the job on a pull request's head commit as a full scan that exits 0, and give two ways to keep that run from satisfying a required check. --- CHANGELOG.md | 8 ++++-- docs/ci-cd.md | 52 +++++++++++++++++++++++++++--------- workflows/github-actions.yml | 8 ++++-- 3 files changed, 52 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ed4f8d81..1d479ae2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,8 +9,12 @@ scanning, so a reopened pull request could pass a required check on a commit an earlier run failed. - Skipped GitHub events and actions, and skipped GitLab pipeline sources, log a - warning that no scan ran. `pull_request_target` gets its own message. Exit codes - are unchanged. + warning that no scan ran. `pull_request_target` gets its own message, and a + missing event name or action says it could not be determined. Exit codes are + unchanged. +- `docs/ci-cd.md` explains that the example GitHub workflow's `push` trigger also + runs the job on a pull request's head commit as a full scan that exits `0`, and + how to keep that run from satisfying a required check. ## 2.13.0 diff --git a/docs/ci-cd.md b/docs/ci-cd.md index 4e19b40b..32025201 100644 --- a/docs/ci-cd.md +++ b/docs/ci-cd.md @@ -513,27 +513,55 @@ 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. + +`--generate-license` and `--legal-format fossa` work on both paths; a full scan +fetches the package list for them. + ### Skipped events With `--scm github`, `pull_request` runs scan on the `opened`, `synchronize`, `reopened` and `ready_for_review` actions. Other actions (`closed`, `labeled`, `edited`, ...) and events the CLI does not handle (`pull_request_target`, `merge_group`, `schedule`, ...) are skipped: no scan runs, the CLI logs a warning -and exits `0`. With `--scm gitlab`, pipeline sources other than `web`, -`merge_request_event`, `push`, `api`, `pipeline` and the comment flow are skipped -the same way. +and exits `0`. `issue_comment` runs the ignore-command flow, not a scan. With +`--scm gitlab`, pipeline sources other than `web`, `merge_request_event`, `push`, +`api`, `pipeline` and the comment flow are skipped the same way. -A required check takes the latest run on the head commit, so a skipped run that -passes can replace an earlier failure. Subscribe the Socket job only to events and +GitHub doesn't document which run a required check uses when a job with the same +name runs more than once on a commit, so a skipped run that passes can satisfy the +check in place of an earlier failure. Subscribe the Socket job only to events and actions the CLI scans. -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. - -`--generate-license` and `--legal-format fossa` work on both paths; a full scan -fetches the package list for them. +- `merge_group`: if the required check also runs on merge queue events, the job + passes there without scanning. The `pull_request` run is the gate. +- `pull_request_target` is skipped because it runs against the base branch, so it + can't stand in for `pull_request` on fork pull requests. Fork pull requests on + `pull_request` get no repository secrets, so the CLI has no API token and exits + `3` (or the `--exit-code-on-api-error` value). Decide how fork pull requests get + a token before making the check required. + +### Push and pull request runs on the same commit + +The [example workflow](../workflows/github-actions.yml) runs one `socket-security` +job on `push` to every branch and on `pull_request`. A new commit on a pull +request's branch triggers both events on the same head commit. The `pull_request` +run compares against the baseline and can fail. The `push` run is a full scan, +which never blocks and exits `0`. Both runs report a check with the same name, so +a required check can resolve against the passing `push` run. + +If the Socket job is a required check, do one of these: + +- Restrict `push` to the default branch (`branches: [main]`). Default-branch scans + still keep the baseline current; feature branches are scanned only through their + pull requests. +- Run the pull request scan in its own job (for example `socket-pr` with + `if: github.event_name == 'pull_request'`, and + `if: github.event_name != 'pull_request'` on the existing job), and require that + job's check. ## Pull request and Dashboard association diff --git a/workflows/github-actions.yml b/workflows/github-actions.yml index 577ad24c..ffd4c79d 100644 --- a/workflows/github-actions.yml +++ b/workflows/github-actions.yml @@ -7,11 +7,15 @@ run-name: Socket Security Github Action on: push: + # On a branch with an open pull request, this also runs the job on the PR head + # commit as a full scan, which exits 0. If this job is a required check, restrict + # push to the default branch or give the pull_request run its own job name. See + # "Push and pull request runs on the same commit" in docs/ci-cd.md. branches: ['**'] # Run on all branches, all commits pull_request: # Every listed action runs a scan. Don't add actions the CLI skips (closed, - # labeled, edited, ...): a skipped run exits 0, and on a required check it can - # replace an earlier failure on the same commit. + # labeled, edited, ...): a skipped run exits 0 and can satisfy a required check + # on a commit an earlier run failed. types: [opened, synchronize, reopened] issue_comment: types: [created] From 9b08674028d3f20a27f0e5be0325f8f90822014c Mon Sep 17 00:00:00 2001 From: David Larsen Date: Fri, 20 Nov 2026 18:08:17 -0500 Subject: [PATCH 4/6] Bump version to 2.13.3 2.13.2 was released from main, so this change needs the next patch version. --- pyproject.toml | 2 +- socketsecurity/__init__.py | 2 +- uv.lock | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 5c88c152..82c5bbf4 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 = [ 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/uv.lock b/uv.lock index 196ae3c8..b3681e40 100644 --- a/uv.lock +++ b/uv.lock @@ -1334,7 +1334,7 @@ wheels = [ [[package]] name = "socketsecurity" -version = "2.13.2" +version = "2.13.3" source = { editable = "." } dependencies = [ { name = "beautifulsoup4" }, From a5b1c93de2f1c40d332775517e8a86b4e2e393a8 Mon Sep 17 00:00:00 2001 From: lelia <2418071+lelia@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:51:57 -0500 Subject: [PATCH 5/6] Isolate the GitHub PR check and prepare CLI 2.14.0 --- CHANGELOG.md | 17 +++++- README.md | 2 +- docs/ci-cd.md | 80 +++++++++++++------------- pyproject.toml | 2 +- socketsecurity/__init__.py | 2 +- socketsecurity/core/scm/github.py | 23 ++++---- tests/core/test_cli_exit_contract.py | 1 - tests/unit/test_github_event_filter.py | 54 ++++++++++------- uv.lock | 2 +- workflows/github-actions-comments.yml | 36 ++++++++++++ workflows/github-actions-push.yml | 32 +++++++++++ workflows/github-actions.yml | 57 ++++-------------- 12 files changed, 181 insertions(+), 127 deletions(-) create mode 100644 workflows/github-actions-comments.yml create mode 100644 workflows/github-actions-push.yml diff --git a/CHANGELOG.md b/CHANGELOG.md index 1a06df0e..41721575 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,12 +1,22 @@ # Changelog -## 2.13.3 +## 2.14.0 + +### Upgrade notes + +- If you use the GitHub Actions example, replace the combined workflow with the + [PR workflow](workflows/github-actions.yml) and require its `socket-security` + check. Install the [push workflow](workflows/github-actions-push.yml) to keep + branch scans and baseline updates. Install the + [ignore-command workflow](workflows/github-actions-comments.yml) if you use PR + ignore commands. ### 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. +- Skipped GitHub events and GitLab pipeline sources now warn that no scan ran. ### Fixed @@ -18,6 +28,11 @@ - With `--scm github`, reopened pull requests and pull requests marked ready for review run the PR scan. +### Documentation + +- The [CI guide](docs/ci-cd.md#required-github-checks) describes GitHub required + checks and the GitHub Actions workflow migration. + ## 2.13.2 ### Added diff --git a/README.md b/README.md index aa22735c..70152cfc 100644 --- a/README.md +++ b/README.md @@ -205,7 +205,7 @@ JSON: Prebuilt workflow examples: -- [GitHub Actions](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/github-actions.yml) +- GitHub Actions for [pull requests](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/github-actions.yml), [pushes](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/github-actions-push.yml), and [ignore commands](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/github-actions-comments.yml) - [Buildkite](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/buildkite.yml) - [GitLab CI](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/gitlab-ci.yml) - [Bitbucket Pipelines](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/bitbucket-pipelines.yml) diff --git a/docs/ci-cd.md b/docs/ci-cd.md index b0e263b8..db1e0788 100644 --- a/docs/ci-cd.md +++ b/docs/ci-cd.md @@ -504,8 +504,8 @@ With `--scm github` or `--scm gitlab`, the detected event decides the scan type: | 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 | +| Supported pull request / merge request events | Diff scan against the repository's baseline when a comparison runs | Yes, on new blocking alerts and on existing blockers with `--strict-blocking` | +| Push without a PR/MR number, including default-branch pushes | Full scan | No blocking on findings | 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 @@ -525,43 +525,43 @@ fetches the package list for them. With `--scm github`, `pull_request` runs scan on the `opened`, `synchronize`, `reopened` and `ready_for_review` actions. Other actions (`closed`, `labeled`, -`edited`, ...) and events the CLI does not handle (`pull_request_target`, -`merge_group`, `schedule`, ...) are skipped: no scan runs, the CLI logs a warning -and exits `0`. `issue_comment` runs the ignore-command flow, not a scan. With -`--scm gitlab`, pipeline sources other than `web`, `merge_request_event`, `push`, -`api`, `pipeline` and the comment flow are skipped the same way. - -GitHub doesn't document which run a required check uses when a job with the same -name runs more than once on a commit, so a skipped run that passes can satisfy the -check in place of an earlier failure. Subscribe the Socket job only to events and -actions the CLI scans. - -- `merge_group`: if the required check also runs on merge queue events, the job - passes there without scanning. The `pull_request` run is the gate. -- `pull_request_target` is skipped because it runs against the base branch, so it - can't stand in for `pull_request` on fork pull requests. Fork pull requests on - `pull_request` get no repository secrets, so the CLI has no API token and exits - `3` (or the `--exit-code-on-api-error` value). Decide how fork pull requests get - a token before making the check required. - -### Push and pull request runs on the same commit - -The [example workflow](../workflows/github-actions.yml) runs one `socket-security` -job on `push` to every branch and on `pull_request`. A new commit on a pull -request's branch triggers both events on the same head commit. The `pull_request` -run compares against the baseline and can fail. The `push` run is a full scan, -which never blocks and exits `0`. Both runs report a check with the same name, so -a required check can resolve against the passing `push` run. - -If the Socket job is a required check, do one of these: - -- Restrict `push` to the default branch (`branches: [main]`). Default-branch scans - still keep the baseline current; feature branches are scanned only through their - pull requests. -- Run the pull request scan in its own job (for example `socket-pr` with - `if: github.event_name == 'pull_request'`, and - `if: github.event_name != 'pull_request'` on the existing job), and require that - job's check. +`edited`, and others) and unsupported events log a warning and exit `0` without +scanning. `issue_comment` handles ignore commands. With `--scm gitlab`, the +recognized scan sources are `web`, `merge_request_event`, `push`, `api`, and +`pipeline`. Other sources, apart from the comment flow, also warn and exit `0` +without scanning. + +- A GitHub merge queue evaluates required checks on the `merge_group` commit. + The CLI skips that event. Use a check that scans the merge group for + [merge queue enforcement](https://docs.github.com/en/pull-requests/how-tos/merge-and-close-pull-requests/troubleshooting-required-status-checks#status-checks-with-github-actions-and-a-merge-queue). +- GitHub runs `pull_request_target` in the base repository context, and the CLI + skips it. Under GitHub's default fork settings, `pull_request` runs cannot + access the Socket API secret. The CLI exits with its infrastructure error code + if the token is missing. See GitHub's guidance for + [securing workflows that handle fork PRs](https://docs.github.com/en/actions/reference/security/securely-using-pull_request_target). + +### Required GitHub checks + +Use the [PR workflow](../workflows/github-actions.yml) for the required +`socket-security` check. If your workflow skips drafts, include +`ready_for_review` in its `pull_request.types` so marking a PR ready starts the scan. +Use the [push workflow](../workflows/github-actions-push.yml) to update the +default-branch baseline and scan branch pushes. Use the +[ignore-command workflow](../workflows/github-actions-comments.yml) if your +repository handles ignore commands in PR comments. + +GitHub normally checks the PR's test merge commit when it has a status and +otherwise checks the head commit. The default PR checkout uses the test merge +commit, while a push run uses the pushed commit. Keep the required job name +exclusive to the PR workflow in either setup. A job skipped by a job-level +`if` in a shared workflow can still report a successful check. See GitHub's +[required status check rules](https://docs.github.com/en/pull-requests/how-tos/merge-and-close-pull-requests/troubleshooting-required-status-checks). + +When replacing the combined example, copy the PR workflow to the existing +workflow path and remove any other jobs named `socket-security`. Confirm the +PR job reports the check named in branch protection. If you use +`--strict-blocking` as a merge gate, verify a reopened PR with an existing +Block alert fails and a completed clean comparison passes. ## Pull request and Dashboard association @@ -685,7 +685,7 @@ listed thinly or not at all. Prebuilt examples in this repo: -- [`../workflows/github-actions.yml`](../workflows/github-actions.yml) +- GitHub Actions for [pull requests](../workflows/github-actions.yml), [pushes](../workflows/github-actions-push.yml), and [ignore commands](../workflows/github-actions-comments.yml) - [`../workflows/buildkite.yml`](../workflows/buildkite.yml) - [`../workflows/gitlab-ci.yml`](../workflows/gitlab-ci.yml) - [`../workflows/bitbucket-pipelines.yml`](../workflows/bitbucket-pipelines.yml) diff --git a/pyproject.toml b/pyproject.toml index b7578c83..4da80233 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ build-backend = "hatchling.build" [project] name = "socketsecurity" -version = "2.13.3" +version = "2.14.0" requires-python = ">= 3.11" license = {"file" = "LICENSE"} dependencies = [ diff --git a/socketsecurity/__init__.py b/socketsecurity/__init__.py index 0871adeb..0f2224d3 100644 --- a/socketsecurity/__init__.py +++ b/socketsecurity/__init__.py @@ -1,4 +1,4 @@ __author__ = 'socket.dev' -__version__ = '2.13.3' +__version__ = '2.14.0' USER_AGENT_NAME = 'socket-python-cli' USER_AGENT = f'{USER_AGENT_NAME}/{__version__}' diff --git a/socketsecurity/core/scm/github.py b/socketsecurity/core/scm/github.py index 7e0f06d2..0dd45f01 100644 --- a/socketsecurity/core/scm/github.py +++ b/socketsecurity/core/scm/github.py @@ -14,13 +14,7 @@ from socketsecurity.exit_codes import InfrastructureError from socketsecurity.socketcli import CliClient -# pull_request actions that can leave a PR head without a current Socket result: -# new commits (opened, synchronize) and a PR coming back after it was closed or -# drafted (reopened, ready_for_review). A skipped run exits 0, and GitHub doesn't -# define which run a required check uses when the same job runs more than once on a -# commit, so a skipped run on one of these could satisfy the check in place of an -# earlier failure. Other actions (closed, labeled, edited, ...) are skipped with a -# warning. +# Reopening a PR or marking it ready can require a fresh check on the same commit. PULL_REQUEST_SCAN_ACTIONS = ("opened", "synchronize", "reopened", "ready_for_review") HANDLED_EVENTS = ( "push, workflow_dispatch and pull_request (scan); issue_comment (ignore commands)" @@ -214,13 +208,16 @@ def check_event_type(self) -> str: elif event_name == "issue_comment": return "comment" elif event_name == "pull_request_target": - # Not treated as pull_request on purpose: GITHUB_SHA and GITHUB_REF point at - # the base branch and the default checkout is the base branch, so a "PR scan" - # here would compare the base against itself and pass. log.warning( - "GitHub event 'pull_request_target' is not scanned: it runs against the " - "base branch, not the pull request head. No scan ran; exiting 0. Trigger " - "the Socket job on pull_request instead." + "GitHub event 'pull_request_target' is not scanned: it runs in the base " + "repository context. No scan ran; exiting 0. Trigger the Socket PR check " + "on pull_request." + ) + sys.exit(0) + elif event_name == "merge_group": + log.warning( + "GitHub event 'merge_group' is not scanned. No scan ran; exiting 0. " + "A required merge queue check must scan the merge group commit." ) sys.exit(0) diff --git a/tests/core/test_cli_exit_contract.py b/tests/core/test_cli_exit_contract.py index 74c4ceef..0ac35be9 100644 --- a/tests/core/test_cli_exit_contract.py +++ b/tests/core/test_cli_exit_contract.py @@ -287,7 +287,6 @@ def test_scm_event_filters_skip_without_scanning(cli_runtime, monkeypatch, caplo with caplog.at_level("INFO", logger="socketdev"): assert cli_runtime.run(["--scm", scm]) == 0 cli_runtime.scan.assert_not_called() - # A skipped run passes, so it has to say so where a required-check owner looks. assert any( record.levelname == "WARNING" and "No scan ran" in record.getMessage() for record in caplog.records diff --git a/tests/unit/test_github_event_filter.py b/tests/unit/test_github_event_filter.py index 5973673c..b394ffb6 100644 --- a/tests/unit/test_github_event_filter.py +++ b/tests/unit/test_github_event_filter.py @@ -1,11 +1,6 @@ -"""Which GitHub events and pull_request actions run a scan. - -A skipped run exits 0, and GitHub doesn't define which run a required check uses -when the same job runs more than once on a commit, so skipping an action that a -workflow subscribes to can satisfy the check with a pass that never scanned -anything. -""" +"""GitHub and GitLab event routing and the CLI outcomes for GitHub PR actions.""" +import json import logging import sys from contextlib import nullcontext @@ -111,9 +106,14 @@ def test_other_pull_request_actions_skip_with_a_warning(monkeypatch, caplog, act ) +@pytest.mark.parametrize("has_payload", [False, True]) def test_missing_pull_request_action_says_it_could_not_be_determined( - monkeypatch, caplog + monkeypatch, caplog, tmp_path, has_payload ): + if has_payload: + event_path = tmp_path / "event.json" + event_path.write_text("{}", encoding="utf-8") + monkeypatch.setenv("GITHUB_EVENT_PATH", str(event_path)) warnings = _skip_warnings(_github(monkeypatch, "pull_request"), caplog) assert any( @@ -134,8 +134,8 @@ def test_missing_event_name_says_it_could_not_be_determined(monkeypatch, caplog) @pytest.mark.parametrize( "event_name, expected", [ - ("pull_request_target", "runs against the base branch"), - ("merge_group", "'merge_group' is not scanned"), + ("pull_request_target", "runs in the base repository context"), + ("merge_group", "A required merge queue check must scan the merge group commit"), ("schedule", "'schedule' is not scanned"), ], ) @@ -145,8 +145,7 @@ def test_unscanned_events_skip_with_a_warning( warnings = _skip_warnings(_github(monkeypatch, event_name, "opened"), caplog) assert any(expected in message and "No scan ran" in message for message in warnings) - # issue_comment is handled, but it runs the ignore-command flow, not a scan. - if event_name != "pull_request_target": + if event_name == "schedule": assert any("issue_comment (ignore commands)" in message for message in warnings) @@ -192,18 +191,19 @@ def _blocking_alert() -> Issue: @pytest.mark.parametrize( - "action, scanned, expected_exit", + "action, has_blocker, scanned, expected_exit", [ - ("reopened", True, 1), - ("ready_for_review", True, 1), - ("synchronize", True, 1), - ("closed", False, 0), + ("reopened", True, True, 1), + ("reopened", False, True, 0), + ("ready_for_review", True, True, 1), + ("ready_for_review", False, True, 0), + ("synchronize", True, True, 1), + ("closed", True, False, 0), ], ) -def test_reopened_pull_request_blocks_like_synchronize( - monkeypatch, action, scanned, expected_exit +def test_pull_request_payload_drives_scan_and_exit( + monkeypatch, tmp_path, action, has_blocker, scanned, expected_exit ): - """A reopened PR with an existing blocker fails instead of passing unscanned.""" monkeypatch.setattr( sys, "argv", @@ -225,10 +225,13 @@ def test_reopened_pull_request_blocks_like_synchronize( ], ) monkeypatch.setenv("GITHUB_EVENT_NAME", "pull_request") - monkeypatch.setenv("EVENT_ACTION", action) + event_path = tmp_path / "event.json" + event_path.write_text(json.dumps({"action": action}), encoding="utf-8") + monkeypatch.setenv("GITHUB_EVENT_PATH", str(event_path)) monkeypatch.setenv("DEFAULT_BRANCH", "false") - diff = Diff(id="scan", new_alerts=[], unchanged_alerts=[_blocking_alert()]) + existing_alerts = [_blocking_alert()] if has_blocker else [] + diff = Diff(id="scan", new_alerts=[], unchanged_alerts=existing_alerts) diff.diff_url = "https://socket.dev/diff" monkeypatch.setattr( Github, @@ -248,6 +251,8 @@ def test_reopened_pull_request_blocks_like_synchronize( monkeypatch.setattr(socketcli, "apply_git_context", lambda config: (False, None)) scan = Mock(return_value=diff) monkeypatch.setattr(socketcli.Core, "create_new_diff", scan) + full_scan = Mock() + monkeypatch.setattr(socketcli.Core, "create_full_scan_with_report_url", full_scan) monkeypatch.setattr(socketcli.Core, "has_manifest_files", Mock(return_value=True)) monkeypatch.setattr(socketcli.OutputHandler, "handle_output", Mock()) @@ -255,5 +260,10 @@ def test_reopened_pull_request_blocks_like_synchronize( socketcli.cli() assert result.value.code == expected_exit + full_scan.assert_not_called() assert scan.called is scanned assert posted.called is scanned + if scanned: + scan.assert_called_once() + posted.assert_called_once() + assert posted.call_args.args[3] is has_blocker diff --git a/uv.lock b/uv.lock index 57c8b444..d509bbc9 100644 --- a/uv.lock +++ b/uv.lock @@ -1334,7 +1334,7 @@ wheels = [ [[package]] name = "socketsecurity" -version = "2.13.3" +version = "2.14.0" source = { editable = "." } dependencies = [ { name = "beautifulsoup4" }, diff --git a/workflows/github-actions-comments.yml b/workflows/github-actions-comments.yml new file mode 100644 index 00000000..9bef3e44 --- /dev/null +++ b/workflows/github-actions-comments.yml @@ -0,0 +1,36 @@ +# Copy this workflow to .github/workflows/ to handle PR ignore commands. +name: Socket Security Ignore Commands + +on: + issue_comment: + types: [created] + +concurrency: + group: socket-ignore-${{ github.event.issue.number }} + cancel-in-progress: false + +jobs: + socket-security-ignore: + if: github.event.issue.pull_request + permissions: + contents: read + issues: write + pull-requests: write + runs-on: ubuntu-latest + container: socketdev/cli:latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Handle Socket Security Ignore Commands + env: + SOCKET_SECURITY_API_KEY: ${{ secrets.SOCKET_SECURITY_API_KEY }} + GH_API_TOKEN: ${{ secrets.GITHUB_TOKEN }} + PR_NUMBER: ${{ github.event.issue.number }} + run: | + socketcli \ + --target-path "$GITHUB_WORKSPACE" \ + --scm github \ + --pr-number "$PR_NUMBER" diff --git a/workflows/github-actions-push.yml b/workflows/github-actions-push.yml new file mode 100644 index 00000000..018feb57 --- /dev/null +++ b/workflows/github-actions-push.yml @@ -0,0 +1,32 @@ +# Copy this workflow to .github/workflows/ to scan pushes and update the baseline. +name: Socket Security Pushes + +on: + push: + branches: ['**'] + +concurrency: + group: socket-push-${{ github.ref }}-${{ github.sha }} + cancel-in-progress: true + +jobs: + socket-security-push: + permissions: + contents: read + runs-on: ubuntu-latest + container: socketdev/cli:latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Run Socket Security Push Scan + env: + SOCKET_SECURITY_API_KEY: ${{ secrets.SOCKET_SECURITY_API_KEY }} + GH_API_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + socketcli \ + --target-path "$GITHUB_WORKSPACE" \ + --scm github \ + --pr-number 0 diff --git a/workflows/github-actions.yml b/workflows/github-actions.yml index ffd4c79d..23b8885b 100644 --- a/workflows/github-actions.yml +++ b/workflows/github-actions.yml @@ -1,70 +1,35 @@ -# Socket Security GitHub Actions Workflow -# This workflow runs Socket Security scans on every commit to any branch -# It automatically detects git repository information and handles different event types - -name: socket-security-workflow -run-name: Socket Security Github Action +# Copy this workflow to .github/workflows/ to enable the PR scan. +name: Socket Security Pull Requests on: - push: - # On a branch with an open pull request, this also runs the job on the PR head - # commit as a full scan, which exits 0. If this job is a required check, restrict - # push to the default branch or give the pull_request run its own job name. See - # "Push and pull request runs on the same commit" in docs/ci-cd.md. - branches: ['**'] # Run on all branches, all commits pull_request: - # Every listed action runs a scan. Don't add actions the CLI skips (closed, - # labeled, edited, ...): a skipped run exits 0 and can satisfy a required check - # on a commit an earlier run failed. - types: [opened, synchronize, reopened] - issue_comment: - types: [created] + types: [opened, synchronize, reopened, ready_for_review] -# Prevent concurrent runs for the same commit concurrency: - group: socket-scan-${{ github.sha }} + group: socket-pr-${{ github.event.pull_request.number }} cancel-in-progress: true jobs: socket-security: permissions: - issues: write contents: read + issues: write pull-requests: write runs-on: ubuntu-latest - - # Option 1: Use the official Socket CLI container (faster, more reliable) container: socketdev/cli:latest - steps: - uses: actions/checkout@v4 with: - # For PRs, fetch one additional commit for proper diff analysis fetch-depth: 0 - - - name: Run Socket Security Scan + persist-credentials: false + + - name: Run Socket Security PR Scan env: SOCKET_SECURITY_API_KEY: ${{ secrets.SOCKET_SECURITY_API_KEY }} GH_API_TOKEN: ${{ secrets.GITHUB_TOKEN }} + PR_NUMBER: ${{ github.event.pull_request.number }} run: | - # Determine PR number based on event type - PR_NUMBER=0 - if [ "${{ github.event_name }}" == "pull_request" ]; then - PR_NUMBER=${{ github.event.pull_request.number }} - elif [ "${{ github.event_name }}" == "issue_comment" ]; then - PR_NUMBER=${{ github.event.issue.number }} - fi - - # Run Socket CLI with minimal required parameters - # The CLI automatically detects: - # - Repository name from git - # - Branch name from git - # - Commit SHA from git - # - Commit message from git - # - Committer information from git - # - Default branch status from git and GitHub environment - # - Changed files from git commit socketcli \ - --target-path $GITHUB_WORKSPACE \ + --target-path "$GITHUB_WORKSPACE" \ --scm github \ - --pr-number $PR_NUMBER + --pr-number "$PR_NUMBER" From a290f9bf05f9ac9313f03f23ff77f5ee2e7b5eab Mon Sep 17 00:00:00 2001 From: lelia <2418071+lelia@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:15:39 -0500 Subject: [PATCH 6/6] Warn that the PR workflow alone stops baseline updates --- CHANGELOG.md | 6 ++++-- docs/ci-cd.md | 5 ++++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 41721575..513d133f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,10 @@ - If you use the GitHub Actions example, replace the combined workflow with the [PR workflow](workflows/github-actions.yml) and require its `socket-security` - check. Install the [push workflow](workflows/github-actions-push.yml) to keep - branch scans and baseline updates. Install the + check. Install the [push workflow](workflows/github-actions-push.yml) in the + same change: the PR workflow doesn't run on pushes, so without it the + default-branch baseline stops updating and PR comparisons run against an old + scan. Install the [ignore-command workflow](workflows/github-actions-comments.yml) if you use PR ignore commands. diff --git a/docs/ci-cd.md b/docs/ci-cd.md index db1e0788..bd21174a 100644 --- a/docs/ci-cd.md +++ b/docs/ci-cd.md @@ -559,7 +559,10 @@ exclusive to the PR workflow in either setup. A job skipped by a job-level When replacing the combined example, copy the PR workflow to the existing workflow path and remove any other jobs named `socket-security`. Confirm the -PR job reports the check named in branch protection. If you use +PR job reports the check named in branch protection. Add the push workflow in +the same change: the PR workflow doesn't run on pushes, so without it the +default-branch baseline stops updating and later PR comparisons run against an +old scan. If you use `--strict-blocking` as a merge gate, verify a reopened PR with an existing Block alert fails and a completed clean comparison passes.