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
89import logging
1920 Github ,
2021 GithubConfig ,
2122)
23+ from socketsecurity .core .scm .gitlab import Gitlab , GitlabConfig
2224from socketsecurity .core .scm_comments import Comments
2325
2426CONTEXT_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
5179def 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" ])
56106def 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
84173def _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