Skip to content

Commit a5b1c93

Browse files
committed
Isolate the GitHub PR check and prepare CLI 2.14.0
1 parent c220223 commit a5b1c93

12 files changed

Lines changed: 181 additions & 127 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,22 @@
11
# Changelog
22

3-
## 2.13.3
3+
## 2.14.0
4+
5+
### Upgrade notes
6+
7+
- If you use the GitHub Actions example, replace the combined workflow with the
8+
[PR workflow](workflows/github-actions.yml) and require its `socket-security`
9+
check. Install the [push workflow](workflows/github-actions-push.yml) to keep
10+
branch scans and baseline updates. Install the
11+
[ignore-command workflow](workflows/github-actions-comments.yml) if you use PR
12+
ignore commands.
413

514
### Changed
615

716
- Updated the Socket Python SDK (`socketdev`) to 3.6.4. This can increase
817
advisory counts in full-scan JSON, SARIF, and GitLab security reports, and
918
in the existing findings shown in GitLab security and FOSSA diff reports.
19+
- Skipped GitHub events and GitLab pipeline sources now warn that no scan ran.
1020

1121
### Fixed
1222

@@ -18,6 +28,11 @@
1828
- With `--scm github`, reopened pull requests and pull requests marked ready for
1929
review run the PR scan.
2030

