Skip to content

Commit 8aa89ea

Browse files
committed
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.
1 parent 988cda1 commit 8aa89ea

3 files changed

Lines changed: 212 additions & 59 deletions

File tree

‎socketsecurity/core/scm/github.py‎

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,15 @@
1616

1717
# pull_request actions that can leave a PR head without a current Socket result:
1818
# new commits (opened, synchronize) and a PR coming back after it was closed or
19-
# drafted (reopened, ready_for_review). A required check takes the latest run on the
20-
# head commit, so a skipped run that exits 0 on one of these would replace an earlier
21-
# failure. Other actions (closed, labeled, edited, ...) are skipped with a warning.
19+
# drafted (reopened, ready_for_review). A skipped run exits 0, and GitHub doesn't
20+
# define which run a required check uses when the same job runs more than once on a
21+
# commit, so a skipped run on one of these could satisfy the check in place of an
22+
# earlier failure. Other actions (closed, labeled, edited, ...) are skipped with a
23+
# warning.
2224
PULL_REQUEST_SCAN_ACTIONS = ("opened", "synchronize", "reopened", "ready_for_review")
25+
HANDLED_EVENTS = (
26+
"push, workflow_dispatch and pull_request (scan); issue_comment (ignore commands)"
27+
)
2328

2429

2530
@dataclass
@@ -191,6 +196,14 @@ def check_event_type(self) -> str:
191196
action = (self.config.event_action or "").lower()
192197
if action in PULL_REQUEST_SCAN_ACTIONS:
193198
return "diff"
199+
if not action:
200+
log.warning(
201+
"Could not determine the pull_request action: EVENT_ACTION is not set "
202+
"and GITHUB_EVENT_PATH has no 'action'. No scan ran; exiting 0. Set "
203+
"EVENT_ACTION (or GITHUB_EVENT_PATH) when running with --scm github "
204+
"outside GitHub Actions."
205+
)
206+
sys.exit(0)
194207
log.warning(
195208
f"Pull request action '{self.config.event_action}' is not scanned "
196209
f"(scanned actions: {', '.join(PULL_REQUEST_SCAN_ACTIONS)}). No scan ran; "
@@ -211,11 +224,17 @@ def check_event_type(self) -> str:
211224
)
212225
sys.exit(0)
213226

227+
if not event_name:
228+
log.warning(
229+
"Could not determine the GitHub event: GITHUB_EVENT_NAME is not set. "
230+
"No scan ran; exiting 0. Set GITHUB_EVENT_NAME when running with "
231+
"--scm github outside GitHub Actions."
232+
)
233+
sys.exit(0)
214234
log.warning(
215-
f"GitHub event '{self.config.event_name}' is not scanned (scanned events: "
216-
"push, workflow_dispatch, pull_request, issue_comment). No scan ran; "
217-
"exiting 0. If this job is a required check, its success here does not "
218-
"reflect a scan."
235+
f"GitHub event '{self.config.event_name}' is not scanned (handled events: "
236+
f"{HANDLED_EVENTS}). No scan ran; exiting 0. If this job is a required "
237+
"check, its success here does not reflect a scan."
219238
)
220239
sys.exit(0)
221240

‎socketsecurity/core/scm/gitlab.py‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -213,12 +213,19 @@ def check_event_type(self) -> str:
213213
return "diff"
214214
elif pipeline_source == "issue_comment":
215215
return "comment"
216+
elif not pipeline_source:
217+
log.warning(
218+
"Could not determine the GitLab pipeline source: CI_PIPELINE_SOURCE is "
219+
"not set. No scan ran; exiting 0. Set CI_PIPELINE_SOURCE when running "
220+
"with --scm gitlab outside GitLab CI."
221+
)
222+
sys.exit(0)
216223
else:
217224
log.warning(
218225
f"GitLab pipeline source '{self.config.pipeline_source}' is not scanned "
219-
"(scanned sources: web, merge_request_event, push, api, pipeline, "
220-
"issue_comment). No scan ran; exiting 0. If this job gates merges, its "
221-
"success here does not reflect a scan."
226+
"(handled sources: web, merge_request_event, push, api and pipeline "
227+
"(scan); issue_comment (ignore commands)). No scan ran; exiting 0. If "
228+
"this job gates merges, its success here does not reflect a scan."
222229
)
223230
sys.exit(0)
224231

