Skip to content

Commit a38c880

Browse files
dc-larsenlelia
andauthored
Scan reopened pull requests instead of passing them unscanned (#460)
* Scan reopened pull requests instead of passing them unscanned With --scm github, a pull_request run whose action was not opened or synchronize logged "Pull Request Action reopened is not a supported type" and exited 0 without scanning. The example workflow subscribes to reopened, and a required check takes the latest run on the head commit, so reopening a pull request could replace a failed Socket check with a pass on the same commit. reopened and ready_for_review now run the same comparison as opened and synchronize. Other actions and unhandled events are still skipped with exit 0, as the exit-code contract documents, but log a warning that no scan ran. pull_request_target gets its own message because it runs against the base branch, so it is not treated as pull_request. GitLab's unhandled pipeline sources log the same warning. * 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. * Document the push/pull_request overlap in the example workflow Move the Skipped events section below the scan-type paragraphs it had split. State the required-check risk without claiming which run GitHub picks. Explain that push on every branch also runs the job on a pull request's head commit as a full scan that exits 0, and give two ways to keep that run from satisfying a required check. * Bump version to 2.13.3 2.13.2 was released from main, so this change needs the next patch version. * Isolate the GitHub PR check and prepare CLI 2.14.0 * Warn that the PR workflow alone stops baseline updates --------- Co-authored-by: lelia <2418071+lelia@users.noreply.github.com>
1 parent e966d9e commit a38c880

10 files changed

Lines changed: 488 additions & 55 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,21 @@
88
even when no manifest changed. This includes default-branch pushes and scans of
99
non-git paths. These runs can now fail on Block findings or comparison errors
1010
and need the [API token scopes for comparison runs](docs/troubleshooting.md#api-token-permissions).
11+
- If you use the GitHub Actions example, replace the combined workflow with the
12+
[PR workflow](workflows/github-actions.yml) and require its `socket-security`
13+
check. Install the [push workflow](workflows/github-actions-push.yml) in the
14+
same change: the PR workflow doesn't run on pushes, so without it the
15+
default-branch baseline stops updating and PR comparisons run against an old
16+
scan. Install the
17+
[ignore-command workflow](workflows/github-actions-comments.yml) if you use PR
18+
ignore commands.
1119

1220
### Changed
1321

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

1827
### Fixed
1928

@@ -28,6 +37,13 @@
2837
- `--strict-blocking` checks existing Block findings on code-only changes.
2938
GitHub and GitLab pull request comments show those findings under Existing
3039
alerts.
40+
- With `--scm github`, reopened pull requests and pull requests marked ready for
41+
review run the PR scan.
42+
43+
### Documentation
44+
45+
- The [CI guide](docs/ci-cd.md#required-github-checks) describes GitHub required
46+
checks and the GitHub Actions workflow migration.
3147

3248
## 2.13.2
3349

‎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: 51 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -84,8 +84,9 @@ they also hide findings and usage errors. Even with exit `0`, a setup/API failur
8484
does not mean a clean scan; check the logs for a completed report.
8585

8686
Findings block only when a [diff comparison runs](#scan-type-by-pipeline).
87-
SCM event filters can also skip unsupported events with exit `0`; confirm a report
88-
was created when validating a new workflow.
87+
SCM event filters can also skip unsupported events with exit `0` and a warning
88+
(see [Skipped events](#skipped-events)); confirm a report was created when
89+
validating a new workflow.
8990
The CLI treats comparisons marked incomplete or returned with missing or
9091
invalid package lists as infrastructure failures. With `--strict-blocking`,
9192
incomplete existing-alert data is also an infrastructure failure. See the
@@ -506,8 +507,8 @@ comparison path.
506507

507508
| Event | Scan | Blocks the build |
508509
|:------|:-----|:-----------------|
509-
| Pull request / merge request | Diff scan against the repository's baseline | Yes, on new blocking alerts; also existing blockers with `--strict-blocking` |
510-
| Any other pipeline, including default-branch pushes | Full scan | No |
510+
| 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` |
511+
| Push without a PR/MR number, including default-branch pushes | Full scan | No blocking on findings |
511512

512513
With changed-file detection, a PR/MR with no supported manifest change runs a
513514
full scan by default. Use `--strict-blocking` or `--ignore-commit-files` to
@@ -524,6 +525,51 @@ when upgrading a pipeline that previously ran only full scans.
524525
`--generate-license` and `--legal-format fossa` work on both paths; a full scan
525526
fetches the package list for them.
526527

528+
### Skipped events
529+
530+
With `--scm github`, `pull_request` runs scan on the `opened`, `synchronize`,
531+
`reopened` and `ready_for_review` actions. Other actions (`closed`, `labeled`,
532+
`edited`, and others) and unsupported events log a warning and exit `0` without
533+
scanning. `issue_comment` handles ignore commands. With `--scm gitlab`, the
534+
recognized scan sources are `web`, `merge_request_event`, `push`, `api`, and
535+
`pipeline`. Other sources, apart from the comment flow, also warn and exit `0`
536+
without scanning.
537+
538+
- A GitHub merge queue evaluates required checks on the `merge_group` commit.
539+
The CLI skips that event. Use a check that scans the merge group for
540+
[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).
541+
- GitHub runs `pull_request_target` in the base repository context, and the CLI
542+
skips it. Under GitHub's default fork settings, `pull_request` runs cannot
543+
access the Socket API secret. The CLI exits with its infrastructure error code
544+
if the token is missing. See GitHub's guidance for
545+
[securing workflows that handle fork PRs](https://docs.github.com/en/actions/reference/security/securely-using-pull_request_target).
546+
547+
### Required GitHub checks
548+
549+
Use the [PR workflow](../workflows/github-actions.yml) for the required
550+
`socket-security` check. If your workflow skips drafts, include
551+
`ready_for_review` in its `pull_request.types` so marking a PR ready starts the scan.
552+
Use the [push workflow](../workflows/github-actions-push.yml) to update the
553+
default-branch baseline and scan branch pushes. Use the
554+
[ignore-command workflow](../workflows/github-actions-comments.yml) if your
555+
repository handles ignore commands in PR comments.
556+
557+
GitHub normally checks the PR's test merge commit when it has a status and
558+
otherwise checks the head commit. The default PR checkout uses the test merge
559+
commit, while a push run uses the pushed commit. Keep the required job name
560+
exclusive to the PR workflow in either setup. A job skipped by a job-level
561+
`if` in a shared workflow can still report a successful check. See GitHub's
562+
[required status check rules](https://docs.github.com/en/pull-requests/how-tos/merge-and-close-pull-requests/troubleshooting-required-status-checks).
563+
564+
When replacing the combined example, copy the PR workflow to the existing
565+
workflow path and remove any other jobs named `socket-security`. Confirm the
566+
PR job reports the check named in branch protection. Add the push workflow in
567+
the same change: the PR workflow doesn't run on pushes, so without it the
568+
default-branch baseline stops updating and later PR comparisons run against an
569+
old scan. If you use
570+
`--strict-blocking` as a merge gate, verify a reopened PR with an existing
571+
Block alert fails and a completed clean comparison passes.
572+
527573
## Pull request and Dashboard association
528574

529575
The CLI sends the resolved pull request number with each full scan and attaches
@@ -646,7 +692,7 @@ listed thinly or not at all.
646692

647693
Prebuilt examples in this repo:
648694

649-
- [`../workflows/github-actions.yml`](../workflows/github-actions.yml)
695+
- GitHub Actions for [pull requests](../workflows/github-actions.yml), [pushes](../workflows/github-actions-push.yml), and [ignore commands](../workflows/github-actions-comments.yml)
650696
- [`../workflows/buildkite.yml`](../workflows/buildkite.yml)
651697
- [`../workflows/gitlab-ci.yml`](../workflows/gitlab-ci.yml)
652698
- [`../workflows/bitbucket-pipelines.yml`](../workflows/bitbucket-pipelines.yml)

‎socketsecurity/core/scm/github.py‎

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

17+
# Reopening a PR or marking it ready can require a fresh check on the same commit.
18+
PULL_REQUEST_SCAN_ACTIONS = ("opened", "synchronize", "reopened", "ready_for_review")
19+
HANDLED_EVENTS = (
20+
"push, workflow_dispatch and pull_request (scan); issue_comment (ignore commands)"
21+
)
22+
1723

1824
@dataclass
1925
class GithubConfig:
@@ -175,19 +181,58 @@ def __init__(
175181
raise InfrastructureError("Unable to get Github API Token")
176182

177183
def check_event_type(self) -> str:
178-
if self.config.event_name.lower() in ["push", "workflow_dispatch"]:
184+
event_name = self.config.event_name.lower()
185+
if event_name in ["push", "workflow_dispatch"]:
179186
if not self.config.pr_number:
180187
return "main"
181188
return "diff"
182-
elif self.config.event_name.lower() == "pull_request":
183-
if self.config.event_action and self.config.event_action.lower() in ['opened', 'synchronize']:
189+
elif event_name == "pull_request":
190+
action = (self.config.event_action or "").lower()
191+
if action in PULL_REQUEST_SCAN_ACTIONS:
184192
return "diff"
185-
log.info(f"Pull Request Action {self.config.event_action} is not a supported type")
193+
if not action:
194+
log.warning(
195+
"Could not determine the pull_request action: EVENT_ACTION is not set "
196+
"and GITHUB_EVENT_PATH has no 'action'. No scan ran; exiting 0. Set "
197+
"EVENT_ACTION (or GITHUB_EVENT_PATH) when running with --scm github "
198+
"outside GitHub Actions."
199+
)
200+
sys.exit(0)
201+
log.warning(
202+
f"Pull request action '{self.config.event_action}' is not scanned "
203+
f"(scanned actions: {', '.join(PULL_REQUEST_SCAN_ACTIONS)}). No scan ran; "
204+
"exiting 0. If this job is a required check, its success here does not "
205+
"reflect a scan: remove this action from the workflow's pull_request types."
206+
)
186207
sys.exit(0)
187-
elif self.config.event_name.lower() == "issue_comment":
208+
elif event_name == "issue_comment":
188209
return "comment"
210+
elif event_name == "pull_request_target":
211+
log.warning(
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."
221+
)
222+
sys.exit(0)
189223

190-
log.error(f"Unknown event type {self.config.event_name}")
224+
if not event_name:
225+
log.warning(
226+
"Could not determine the GitHub event: GITHUB_EVENT_NAME is not set. "
227+
"No scan ran; exiting 0. Set GITHUB_EVENT_NAME when running with "
228+
"--scm github outside GitHub Actions."
229+
)
230+
sys.exit(0)
231+
log.warning(
232+
f"GitHub event '{self.config.event_name}' is not scanned (handled events: "
233+
f"{HANDLED_EVENTS}). No scan ran; exiting 0. If this job is a required "
234+
"check, its success here does not reflect a scan."
235+
)
191236
sys.exit(0)
192237

193238
def post_comment(self, body: str) -> None:

‎socketsecurity/core/scm/gitlab.py‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -213,8 +213,20 @@ 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:
217-
log.error(f"Unknown event type {pipeline_source}")
224+
log.warning(
225+
f"GitLab pipeline source '{self.config.pipeline_source}' is not scanned "
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."
229+
)
218230
sys.exit(0)
219231

220232
def post_comment(self, body: str) -> None:

‎tests/core/test_cli_exit_contract.py‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -275,14 +275,19 @@ def test_branch_full_scan_does_not_gate_on_findings(cli_runtime, monkeypatch, ou
275275

276276
@pytest.mark.parametrize("scm, event, action", [
277277
("github", "pull_request", "closed"), ("github", "unsupported", ""),
278-
("gitlab", "unsupported", ""),
278+
("github", "pull_request_target", "opened"), ("gitlab", "unsupported", ""),
279279
])
280-
def test_scm_event_filters_skip_without_scanning(cli_runtime, monkeypatch, scm, event, action):
280+
def test_scm_event_filters_skip_without_scanning(cli_runtime, monkeypatch, caplog, scm, event, action):
281281
monkeypatch.setenv("GH_API_TOKEN", "test")
282282
monkeypatch.setenv("GITLAB_TOKEN", "test")
283283
monkeypatch.setenv("GITHUB_EVENT_NAME", event)
284284
monkeypatch.setenv("EVENT_ACTION", action)
285285
monkeypatch.setenv("CI_PIPELINE_SOURCE", event)
286286

287-
assert cli_runtime.run(["--scm", scm]) == 0
287+
with caplog.at_level("INFO", logger="socketdev"):
288+
assert cli_runtime.run(["--scm", scm]) == 0
288289
cli_runtime.scan.assert_not_called()
290+
assert any(
291+
record.levelname == "WARNING" and "No scan ran" in record.getMessage()
292+
for record in caplog.records
293+
)

0 commit comments

Comments
 (0)