Skip to content

Commit 5f8b4a5

Browse files
committed
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.
1 parent 4250b5c commit 5f8b4a5

8 files changed

Lines changed: 271 additions & 4 deletions

File tree

‎CHANGELOG.md‎

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

3+
## 2.13.1
4+
5+
### Fixed
6+
7+
- With `--scm github`, an `issue_comment` run no longer exits `3` with
8+
`KeyError: 'ignore'` when the pull request has a Socket security comment but
9+
no `@SocketSecurity ignore` command. Any ordinary comment, or an ignore command
10+
from someone without write access, used to fail the job. These runs now exit
11+
`0` and leave the security comment unchanged.
12+
313
## 2.13.0
414

515
### Upgrade notes

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ build-backend = "hatchling.build"
66

77
[project]
88
name = "socketsecurity"
9-
version = "2.13.0"
9+
version = "2.13.1"
1010
requires-python = ">= 3.11"
1111
license = {"file" = "LICENSE"}
1212
dependencies = [

‎socketsecurity/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
__author__ = 'socket.dev'
2-
__version__ = '2.13.0'
2+
__version__ = '2.13.1'
33
USER_AGENT_NAME = 'socket-python-cli'
44
USER_AGENT = f'{USER_AGENT_NAME}/{__version__}'

‎socketsecurity/core/scm/github.py‎

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

336336
def remove_comment_alerts(self, comments: dict) -> None:
337+
if not comments.get("ignore"):
338+
log.info("No @SocketSecurity ignore commands on this pull request; security comment left unchanged")
339+
return
337340
if security_alert := comments.get("security"):
338341
new_body = Comments.process_security_comment(security_alert, comments)
339342
self.handle_ignore_reactions(comments)

‎socketsecurity/core/scm/gitlab.py‎

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

470470
def remove_comment_alerts(self, comments: dict):
471+
if not comments.get("ignore"):
472+
log.info("No @SocketSecurity ignore commands on this merge request; security comment left unchanged")
473+
return
471474
security_alert = comments.get("security")
472475
if security_alert is not None:
473476
# Type narrowing: after None check, mypy knows this is Comment

‎socketsecurity/core/scm_comments.py‎

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

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

‎uv.lock‎

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

0 commit comments

Comments
 (0)