Skip to content

Commit ef54e69

Browse files
dc-larsenlelia
andauthored
Handle GitHub comment runs without Socket ignore commands (#464)
* Handle issue_comment runs that have no ignore command An issue_comment run on a pull request that already has a Socket security comment crashed with KeyError: 'ignore' and exited 3 unless the pull request also had an honored @SocketSecurity ignore command. check_for_socket_comments only adds the "ignore" key when such a command exists, but remove_comment_alerts called process_security_comment whenever the security comment existed, and get_ignore_options indexed comments["ignore"] directly. Any ordinary comment, or an ignore command from someone without write access, failed the job. remove_comment_alerts (GitHub and GitLab) now returns early and leaves the security comment untouched when there are no ignore commands, and get_ignore_options treats a missing key as no commands. Ignore, ignore-all and --disable-ignore behave as before. * Bump version to 2.13.3 2.13.2 was released from main, so this change needs the next patch version. --------- Co-authored-by: lelia <2418071+lelia@users.noreply.github.com>
1 parent a38c880 commit ef54e69

6 files changed

Lines changed: 270 additions & 1 deletion

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@
3939
alerts.
4040
- With `--scm github`, reopened pull requests and pull requests marked ready for
4141
review run the PR scan.
42+
- GitHub pull request comment runs exit `0` and leave the Socket security
43+
comment unchanged when there are no Socket ignore commands to process.
4244

4345
### Documentation
4446

‎docs/ci-cd.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,11 @@ Buildkite-specific config-file format is required.
139139
SOCKET_SECURITY_API_TOKEN: ${{ secrets.SOCKET_SECURITY_API_TOKEN }}
140140
```
141141

142+
With `--scm github`, `issue_comment` runs process Socket ignore commands on the
143+
pull request. When there are no commands to process, the run exits `0` and
144+
leaves the security comment unchanged. Use a dedicated `pull_request` scan job
145+
for any required check that gates merges on scan findings.
146+
142147
#### GitHub Actions: scan changed monorepo workspaces independently
143148

144149
GitHub Actions `paths` filters only decide whether a workflow starts. They do not

‎socketsecurity/core/scm/github.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -379,6 +379,9 @@ def add_socket_comments(
379379
self.post_comment(security_comment)
380380

381381
def remove_comment_alerts(self, comments: dict) -> None:
382+
if not comments.get("ignore"):
383+
log.info("No @SocketSecurity ignore commands to process on this pull request")
384+
return
382385
if security_alert := comments.get("security"):
383386
new_body = Comments.process_security_comment(security_alert, comments)
384387
self.handle_ignore_reactions(comments)

‎socketsecurity/core/scm/gitlab.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -480,6 +480,9 @@ def handle_ignore_reactions(self, comments: dict) -> None:
480480
self.post_thumbsup_reaction(comment.id)
481481

482482
def remove_comment_alerts(self, comments: dict):
483+
if not comments.get("ignore"):
484+
log.info("No @SocketSecurity ignore commands to process on this merge request")
485+
return
483486
security_alert = comments.get("security")
484487
if security_alert is not None:
485488
# Type narrowing: after None check, mypy knows this is Comment

‎socketsecurity/core/scm_comments.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ def get_ignore_options(comments: dict) -> [bool, list]:
5959
ignore_commands = []
6060
ignore_all = False
6161

62-
for comment in comments["ignore"]:
62+
for comment in comments.get("ignore", []):
6363
comment: Comment
6464
first_line = comment.body_list[0]
6565
if not ignore_all and "socketsecurity ignore" in first_line.lower():
Lines changed: 256 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,256 @@
1+
"""SCM comment events with and without Socket ignore commands."""
2+
3+
import sys
4+
from contextlib import nullcontext
5+
from unittest.mock import MagicMock, Mock
6+
7+
import pytest
8+
9+
from socketsecurity import socketcli
10+
from socketsecurity.core.classes import Comment
11+
from socketsecurity.core.scm.github import Github
12+
from socketsecurity.core.scm.gitlab import Gitlab, GitlabConfig
13+
from socketsecurity.core.scm_comments import Comments
14+
15+
SECURITY_COMMENT = "\n".join([
16+
"<!-- socket-security-comment-actions -->",
17+
"<h2>Socket Security: Pull Request Alerts</h2>",
18+
"<table>",
19+
"<!-- start-socket-alert-npm/lodash@4.17.11 -->",
20+
"<tr><td><details><summary>npm/lodash@4.17.11 - Prototype Pollution</summary></details></td></tr>",
21+
"<!-- end-socket-alert-npm/lodash@4.17.11 -->",
22+
"<!-- start-socket-alert-npm/handlebars@4.0.11 -->",
23+
"<tr><td><details><summary>npm/handlebars@4.0.11 - Remote Code Execution</summary></details></td></tr>",
24+
"<!-- end-socket-alert-npm/handlebars@4.0.11 -->",
25+
"</table>",
26+
"[View full report](https://socket.dev/dashboard/org/acme/diff/abc?foo=bar)",
27+
])
28+
GITHUB_COMMENTS_PATH = "repos/acme/repo/issues/42/comments"
29+
GITHUB_PERMISSION_PATH = "repos/acme/repo/collaborators/maintainer/permission"
30+
31+
32+
def _comment(body: str, comment_id: int) -> Comment:
33+
return Comment(
34+
id=comment_id,
35+
body=body,
36+
body_list=body.split("\n"),
37+
reactions={"+1": 0},
38+
user={"login": "maintainer", "id": 7},
39+
)
40+
41+
42+
def _run_comment_event(monkeypatch, raw_comments, *, permission="write", extra_args=()):
43+
argv = [
44+
"socketcli", "--api-token", "test", "--scm", "github",
45+
"--repo", "repo", "--branch", "feature", "--pr-number", "42",
46+
*extra_args,
47+
]
48+
monkeypatch.setattr(sys, "argv", argv)
49+
for key, value in {
50+
"GH_API_TOKEN": "test", "GITHUB_EVENT_NAME": "issue_comment",
51+
"EVENT_ACTION": "created", "GITHUB_REPOSITORY": "acme/repo",
52+
"DEFAULT_BRANCH": "false",
53+
}.items():
54+
monkeypatch.setenv(key, value)
55+
56+
get_comments = Mock(return_value=[vars(comment) for comment in raw_comments.values()])
57+
58+
def request(*, path, method="GET", **kwargs):
59+
assert method == "GET"
60+
if path == GITHUB_COMMENTS_PATH:
61+
return Mock(json=get_comments)
62+
assert path == GITHUB_PERMISSION_PATH
63+
return Mock(json=Mock(return_value={"permission": permission}))
64+
65+
update_comment = Mock()
66+
monkeypatch.setattr(Github, "update_comment", update_comment)
67+
post_reaction = Mock()
68+
monkeypatch.setattr(Github, "post_reaction", post_reaction)
69+
monkeypatch.setattr(Github, "comment_reaction_exists", Mock(return_value=False))
70+
71+
sdk = MagicMock()
72+
sdk.org.get.return_value = {"organizations": {"org-id": {"slug": "acme"}}}
73+
monkeypatch.setattr(socketcli, "build_socket_sdk", Mock(return_value=sdk))
74+
client = Mock()
75+
client.request.side_effect = request
76+
monkeypatch.setattr(socketcli, "CliClient", Mock(return_value=client))
77+
monkeypatch.setattr(socketcli, "StreamingLogs", lambda **kwargs: nullcontext(Mock()))
78+
monkeypatch.setattr(socketcli, "apply_git_context", lambda config: (False, None))
79+
scan = Mock()
80+
monkeypatch.setattr(socketcli.Core, "create_new_diff", scan)
81+
monkeypatch.setattr(socketcli.Core, "create_full_scan_with_report_url", scan)
82+
83+
with pytest.raises(SystemExit) as result:
84+
socketcli.cli()
85+
86+
scan.assert_not_called()
87+
return result.value.code, get_comments, update_comment, post_reaction, client
88+
89+
90+
def _security_and(*bodies):
91+
raw = {1: _comment(SECURITY_COMMENT, 1)}
92+
for offset, body in enumerate(bodies, start=2):
93+
raw[offset] = _comment(body, offset)
94+
return raw
95+
96+
97+
class TestCliCommentEvent:
98+
@pytest.mark.parametrize("body", [
99+
"LGTM, merging after CI",
100+
"",
101+
"Can we ignore this one? @SocketSecurity please look",
102+
])
103+
def test_ordinary_comment_exits_0_and_leaves_security_comment(self, monkeypatch, body):
104+
code, get_comments, update_comment, post_reaction, client = _run_comment_event(
105+
monkeypatch, _security_and(body), extra_args=("--strict-blocking",),
106+
)
107+
108+
assert code == 0
109+
get_comments.assert_called_once()
110+
assert [call.kwargs["path"] for call in client.request.call_args_list] == [
111+
GITHUB_COMMENTS_PATH,
112+
]
113+
update_comment.assert_not_called()
114+
post_reaction.assert_not_called()
115+
client.post_telemetry_events.assert_not_called()
116+
117+
def test_ordinary_comment_without_security_comment_exits_0(self, monkeypatch):
118+
code, _, update_comment, _, _ = _run_comment_event(
119+
monkeypatch, {5: _comment("ship it", 5)},
120+
)
121+
122+
assert code == 0
123+
update_comment.assert_not_called()
124+
125+
def test_ignore_command_removes_only_that_package(self, monkeypatch):
126+
code, _, update_comment, post_reaction, client = _run_comment_event(
127+
monkeypatch,
128+
_security_and("first ordinary comment", "@SocketSecurity ignore npm/lodash@4.17.11"),
129+
)
130+
131+
assert code == 0
132+
update_comment.assert_called_once()
133+
body, comment_id = update_comment.call_args.args
134+
assert comment_id == "1"
135+
assert "start-socket-alert-npm/lodash@4.17.11" not in body
136+
assert "start-socket-alert-npm/handlebars@4.0.11" in body
137+
post_reaction.assert_called_once_with(3)
138+
events = client.post_telemetry_events.call_args.args[1]
139+
assert [e["artifact_input"] for e in events] == ["npm/lodash@4.17.11"]
140+
141+
def test_ignore_all_clears_the_table(self, monkeypatch):
142+
code, _, update_comment, post_reaction, client = _run_comment_event(
143+
monkeypatch, _security_and("@SocketSecurity ignore-all"),
144+
)
145+
146+
assert code == 0
147+
body = update_comment.call_args.args[0]
148+
assert "start-socket-alert" not in body
149+
assert "No dependency alerts to report" in body
150+
post_reaction.assert_called_once_with(2)
151+
events = client.post_telemetry_events.call_args.args[1]
152+
assert len(events) == 1 and events[0]["ignore_all"] is True
153+
154+
@pytest.mark.parametrize("command", [
155+
"@SocketSecurity ignore npm/lodash@4.17.11", "@SocketSecurity ignore-all", "LGTM",
156+
])
157+
def test_disable_ignore_skips_comment_processing(self, monkeypatch, command):
158+
code, get_comments, update_comment, post_reaction, client = _run_comment_event(
159+
monkeypatch, _security_and(command), extra_args=("--disable-ignore",),
160+
)
161+
162+
assert code == 0
163+
get_comments.assert_not_called()
164+
client.request.assert_not_called()
165+
update_comment.assert_not_called()
166+
post_reaction.assert_not_called()
167+
client.post_telemetry_events.assert_not_called()
168+
169+
def test_unauthorized_ignore_is_dropped_without_crashing(self, monkeypatch):
170+
code, _, update_comment, post_reaction, client = _run_comment_event(
171+
monkeypatch,
172+
_security_and("@SocketSecurity ignore npm/lodash@4.17.11"),
173+
permission="read",
174+
extra_args=("--strict-blocking",),
175+
)
176+
177+
assert code == 0
178+
assert [call.kwargs["path"] for call in client.request.call_args_list] == [
179+
GITHUB_COMMENTS_PATH,
180+
GITHUB_PERMISSION_PATH,
181+
]
182+
update_comment.assert_not_called()
183+
post_reaction.assert_not_called()
184+
client.post_telemetry_events.assert_not_called()
185+
186+
@pytest.mark.parametrize("command", [
187+
"@SocketSecurity ignore",
188+
"@SocketSecurity ignore lodash",
189+
"@SocketSecurity ignore @4.17.11",
190+
"@SocketSecurity ignore npm/lodash@",
191+
])
192+
def test_malformed_ignore_command_keeps_every_alert(self, monkeypatch, command):
193+
code, _, update_comment, _, _ = _run_comment_event(monkeypatch, _security_and(command))
194+
195+
assert code == 0
196+
body = update_comment.call_args.args[0]
197+
assert "start-socket-alert-npm/lodash@4.17.11" in body
198+
assert "start-socket-alert-npm/handlebars@4.0.11" in body
199+
200+
201+
class TestGetIgnoreOptions:
202+
def test_no_ignore_key(self):
203+
assert Comments.get_ignore_options({}) == (False, [])
204+
assert Comments.get_ignore_options({"security": _comment(SECURITY_COMMENT, 1)}) == (False, [])
205+
206+
def test_process_security_comment_without_ignore_key_keeps_alerts(self):
207+
security = _comment(SECURITY_COMMENT, 1)
208+
body = Comments.process_security_comment(security, {"security": security})
209+
210+
assert "start-socket-alert-npm/lodash@4.17.11" in body
211+
assert "start-socket-alert-npm/handlebars@4.0.11" in body
212+
213+
214+
class TestAdapterRemoveCommentAlerts:
215+
def _github(self):
216+
gh = Github.__new__(Github)
217+
gh.update_comment = Mock()
218+
gh.handle_ignore_reactions = Mock()
219+
return gh
220+
221+
def _gitlab(self):
222+
config = GitlabConfig(
223+
commit_sha="abc", api_url="https://gitlab.example.com/api/v4",
224+
project_dir=".", mr_source_branch="feature", mr_iid="7",
225+
mr_project_id=1, commit_message="", default_branch="main",
226+
project_name="repo", pipeline_source="merge_request_event",
227+
commit_author="dev", token="t", repository="repo", is_default_branch=False,
228+
headers={},
229+
)
230+
gl = Gitlab(client=MagicMock(), config=config)
231+
gl.update_comment = Mock()
232+
gl.handle_ignore_reactions = Mock()
233+
return gl
234+
235+
@pytest.mark.parametrize("make", ["_github", "_gitlab"])
236+
def test_no_ignore_comments_leaves_security_comment(self, make):
237+
scm = getattr(self, make)()
238+
scm.remove_comment_alerts({"security": _comment(SECURITY_COMMENT, 1)})
239+
240+
scm.update_comment.assert_not_called()
241+
scm.handle_ignore_reactions.assert_not_called()
242+
243+
@pytest.mark.parametrize("make", ["_github", "_gitlab"])
244+
def test_ignore_comment_rewrites_security_comment(self, make):
245+
scm = getattr(self, make)()
246+
comments = Comments.check_for_socket_comments({
247+
1: _comment(SECURITY_COMMENT, 1),
248+
2: _comment("@SocketSecurity ignore npm/handlebars@4.0.11", 2),
249+
})
250+
scm.remove_comment_alerts(comments)
251+
252+
body, comment_id = scm.update_comment.call_args.args
253+
assert comment_id == "1"
254+
assert "start-socket-alert-npm/handlebars@4.0.11" not in body
255+
assert "start-socket-alert-npm/lodash@4.17.11" in body
256+
scm.handle_ignore_reactions.assert_called_once_with(comments)

0 commit comments

Comments
 (0)