31+
### Documentation
32+
33+
- The [CI guide](docs/ci-cd.md#required-github-checks) describes GitHub required
34+
checks and the GitHub Actions workflow migration.
35+
2136
## 2.13.2
2237

2338
### Added

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,7 @@ JSON:
205205

206206
Prebuilt workflow examples:
207207

208-
- [GitHub Actions](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/github-actions.yml)
208+
- GitHub Actions for [pull requests](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/github-actions.yml), [pushes](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/github-actions-push.yml), and [ignore commands](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/github-actions-comments.yml)
209209
- [Buildkite](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/buildkite.yml)
210210
- [GitLab CI](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/gitlab-ci.yml)
211211
- [Bitbucket Pipelines](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/bitbucket-pipelines.yml)

‎docs/ci-cd.md‎

Lines changed: 40 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -504,8 +504,8 @@ With `--scm github` or `--scm gitlab`, the detected event decides the scan type:
504504

505505
| Event | Scan | Blocks the build |
506506
|:------|:-----|:-----------------|
507-
| Pull request / merge request | Diff scan against the repository's baseline | Yes, on new blocking alerts; also existing blockers with `--strict-blocking` |
508-
| Any other pipeline, including default-branch pushes | Full scan | No |
507+
| Supported pull request / merge request events | Diff scan against the repository's baseline when a comparison runs | Yes, on new blocking alerts and on existing blockers with `--strict-blocking` |
508+
| Push without a PR/MR number, including default-branch pushes | Full scan | No blocking on findings |
509509

510510
A full scan has no baseline, so it cannot tell a newly introduced alert from one
511511
that was already there. Rather than block on a number that would mean something
@@ -525,43 +525,43 @@ fetches the package list for them.
525525

526526
With `--scm github`, `pull_request` runs scan on the `opened`, `synchronize`,
527527
`reopened` and `ready_for_review` actions. Other actions (`closed`, `labeled`,
528-
`edited`, ...) and events the CLI does not handle (`pull_request_target`,
529-
`merge_group`, `schedule`, ...) are skipped: no scan runs, the CLI logs a warning
530-
and exits `0`. `issue_comment` runs the ignore-command flow, not a scan. With
531-
`--scm gitlab`, pipeline sources other than `web`, `merge_request_event`, `push`,
532-
`api`, `pipeline` and the comment flow are skipped the same way.
533-
534-
GitHub doesn't document which run a required check uses when a job with the same
535-
name runs more than once on a commit, so a skipped run that passes can satisfy the
536-
check in place of an earlier failure. Subscribe the Socket job only to events and
537-
actions the CLI scans.
538-
539-
- `merge_group`: if the required check also runs on merge queue events, the job
540-
passes there without scanning. The `pull_request` run is the gate.
541-
- `pull_request_target` is skipped because it runs against the base branch, so it
542-
can't stand in for `pull_request` on fork pull requests. Fork pull requests on
543-
`pull_request` get no repository secrets, so the CLI has no API token and exits
544-
`3` (or the `--exit-code-on-api-error` value). Decide how fork pull requests get
545-
a token before making the check required.
546-
547-
### Push and pull request runs on the same commit
548-
549-
The [example workflow](../workflows/github-actions.yml) runs one `socket-security`
550-
job on `push` to every branch and on `pull_request`. A new commit on a pull
551-
request's branch triggers both events on the same head commit. The `pull_request`
552-
run compares against the baseline and can fail. The `push` run is a full scan,
553-
which never blocks and exits `0`. Both runs report a check with the same name, so
554-
a required check can resolve against the passing `push` run.
555-
556-
If the Socket job is a required check, do one of these:
557-
558-
- Restrict `push` to the default branch (`branches: [main]`). Default-branch scans
559-
still keep the baseline current; feature branches are scanned only through their
560-
pull requests.
561-
- Run the pull request scan in its own job (for example `socket-pr` with
562-
`if: github.event_name == 'pull_request'`, and
563-
`if: github.event_name != 'pull_request'` on the existing job), and require that
564-
job's check.
528+
`edited`, and others) and unsupported events log a warning and exit `0` without
529+
scanning. `issue_comment` handles ignore commands. With `--scm gitlab`, the
530+
recognized scan sources are `web`, `merge_request_event`, `push`, `api`, and
531+
`pipeline`. Other sources, apart from the comment flow, also warn and exit `0`
532+
without scanning.
533+
534+
- A GitHub merge queue evaluates required checks on the `merge_group` commit.
535+
The CLI skips that event. Use a check that scans the merge group for
536+
[merge queue enforcement](https://docs.github.com/en/pull-requests/how-tos/merge-and-close-pull-requests/troubleshooting-required-status-checks#status-checks-with-github-actions-and-a-merge-queue).
537+
- GitHub runs `pull_request_target` in the base repository context, and the CLI
538+
skips it. Under GitHub's default fork settings, `pull_request` runs cannot
539+
access the Socket API secret. The CLI exits with its infrastructure error code
540+
if the token is missing. See GitHub's guidance for
541+
[securing workflows that handle fork PRs](https://docs.github.com/en/actions/reference/security/securely-using-pull_request_target).
542+
543+
### Required GitHub checks
544+
545+
Use the [PR workflow](../workflows/github-actions.yml) for the required
546+
`socket-security` check. If your workflow skips drafts, include
547+
`ready_for_review` in its `pull_request.types` so marking a PR ready starts the scan.
548+
Use the [push workflow](../workflows/github-actions-push.yml) to update the
549+
default-branch baseline and scan branch pushes. Use the
550+
[ignore-command workflow](../workflows/github-actions-comments.yml) if your
551+
repository handles ignore commands in PR comments.
552+
553+
GitHub normally checks the PR's test merge commit when it has a status and
554+
otherwise checks the head commit. The default PR checkout uses the test merge
555+
commit, while a push run uses the pushed commit. Keep the required job name
556+
exclusive to the PR workflow in either setup. A job skipped by a job-level
557+
`if` in a shared workflow can still report a successful check. See GitHub's
558+
[required status check rules](https://docs.github.com/en/pull-requests/how-tos/merge-and-close-pull-requests/troubleshooting-required-status-checks).
559+
560+
When replacing the combined example, copy the PR workflow to the existing
561+
workflow path and remove any other jobs named `socket-security`. Confirm the
562+
PR job reports the check named in branch protection. If you use
563+
`--strict-blocking` as a merge gate, verify a reopened PR with an existing
564+
Block alert fails and a completed clean comparison passes.
565565

566566
## Pull request and Dashboard association
567567

@@ -685,7 +685,7 @@ listed thinly or not at all.
685685

686686
Prebuilt examples in this repo:
687687

688-
- [`../workflows/github-actions.yml`](../workflows/github-actions.yml)
688+
- GitHub Actions for [pull requests](../workflows/github-actions.yml), [pushes](../workflows/github-actions-push.yml), and [ignore commands](../workflows/github-actions-comments.yml)
689689
- [`../workflows/buildkite.yml`](../workflows/buildkite.yml)
690690
- [`../workflows/gitlab-ci.yml`](../workflows/gitlab-ci.yml)
691691
- [`../workflows/bitbucket-pipelines.yml`](../workflows/bitbucket-pipelines.yml)

‎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.3"
9+
version = "2.14.0"
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.3'
2+
__version__ = '2.14.0'
33
USER_AGENT_NAME = 'socket-python-cli'
44
USER_AGENT = f'{USER_AGENT_NAME}/{__version__}'

‎socketsecurity/core/scm/github.py‎

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,7 @@
1414
from socketsecurity.exit_codes import InfrastructureError
1515
from socketsecurity.socketcli import CliClient
1616

17-
# pull_request actions that can leave a PR head without a current Socket result:
18-
# new commits (opened, synchronize) and a PR coming back after it was closed or
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.
17+
# Reopening a PR or marking it ready can require a fresh check on the same commit.
2418
PULL_REQUEST_SCAN_ACTIONS = ("opened", "synchronize", "reopened", "ready_for_review")
2519
HANDLED_EVENTS = (
2620
"push, workflow_dispatch and pull_request (scan); issue_comment (ignore commands)"
@@ -214,13 +208,16 @@ def check_event_type(self) -> str:
214208
elif event_name == "issue_comment":
215209
return "comment"
216210
elif event_name == "pull_request_target":
217-
# Not treated as pull_request on purpose: GITHUB_SHA and GITHUB_REF point at
218-
# the base branch and the default checkout is the base branch, so a "PR scan"
219-
# here would compare the base against itself and pass.
220211
log.warning(
221-
"GitHub event 'pull_request_target' is not scanned: it runs against the "
222-
"base branch, not the pull request head. No scan ran; exiting 0. Trigger "
223-
"the Socket job on pull_request instead."
212+
"GitHub event 'pull_request_target' is not scanned: it runs in the base "
213+
"repository context. No scan ran; exiting 0. Trigger the Socket PR check "
214+
"on pull_request."
215+
)
216+
sys.exit(0)
217+
elif event_name == "merge_group":
218+
log.warning(
219+
"GitHub event 'merge_group' is not scanned. No scan ran; exiting 0. "
220+
"A required merge queue check must scan the merge group commit."
224221
)
225222
sys.exit(0)
226223

‎tests/core/test_cli_exit_contract.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -287,7 +287,6 @@ def test_scm_event_filters_skip_without_scanning(cli_runtime, monkeypatch, caplo
287287
with caplog.at_level("INFO", logger="socketdev"):
288288
assert cli_runtime.run(["--scm", scm]) == 0
289289
cli_runtime.scan.assert_not_called()
290-
# A skipped run passes, so it has to say so where a required-check owner looks.
291290
assert any(
292291
record.levelname == "WARNING" and "No scan ran" in record.getMessage()
293292
for record in caplog.records

‎tests/unit/test_github_event_filter.py‎

Lines changed: 32 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,6 @@
1-
"""Which GitHub events and pull_request actions run a scan.
2-
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.
7-
"""
1+
"""GitHub and GitLab event routing and the CLI outcomes for GitHub PR actions."""
82

3+
import json
94
import logging
105
import sys
116
from contextlib import nullcontext
@@ -111,9 +106,14 @@ def test_other_pull_request_actions_skip_with_a_warning(monkeypatch, caplog, act
111106
)
112107

113108

109+
@pytest.mark.parametrize("has_payload", [False, True])
114110
def test_missing_pull_request_action_says_it_could_not_be_determined(
115-
monkeypatch, caplog
111+
monkeypatch, caplog, tmp_path, has_payload
116112
):
113+
if has_payload:
114+
event_path = tmp_path / "event.json"
115+
event_path.write_text("{}", encoding="utf-8")
116+
monkeypatch.setenv("GITHUB_EVENT_PATH", str(event_path))
117117
warnings = _skip_warnings(_github(monkeypatch, "pull_request"), caplog)
118118

119119
assert any(
@@ -134,8 +134,8 @@ def test_missing_event_name_says_it_could_not_be_determined(monkeypatch, caplog)
134134
@pytest.mark.parametrize(
135135
"event_name, expected",
136136
[
137-
("pull_request_target", "runs against the base branch"),
138-
("merge_group", "'merge_group' is not scanned"),
137+
("pull_request_target", "runs in the base repository context"),
138+
("merge_group", "A required merge queue check must scan the merge group commit"),
139139
("schedule", "'schedule' is not scanned"),
140140
],
141141
)
@@ -145,8 +145,7 @@ def test_unscanned_events_skip_with_a_warning(
145145
warnings = _skip_warnings(_github(monkeypatch, event_name, "opened"), caplog)
146146

147147
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":
148+
if event_name == "schedule":
150149
assert any("issue_comment (ignore commands)" in message for message in warnings)
151150

152151

@@ -192,18 +191,19 @@ def _blocking_alert() -> Issue:
192191

193192

194193
@pytest.mark.parametrize(
195-
"action, scanned, expected_exit",
194+
"action, has_blocker, scanned, expected_exit",
196195
[
197-
("reopened", True, 1),
198-
("ready_for_review", True, 1),
199-
("synchronize", True, 1),
200-
("closed", False, 0),
196+
("reopened", True, True, 1),
197+
("reopened", False, True, 0),
198+
("ready_for_review", True, True, 1),
199+
("ready_for_review", False, True, 0),
200+
("synchronize", True, True, 1),
201+
("closed", True, False, 0),
201202
],
202203
)
203-
def test_reopened_pull_request_blocks_like_synchronize(
204-
monkeypatch, action, scanned, expected_exit
204+
def test_pull_request_payload_drives_scan_and_exit(
205+
monkeypatch, tmp_path, action, has_blocker, scanned, expected_exit
205206
):
206-
"""A reopened PR with an existing blocker fails instead of passing unscanned."""
207207
monkeypatch.setattr(
208208
sys,
209209
"argv",
@@ -225,10 +225,13 @@ def test_reopened_pull_request_blocks_like_synchronize(
225225
],
226226
)
227227
monkeypatch.setenv("GITHUB_EVENT_NAME", "pull_request")
228-
monkeypatch.setenv("EVENT_ACTION", action)
228+
event_path = tmp_path / "event.json"
229+
event_path.write_text(json.dumps({"action": action}), encoding="utf-8")
230+
monkeypatch.setenv("GITHUB_EVENT_PATH", str(event_path))
229231
monkeypatch.setenv("DEFAULT_BRANCH", "false")
230232

231-
diff = Diff(id="scan", new_alerts=[], unchanged_alerts=[_blocking_alert()])
233+
existing_alerts = [_blocking_alert()] if has_blocker else []
234+
diff = Diff(id="scan", new_alerts=[], unchanged_alerts=existing_alerts)
232235
diff.diff_url = "https://socket.dev/diff"
233236
monkeypatch.setattr(
234237
Github,
@@ -248,12 +251,19 @@ def test_reopened_pull_request_blocks_like_synchronize(
248251
monkeypatch.setattr(socketcli, "apply_git_context", lambda config: (False, None))
249252
scan = Mock(return_value=diff)
250253
monkeypatch.setattr(socketcli.Core, "create_new_diff", scan)
254+
full_scan = Mock()
255+
monkeypatch.setattr(socketcli.Core, "create_full_scan_with_report_url", full_scan)
251256
monkeypatch.setattr(socketcli.Core, "has_manifest_files", Mock(return_value=True))
252257
monkeypatch.setattr(socketcli.OutputHandler, "handle_output", Mock())
253258

254259
with pytest.raises(SystemExit) as result:
255260
socketcli.cli()
256261

257262
assert result.value.code == expected_exit
263+
full_scan.assert_not_called()
258264
assert scan.called is scanned
259265
assert posted.called is scanned
266+
if scanned:
267+
scan.assert_called_once()
268+
posted.assert_called_once()
269+
assert posted.call_args.args[3] is has_blocker

‎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.
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Copy this workflow to .github/workflows/ to handle PR ignore commands.
2+
name: Socket Security Ignore Commands
3+
4+
on:
5+
issue_comment:
6+
types: [created]
7+
8+
concurrency:
9+
group: socket-ignore-${{ github.event.issue.number }}
10+
cancel-in-progress: false
11+
12+
jobs:
13+
socket-security-ignore:
14+
if: github.event.issue.pull_request
15+
permissions:
16+
contents: read
17+
issues: write
18+
pull-requests: write
19+
runs-on: ubuntu-latest
20+
container: socketdev/cli:latest
21+
steps:
22+
- uses: actions/checkout@v4
23+
with:
24+
fetch-depth: 0
25+
persist-credentials: false
26+
27+
- name: Handle Socket Security Ignore Commands
28+
env:
29+
SOCKET_SECURITY_API_KEY: ${{ secrets.SOCKET_SECURITY_API_KEY }}
30+
GH_API_TOKEN: ${{ secrets.GITHUB_TOKEN }}
31+
PR_NUMBER: ${{ github.event.issue.number }}
32+
run: |
33+
socketcli \
34+
--target-path "$GITHUB_WORKSPACE" \
35+
--scm github \
36+
--pr-number "$PR_NUMBER"

0 commit comments

Comments
 (0)