‎tests/unit/test_github_event_filter.py‎

Lines changed: 176 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
"""Which GitHub events and pull_request actions run a scan.
22
3-
A skipped run exits 0, and a required check takes the latest run on the head
4-
commit, so skipping an action that a workflow subscribes to can replace an
5-
earlier failure with a pass that never scanned anything.
3+
A skipped run exits 0, and GitHub doesn't define which run a required check uses
4+
when the same job runs more than once on a commit, so skipping an action that a
5+
workflow subscribes to can satisfy the check with a pass that never scanned
6+
anything.
67
"""
78

89
import logging
@@ -19,12 +20,24 @@
1920
Github,
2021
GithubConfig,
2122
)
23+
from socketsecurity.core.scm.gitlab import Gitlab, GitlabConfig
2224
from socketsecurity.core.scm_comments import Comments
2325

2426
CONTEXT_VARIABLES = (
25-
"BUILDKITE", "BUILDKITE_PULL_REQUEST", "DEFAULT_BRANCH", "EVENT_ACTION",
26-
"GITHUB_EVENT_NAME", "GITHUB_EVENT_PATH", "GITHUB_REPOSITORY", "PR_NUMBER",
27-
"SOCKET_SECURITY_API_KEY", "SOCKET_SECURITY_API_TOKEN", "SOCKET_API_KEY", "SOCKET_API_TOKEN",
27+
"BUILDKITE",
28+
"BUILDKITE_PULL_REQUEST",
29+
"DEFAULT_BRANCH",
30+
"EVENT_ACTION",
31+
"CI_MERGE_REQUEST_IID",
32+
"CI_PIPELINE_SOURCE",
33+
"GITHUB_EVENT_NAME",
34+
"GITHUB_EVENT_PATH",
35+
"GITHUB_REPOSITORY",
36+
"PR_NUMBER",
37+
"SOCKET_SECURITY_API_KEY",
38+
"SOCKET_SECURITY_API_TOKEN",
39+
"SOCKET_API_KEY",
40+
"SOCKET_API_TOKEN",
2841
)
2942

3043

@@ -36,88 +49,202 @@ def clear_context(monkeypatch):
3649
monkeypatch.setenv("GITHUB_REPOSITORY", "acme/repo")
3750

3851

39-
def _github(monkeypatch, event_name, action=None):
40-
monkeypatch.setenv("GITHUB_EVENT_NAME", event_name)
52+
def _github(monkeypatch, event_name, action=None, pr_number="7"):
53+
if event_name is not None:
54+
monkeypatch.setenv("GITHUB_EVENT_NAME", event_name)
4155
if action is not None:
4256
monkeypatch.setenv("EVENT_ACTION", action)
43-
return Github(client=object(), config=GithubConfig.from_env(pr_number="7"))
57+
return Github(client=object(), config=GithubConfig.from_env(pr_number=pr_number))
4458

4559

46-
@pytest.mark.parametrize("action", ["opened", "synchronize", "reopened", "ready_for_review", "Reopened"])
47-
def test_pull_request_actions_that_change_the_head_result_are_scanned(monkeypatch, action):
60+
def _skip_warnings(scm, caplog) -> list[str]:
61+
with (
62+
caplog.at_level(logging.INFO, logger="socketdev"),
63+
pytest.raises(SystemExit) as result,
64+
):
65+
scm.check_event_type()
66+
assert result.value.code == 0
67+
return [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING]
68+
69+
70+
@pytest.mark.parametrize(
71+
"action", ["opened", "synchronize", "reopened", "ready_for_review", "Reopened"]
72+
)
73+
def test_pull_request_actions_that_change_the_head_result_are_scanned(
74+
monkeypatch, action
75+
):
4876
assert _github(monkeypatch, "pull_request", action).check_event_type() == "diff"
4977

5078

5179
def test_scanned_actions_are_the_documented_set():
52-
assert PULL_REQUEST_SCAN_ACTIONS == ("opened", "synchronize", "reopened", "ready_for_review")
80+
assert PULL_REQUEST_SCAN_ACTIONS == (
81+
"opened",
82+
"synchronize",
83+
"reopened",
84+
"ready_for_review",
85+
)
86+
87+
88+
@pytest.mark.parametrize(
89+
"event_name, pr_number, expected",
90+
[
91+
("push", None, "main"),
92+
("push", "7", "diff"),
93+
("workflow_dispatch", None, "main"),
94+
("workflow_dispatch", "7", "diff"),
95+
("issue_comment", "7", "comment"),
96+
],
97+
)
98+
def test_other_handled_events_are_unchanged(
99+
monkeypatch, event_name, pr_number, expected
100+
):
101+
github = _github(monkeypatch, event_name, pr_number=pr_number)
102+
assert github.check_event_type() == expected
53103

