diff --git a/CHANGELOG.md b/CHANGELOG.md index 9fd7d533..fdd5c263 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,8 @@ alerts. - With `--scm github`, reopened pull requests and pull requests marked ready for review run the PR scan. +- GitHub pull request comment runs exit `0` and leave the Socket security + comment unchanged when there are no Socket ignore commands to process. ### Documentation diff --git a/docs/ci-cd.md b/docs/ci-cd.md index ebb6e6c4..7c22a810 100644 --- a/docs/ci-cd.md +++ b/docs/ci-cd.md @@ -139,6 +139,11 @@ Buildkite-specific config-file format is required. SOCKET_SECURITY_API_TOKEN: ${{ secrets.SOCKET_SECURITY_API_TOKEN }} ``` +With `--scm github`, `issue_comment` runs process Socket ignore commands on the +pull request. When there are no commands to process, the run exits `0` and +leaves the security comment unchanged. Use a dedicated `pull_request` scan job +for any required check that gates merges on scan findings. + #### GitHub Actions: scan changed monorepo workspaces independently GitHub Actions `paths` filters only decide whether a workflow starts. They do not diff --git a/socketsecurity/core/scm/github.py b/socketsecurity/core/scm/github.py index 0dd45f01..f5445f9b 100644 --- a/socketsecurity/core/scm/github.py +++ b/socketsecurity/core/scm/github.py @@ -379,6 +379,9 @@ def add_socket_comments( self.post_comment(security_comment) def remove_comment_alerts(self, comments: dict) -> None: + if not comments.get("ignore"): + log.info("No @SocketSecurity ignore commands to process on this pull request") + return if security_alert := comments.get("security"): new_body = Comments.process_security_comment(security_alert, comments) self.handle_ignore_reactions(comments) diff --git a/socketsecurity/core/scm/gitlab.py b/socketsecurity/core/scm/gitlab.py index 4c9cdbf6..d661a897 100644 --- a/socketsecurity/core/scm/gitlab.py +++ b/socketsecurity/core/scm/gitlab.py @@ -480,6 +480,9 @@ def handle_ignore_reactions(self, comments: dict) -> None: self.post_thumbsup_reaction(comment.id) def remove_comment_alerts(self, comments: dict): + if not comments.get("ignore"): + log.info("No @SocketSecurity ignore commands to process on this merge request") + return security_alert = comments.get("security") if security_alert is not None: # Type narrowing: after None check, mypy knows this is Comment diff --git a/socketsecurity/core/scm_comments.py b/socketsecurity/core/scm_comments.py index c794583f..66826a67 100644 --- a/socketsecurity/core/scm_comments.py +++ b/socketsecurity/core/scm_comments.py @@ -59,7 +59,7 @@ def get_ignore_options(comments: dict) -> [bool, list]: ignore_commands = [] ignore_all = False - for comment in comments["ignore"]: + for comment in comments.get("ignore", []): comment: Comment first_line = comment.body_list[0] if not ignore_all and "socketsecurity ignore" in first_line.lower(): diff --git a/tests/unit/test_comment_event_flow.py b/tests/unit/test_comment_event_flow.py new file mode 100644 index 00000000..3bf52604 --- /dev/null +++ b/tests/unit/test_comment_event_flow.py @@ -0,0 +1,256 @@ +"""SCM comment events with and without Socket ignore commands.""" + +import sys +from contextlib import nullcontext +from unittest.mock import MagicMock, Mock + +import pytest + +from socketsecurity import socketcli +from socketsecurity.core.classes import Comment +from socketsecurity.core.scm.github import Github +from socketsecurity.core.scm.gitlab import Gitlab, GitlabConfig +from socketsecurity.core.scm_comments import Comments + +SECURITY_COMMENT = "\n".join([ + "", + "

Socket Security: Pull Request Alerts

