diff --git a/CHANGELOG.md b/CHANGELOG.md
index 165e42c..cac014b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,15 @@
# Changelog
+## 2.13.3
+
+### Fixed
+
+- With `--scm github`, an `issue_comment` run no longer exits `3` with
+ `KeyError: 'ignore'` when the pull request has a Socket security comment but
+ no `@SocketSecurity ignore` command. Any ordinary comment, or an ignore command
+ from someone without write access, used to fail the job. These runs now exit
+ `0` and leave the security comment unchanged.
+
## 2.13.2
### Added
diff --git a/pyproject.toml b/pyproject.toml
index 5c88c15..82c5bbf 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 7ba49e1..0871ade 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/socketsecurity/core/scm/github.py b/socketsecurity/core/scm/github.py
index 5248fc8..ed5a1e1 100644
--- a/socketsecurity/core/scm/github.py
+++ b/socketsecurity/core/scm/github.py
@@ -334,6 +334,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 on this pull request; security comment left unchanged")
+ 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 a7b2bd3..f72a6df 100644
--- a/socketsecurity/core/scm/gitlab.py
+++ b/socketsecurity/core/scm/gitlab.py
@@ -468,6 +468,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 on this merge request; security comment left unchanged")
+ 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 c794583..a369b50 100644
--- a/socketsecurity/core/scm_comments.py
+++ b/socketsecurity/core/scm_comments.py
@@ -59,7 +59,9 @@ def get_ignore_options(comments: dict) -> [bool, list]:
ignore_commands = []
ignore_all = False
- for comment in comments["ignore"]:
+ # check_for_socket_comments only adds the "ignore" key when the pull
+ # request has at least one honored ignore command, so it is often absent.
+ 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 0000000..5431678
--- /dev/null
+++ b/tests/unit/test_comment_event_flow.py
@@ -0,0 +1,249 @@
+"""The ``issue_comment`` / note flow: ordinary comments must not crash it.
+
+``check_for_socket_comments`` only adds an ``"ignore"`` key when the pull request
+has an honored ``@SocketSecurity ignore`` command. Any other comment on a pull
+request that already has a Socket security comment used to reach
+``get_ignore_options`` without that key and exit 3 with ``KeyError: 'ignore'``.
+"""
+
+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)",
+])
+
+
+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, *, authorized=True, extra_args=()):
+ """Run ``socketcli.cli()`` for a GitHub ``issue_comment`` event.
+
+ Returns the exit code and the mocks for the GitHub writes.
+ """
+ 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(side_effect=lambda: Comments.check_for_socket_comments(
+ raw_comments, is_authorized=lambda comment: authorized,
+ ))
+ monkeypatch.setattr(Github, "get_comments_for_pr", lambda self: get_comments())
+ 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()
+ 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),
+ )
+
+ assert code == 0
+ get_comments.assert_called_once()
+ 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()
+ 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):
+ """A rejected command leaves no "ignore" key, the same shape as an ordinary comment."""
+ code, _, update_comment, post_reaction, _ = _run_comment_event(
+ monkeypatch,
+ _security_and("@SocketSecurity ignore npm/lodash@4.17.11"),
+ authorized=False,
+ )
+
+ assert code == 0
+ update_comment.assert_not_called()
+ post_reaction.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)
diff --git a/uv.lock b/uv.lock
index 196ae3c..b3681e4 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" },