54104

55-
@pytest.mark.parametrize("action", ["closed", "labeled", "edited", None])
105+
@pytest.mark.parametrize("action", ["closed", "labeled", "edited"])
56106
def test_other_pull_request_actions_skip_with_a_warning(monkeypatch, caplog, action):
57-
github = _github(monkeypatch, "pull_request", action)
107+
warnings = _skip_warnings(_github(monkeypatch, "pull_request", action), caplog)
58108

59-
with caplog.at_level(logging.INFO, logger="socketdev"), pytest.raises(SystemExit) as result:
60-
github.check_event_type()
109+
assert any(
110+
f"'{action}' is not scanned" in m and "No scan ran" in m for m in warnings
111+
)
61112

62-
assert result.value.code == 0
63-
warning = next(r for r in caplog.records if r.levelno == logging.WARNING)
64-
assert f"'{action}' is not scanned" in warning.getMessage()
65-
assert "No scan ran" in warning.getMessage()
66113

114+
def test_missing_pull_request_action_says_it_could_not_be_determined(
115+
monkeypatch, caplog
116+
):
117+
warnings = _skip_warnings(_github(monkeypatch, "pull_request"), caplog)
67118

68-
@pytest.mark.parametrize("event_name, expected", [
69-
("pull_request_target", "runs against the base branch"),
70-
("merge_group", "'merge_group' is not scanned"),
71-
("schedule", "'schedule' is not scanned"),
72-
])
73-
def test_unscanned_events_skip_with_a_warning(monkeypatch, caplog, event_name, expected):
74-
github = _github(monkeypatch, event_name, "opened")
119+
assert any(
120+
"Could not determine the pull_request action" in m and "No scan ran" in m
121+
for m in warnings
122+
)
123+
assert not any("is not scanned" in m for m in warnings)
75124

76-
with caplog.at_level(logging.INFO, logger="socketdev"), pytest.raises(SystemExit) as result:
77-
github.check_event_type()
78125

79-
assert result.value.code == 0
80-
warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING]
126+
def test_missing_event_name_says_it_could_not_be_determined(monkeypatch, caplog):
127+
warnings = _skip_warnings(_github(monkeypatch, None), caplog)
128+
129+
assert any(
130+
"GITHUB_EVENT_NAME is not set" in m and "No scan ran" in m for m in warnings
131+
)
132+
133+
134+
@pytest.mark.parametrize(
135+
"event_name, expected",
136+
[
137+
("pull_request_target", "runs against the base branch"),
138+
("merge_group", "'merge_group' is not scanned"),
139+
("schedule", "'schedule' is not scanned"),
140+
],
141+
)
142+
def test_unscanned_events_skip_with_a_warning(
143+
monkeypatch, caplog, event_name, expected
144+
):
145+
warnings = _skip_warnings(_github(monkeypatch, event_name, "opened"), caplog)
146+
147+
assert any(expected in message and "No scan ran" in message for message in warnings)
148+
# issue_comment is handled, but it runs the ignore-command flow, not a scan.
149+
if event_name != "pull_request_target":
150+
assert any("issue_comment (ignore commands)" in message for message in warnings)
151+
152+
153+
def _gitlab(monkeypatch, pipeline_source):
154+
monkeypatch.setenv("GITLAB_TOKEN", "test-token")
155+
if pipeline_source is not None:
156+
monkeypatch.setenv("CI_PIPELINE_SOURCE", pipeline_source)
157+
return Gitlab(client=object(), config=GitlabConfig.from_env())
158+
159+
160+
@pytest.mark.parametrize(
161+
"pipeline_source, expected",
162+
[
163+
("schedule", "'schedule' is not scanned"),
164+
(None, "CI_PIPELINE_SOURCE is not set"),
165+
],
166+
)
167+
def test_gitlab_skipped_sources_warn(monkeypatch, caplog, pipeline_source, expected):
168+
warnings = _skip_warnings(_gitlab(monkeypatch, pipeline_source), caplog)
169+
81170
assert any(expected in message and "No scan ran" in message for message in warnings)
82171