", + "", + "", + "", + "", + "", + "", + "", + "
npm/lodash@4.17.11 - Prototype Pollution
npm/handlebars@4.0.11 - Remote Code Execution
", + "[View full report](https://socket.dev/dashboard/org/acme/diff/abc?foo=bar)", +]) +GITHUB_COMMENTS_PATH = "repos/acme/repo/issues/42/comments" +GITHUB_PERMISSION_PATH = "repos/acme/repo/collaborators/maintainer/permission" + + +def _comment(body: str, comment_id: int) -> Comment: + return Comment( + id=comment_id, + body=body, + body_list=body.split("\n"), + reactions={"+1": 0}, + user={"login": "maintainer", "id": 7}, + ) + + +def _run_comment_event(monkeypatch, raw_comments, *, permission="write", extra_args=()): + argv = [ + "socketcli", "--api-token", "test", "--scm", "github", + "--repo", "repo", "--branch", "feature", "--pr-number", "42", + *extra_args, + ] + monkeypatch.setattr(sys, "argv", argv) + for key, value in { + "GH_API_TOKEN": "test", "GITHUB_EVENT_NAME": "issue_comment", + "EVENT_ACTION": "created", "GITHUB_REPOSITORY": "acme/repo", + "DEFAULT_BRANCH": "false", + }.items(): + monkeypatch.setenv(key, value) + + get_comments = Mock(return_value=[vars(comment) for comment in raw_comments.values()]) + + def request(*, path, method="GET", **kwargs): + assert method == "GET" + if path == GITHUB_COMMENTS_PATH: + return Mock(json=get_comments) + assert path == GITHUB_PERMISSION_PATH + return Mock(json=Mock(return_value={"permission": permission})) + + update_comment = Mock() + monkeypatch.setattr(Github, "update_comment", update_comment) + post_reaction = Mock() + monkeypatch.setattr(Github, "post_reaction", post_reaction) + monkeypatch.setattr(Github, "comment_reaction_exists", Mock(return_value=False)) + + sdk = MagicMock() + sdk.org.get.return_value = {"organizations": {"org-id": {"slug": "acme"}}} + monkeypatch.setattr(socketcli, "build_socket_sdk", Mock(return_value=sdk)) + client = Mock() + client.request.side_effect = request + monkeypatch.setattr(socketcli, "CliClient", Mock(return_value=client)) + monkeypatch.setattr(socketcli, "StreamingLogs", lambda **kwargs: nullcontext(Mock())) + monkeypatch.setattr(socketcli, "apply_git_context", lambda config: (False, None)) + scan = Mock() + monkeypatch.setattr(socketcli.Core, "create_new_diff", scan) + monkeypatch.setattr(socketcli.Core, "create_full_scan_with_report_url", scan) + + with pytest.raises(SystemExit) as result: + socketcli.cli() + + scan.assert_not_called() + return result.value.code, get_comments, update_comment, post_reaction, client + + +def _security_and(*bodies): + raw = {1: _comment(SECURITY_COMMENT, 1)} + for offset, body in enumerate(bodies, start=2): + raw[offset] = _comment(body, offset) + return raw + + +class TestCliCommentEvent: + @pytest.mark.parametrize("body", [ + "LGTM, merging after CI", + "", + "Can we ignore this one? @SocketSecurity please look", + ]) + def test_ordinary_comment_exits_0_and_leaves_security_comment(self, monkeypatch, body): + code, get_comments, update_comment, post_reaction, client = _run_comment_event( + monkeypatch, _security_and(body), extra_args=("--strict-blocking",), + ) + + assert code == 0 + get_comments.assert_called_once() + assert [call.kwargs["path"] for call in client.request.call_args_list] == [ + GITHUB_COMMENTS_PATH, + ] + update_comment.assert_not_called() + post_reaction.assert_not_called() + client.post_telemetry_events.assert_not_called() + + def test_ordinary_comment_without_security_comment_exits_0(self, monkeypatch): + code, _, update_comment, _, _ = _run_comment_event( + monkeypatch, {5: _comment("ship it", 5)}, + ) + + assert code == 0 + update_comment.assert_not_called() + + def test_ignore_command_removes_only_that_package(self, monkeypatch): + code, _, update_comment, post_reaction, client = _run_comment_event( + monkeypatch, + _security_and("first ordinary comment", "@SocketSecurity ignore npm/lodash@4.17.11"), + ) + + assert code == 0 + update_comment.assert_called_once() + body, comment_id = update_comment.call_args.args + assert comment_id == "1" + assert "start-socket-alert-npm/lodash@4.17.11" not in body + assert "start-socket-alert-npm/handlebars@4.0.11" in body + post_reaction.assert_called_once_with(3) + events = client.post_telemetry_events.call_args.args[1] + assert [e["artifact_input"] for e in events] == ["npm/lodash@4.17.11"] + + def test_ignore_all_clears_the_table(self, monkeypatch): + code, _, update_comment, post_reaction, client = _run_comment_event( + monkeypatch, _security_and("@SocketSecurity ignore-all"), + ) + + assert code == 0 + body = update_comment.call_args.args[0] + assert "start-socket-alert" not in body + assert "No dependency alerts to report" in body + post_reaction.assert_called_once_with(2) + events = client.post_telemetry_events.call_args.args[1] + assert len(events) == 1 and events[0]["ignore_all"] is True + + @pytest.mark.parametrize("command", [ + "@SocketSecurity ignore npm/lodash@4.17.11", "@SocketSecurity ignore-all", "LGTM", + ]) + def test_disable_ignore_skips_comment_processing(self, monkeypatch, command): + code, get_comments, update_comment, post_reaction, client = _run_comment_event( + monkeypatch, _security_and(command), extra_args=("--disable-ignore",), + ) + + assert code == 0 + get_comments.assert_not_called() + client.request.assert_not_called() + update_comment.assert_not_called() + post_reaction.assert_not_called() + client.post_telemetry_events.assert_not_called() + + def test_unauthorized_ignore_is_dropped_without_crashing(self, monkeypatch): + code, _, update_comment, post_reaction, client = _run_comment_event( + monkeypatch, + _security_and("@SocketSecurity ignore npm/lodash@4.17.11"), + permission="read", + extra_args=("--strict-blocking",), + ) + + assert code == 0 + assert [call.kwargs["path"] for call in client.request.call_args_list] == [ + GITHUB_COMMENTS_PATH, + GITHUB_PERMISSION_PATH, + ] + update_comment.assert_not_called() + post_reaction.assert_not_called() + client.post_telemetry_events.assert_not_called() + + @pytest.mark.parametrize("command", [ + "@SocketSecurity ignore", + "@SocketSecurity ignore lodash", + "@SocketSecurity ignore @4.17.11", + "@SocketSecurity ignore npm/lodash@", + ]) + def test_malformed_ignore_command_keeps_every_alert(self, monkeypatch, command): + code, _, update_comment, _, _ = _run_comment_event(monkeypatch, _security_and(command)) + + assert code == 0 + body = update_comment.call_args.args[0] + assert "start-socket-alert-npm/lodash@4.17.11" in body + assert "start-socket-alert-npm/handlebars@4.0.11" in body + + +class TestGetIgnoreOptions: + def test_no_ignore_key(self): + assert Comments.get_ignore_options({}) == (False, []) + assert Comments.get_ignore_options({"security": _comment(SECURITY_COMMENT, 1)}) == (False, []) + + def test_process_security_comment_without_ignore_key_keeps_alerts(self): + security = _comment(SECURITY_COMMENT, 1) + body = Comments.process_security_comment(security, {"security": security}) + + assert "start-socket-alert-npm/lodash@4.17.11" in body + assert "start-socket-alert-npm/handlebars@4.0.11" in body + + +class TestAdapterRemoveCommentAlerts: + def _github(self): + gh = Github.__new__(Github) + gh.update_comment = Mock() + gh.handle_ignore_reactions = Mock() + return gh + + def _gitlab(self): + config = GitlabConfig( + commit_sha="abc", api_url="https://gitlab.example.com/api/v4", + project_dir=".", mr_source_branch="feature", mr_iid="7", + mr_project_id=1, commit_message="", default_branch="main", + project_name="repo", pipeline_source="merge_request_event", + commit_author="dev", token="t", repository="repo", is_default_branch=False, + headers={}, + ) + gl = Gitlab(client=MagicMock(), config=config) + gl.update_comment = Mock() + gl.handle_ignore_reactions = Mock() + return gl + + @pytest.mark.parametrize("make", ["_github", "_gitlab"]) + def test_no_ignore_comments_leaves_security_comment(self, make): + scm = getattr(self, make)() + scm.remove_comment_alerts({"security": _comment(SECURITY_COMMENT, 1)}) + + scm.update_comment.assert_not_called() + scm.handle_ignore_reactions.assert_not_called() + + @pytest.mark.parametrize("make", ["_github", "_gitlab"]) + def test_ignore_comment_rewrites_security_comment(self, make): + scm = getattr(self, make)() + comments = Comments.check_for_socket_comments({ + 1: _comment(SECURITY_COMMENT, 1), + 2: _comment("@SocketSecurity ignore npm/handlebars@4.0.11", 2), + }) + scm.remove_comment_alerts(comments) + + body, comment_id = scm.update_comment.call_args.args + assert comment_id == "1" + assert "start-socket-alert-npm/handlebars@4.0.11" not in body + assert "start-socket-alert-npm/lodash@4.17.11" in body + scm.handle_ignore_reactions.assert_called_once_with(comments)