83172

84173
def _blocking_alert() -> Issue:
85174
return Issue(
86-
pkg_name="lodash", pkg_version="4.17.11", pkg_type="npm", severity="critical",
87-
title="Critical CVE", description="", type="criticalCVE", url="https://socket.dev/test",
88-
manifests="package.json", props={}, key="key", purl="pkg:npm/lodash@4.17.11",
89-
error=True, warn=False, ignore=False, monitor=False,
175+
pkg_name="lodash",
176+
pkg_version="4.17.11",
177+
pkg_type="npm",
178+
severity="critical",
179+
title="Critical CVE",
180+
description="",
181+
type="criticalCVE",
182+
url="https://socket.dev/test",
183+
manifests="package.json",
184+
props={},
185+
key="key",
186+
purl="pkg:npm/lodash@4.17.11",
187+
error=True,
188+
warn=False,
189+
ignore=False,
190+
monitor=False,
90191
)
91192

92193

93-
@pytest.mark.parametrize("action, scanned, expected_exit", [
94-
("reopened", True, 1),
95-
("ready_for_review", True, 1),
96-
("synchronize", True, 1),
97-
("closed", False, 0),
98-
])
99-
def test_reopened_pull_request_blocks_like_synchronize(monkeypatch, action, scanned, expected_exit):
194+
@pytest.mark.parametrize(
195+
"action, scanned, expected_exit",
196+
[
197+
("reopened", True, 1),
198+
("ready_for_review", True, 1),
199+
("synchronize", True, 1),
200+
("closed", False, 0),
201+
],
202+
)
203+
def test_reopened_pull_request_blocks_like_synchronize(
204+
monkeypatch, action, scanned, expected_exit
205+
):
100206
"""A reopened PR with an existing blocker fails instead of passing unscanned."""
101-
monkeypatch.setattr(sys, "argv", [
102-
"socketcli", "--api-token", "test", "--scm", "github", "--strict-blocking",
103-
"--repo", "repo", "--branch", "feature", "--pr-number", "7",
104-
"--files", '["package.json"]',
105-
])
207+
monkeypatch.setattr(
208+
sys,
209+
"argv",
210+
[
211+
"socketcli",
212+
"--api-token",
213+
"test",
214+
"--scm",
215+
"github",
216+
"--strict-blocking",
217+
"--repo",
218+
"repo",
219+
"--branch",
220+
"feature",
221+
"--pr-number",
222+
"7",
223+
"--files",
224+
'["package.json"]',
225+
],
226+
)
106227
monkeypatch.setenv("GITHUB_EVENT_NAME", "pull_request")
107228
monkeypatch.setenv("EVENT_ACTION", action)
108229
monkeypatch.setenv("DEFAULT_BRANCH", "false")
109230

110231
diff = Diff(id="scan", new_alerts=[], unchanged_alerts=[_blocking_alert()])
111232
diff.diff_url = "https://socket.dev/diff"
112-
monkeypatch.setattr(Github, "get_comments_for_pr", lambda self: Comments.check_for_socket_comments({}))
233+
monkeypatch.setattr(
234+
Github,
235+
"get_comments_for_pr",
236+
lambda self: Comments.check_for_socket_comments({}),
237+
)
113238
posted = Mock()
114239
monkeypatch.setattr(Github, "add_socket_comments", posted)
115240
monkeypatch.setattr(Github, "handle_ignore_reactions", Mock())
116241
sdk = MagicMock()
117242
sdk.org.get.return_value = {"organizations": {"org-id": {"slug": "acme"}}}
118243
monkeypatch.setattr(socketcli, "build_socket_sdk", Mock(return_value=sdk))
119244
monkeypatch.setattr(socketcli, "CliClient", Mock(return_value=Mock()))
120-
monkeypatch.setattr(socketcli, "StreamingLogs", lambda **kwargs: nullcontext(Mock()))
245+
monkeypatch.setattr(
246+
socketcli, "StreamingLogs", lambda **kwargs: nullcontext(Mock())
247+
)
121248
monkeypatch.setattr(socketcli, "apply_git_context", lambda config: (False, None))
122249
scan = Mock(return_value=diff)
123250
monkeypatch.setattr(socketcli.Core, "create_new_diff", scan)

0 commit comments

Comments
 (0)