Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

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

### Changed

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

### Fixed

Expand All @@ -28,6 +37,13 @@
- `--strict-blocking` checks existing Block findings on code-only changes.
GitHub and GitLab pull request comments show those findings under Existing
alerts.
- With `--scm github`, reopened pull requests and pull requests marked ready for
review run the PR scan.

### Documentation

- The [CI guide](docs/ci-cd.md#required-github-checks) describes GitHub required
checks and the GitHub Actions workflow migration.

## 2.13.2

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ JSON:

Prebuilt workflow examples:

- [GitHub Actions](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/github-actions.yml)
- 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)
- [Buildkite](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/buildkite.yml)
- [GitLab CI](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/gitlab-ci.yml)
- [Bitbucket Pipelines](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/bitbucket-pipelines.yml)
Expand Down
56 changes: 51 additions & 5 deletions docs/ci-cd.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,9 @@ they also hide findings and usage errors. Even with exit `0`, a setup/API failur
does not mean a clean scan; check the logs for a completed report.

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

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

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

### Skipped events

With `--scm github`, `pull_request` runs scan on the `opened`, `synchronize`,
`reopened` and `ready_for_review` actions. Other actions (`closed`, `labeled`,
`edited`, and others) and unsupported events log a warning and exit `0` without
scanning. `issue_comment` handles ignore commands. With `--scm gitlab`, the
recognized scan sources are `web`, `merge_request_event`, `push`, `api`, and
`pipeline`. Other sources, apart from the comment flow, also warn and exit `0`
without scanning.

- A GitHub merge queue evaluates required checks on the `merge_group` commit.
The CLI skips that event. Use a check that scans the merge group for
[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).
- GitHub runs `pull_request_target` in the base repository context, and the CLI
skips it. Under GitHub's default fork settings, `pull_request` runs cannot
access the Socket API secret. The CLI exits with its infrastructure error code
if the token is missing. See GitHub's guidance for
[securing workflows that handle fork PRs](https://docs.github.com/en/actions/reference/security/securely-using-pull_request_target).

### Required GitHub checks

Use the [PR workflow](../workflows/github-actions.yml) for the required
`socket-security` check. If your workflow skips drafts, include
`ready_for_review` in its `pull_request.types` so marking a PR ready starts the scan.
Use the [push workflow](../workflows/github-actions-push.yml) to update the
default-branch baseline and scan branch pushes. Use the
[ignore-command workflow](../workflows/github-actions-comments.yml) if your
repository handles ignore commands in PR comments.

GitHub normally checks the PR's test merge commit when it has a status and
otherwise checks the head commit. The default PR checkout uses the test merge
commit, while a push run uses the pushed commit. Keep the required job name
exclusive to the PR workflow in either setup. A job skipped by a job-level
`if` in a shared workflow can still report a successful check. See GitHub's
[required status check rules](https://docs.github.com/en/pull-requests/how-tos/merge-and-close-pull-requests/troubleshooting-required-status-checks).

When replacing the combined example, copy the PR workflow to the existing
workflow path and remove any other jobs named `socket-security`. Confirm the
PR job reports the check named in branch protection. Add the push workflow in
the same change: the PR workflow doesn't run on pushes, so without it the
default-branch baseline stops updating and later PR comparisons run against an
old scan. If you use
`--strict-blocking` as a merge gate, verify a reopened PR with an existing
Block alert fails and a completed clean comparison passes.

## Pull request and Dashboard association

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

Prebuilt examples in this repo:

- [`../workflows/github-actions.yml`](../workflows/github-actions.yml)
- GitHub Actions for [pull requests](../workflows/github-actions.yml), [pushes](../workflows/github-actions-push.yml), and [ignore commands](../workflows/github-actions-comments.yml)
- [`../workflows/buildkite.yml`](../workflows/buildkite.yml)
- [`../workflows/gitlab-ci.yml`](../workflows/gitlab-ci.yml)
- [`../workflows/bitbucket-pipelines.yml`](../workflows/bitbucket-pipelines.yml)
Expand Down
57 changes: 51 additions & 6 deletions socketsecurity/core/scm/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@
from socketsecurity.exit_codes import InfrastructureError
from socketsecurity.socketcli import CliClient

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


@dataclass
class GithubConfig:
Expand Down Expand Up @@ -175,19 +181,58 @@ def __init__(
raise InfrastructureError("Unable to get Github API Token")

def check_event_type(self) -> str:
if self.config.event_name.lower() in ["push", "workflow_dispatch"]:
event_name = self.config.event_name.lower()
if event_name in ["push", "workflow_dispatch"]:
if not self.config.pr_number:
return "main"
return "diff"
elif self.config.event_name.lower() == "pull_request":
if self.config.event_action and self.config.event_action.lower() in ['opened', 'synchronize']:
elif event_name == "pull_request":
action = (self.config.event_action or "").lower()
if action in PULL_REQUEST_SCAN_ACTIONS:
return "diff"
log.info(f"Pull Request Action {self.config.event_action} is not a supported type")
if not action:
log.warning(
"Could not determine the pull_request action: EVENT_ACTION is not set "
"and GITHUB_EVENT_PATH has no 'action'. No scan ran; exiting 0. Set "
"EVENT_ACTION (or GITHUB_EVENT_PATH) when running with --scm github "
"outside GitHub Actions."
)
sys.exit(0)
log.warning(
f"Pull request action '{self.config.event_action}' is not scanned "
f"(scanned actions: {', '.join(PULL_REQUEST_SCAN_ACTIONS)}). No scan ran; "
"exiting 0. If this job is a required check, its success here does not "
"reflect a scan: remove this action from the workflow's pull_request types."
)
sys.exit(0)
elif self.config.event_name.lower() == "issue_comment":
elif event_name == "issue_comment":
return "comment"
elif event_name == "pull_request_target":
log.warning(
"GitHub event 'pull_request_target' is not scanned: it runs in the base "
"repository context. No scan ran; exiting 0. Trigger the Socket PR check "
"on pull_request."
)
sys.exit(0)
elif event_name == "merge_group":
log.warning(
"GitHub event 'merge_group' is not scanned. No scan ran; exiting 0. "
"A required merge queue check must scan the merge group commit."
)
sys.exit(0)

log.error(f"Unknown event type {self.config.event_name}")
if not event_name:
log.warning(
"Could not determine the GitHub event: GITHUB_EVENT_NAME is not set. "
"No scan ran; exiting 0. Set GITHUB_EVENT_NAME when running with "
"--scm github outside GitHub Actions."
)
sys.exit(0)
log.warning(
f"GitHub event '{self.config.event_name}' is not scanned (handled events: "
f"{HANDLED_EVENTS}). No scan ran; exiting 0. If this job is a required "
"check, its success here does not reflect a scan."
)
sys.exit(0)

def post_comment(self, body: str) -> None:
Expand Down
14 changes: 13 additions & 1 deletion socketsecurity/core/scm/gitlab.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,8 +213,20 @@ def check_event_type(self) -> str:
return "diff"
elif pipeline_source == "issue_comment":
return "comment"
elif not pipeline_source:
log.warning(
"Could not determine the GitLab pipeline source: CI_PIPELINE_SOURCE is "
"not set. No scan ran; exiting 0. Set CI_PIPELINE_SOURCE when running "
"with --scm gitlab outside GitLab CI."
)
sys.exit(0)
else:
log.error(f"Unknown event type {pipeline_source}")
log.warning(
f"GitLab pipeline source '{self.config.pipeline_source}' is not scanned "
"(handled sources: web, merge_request_event, push, api and pipeline "
"(scan); issue_comment (ignore commands)). No scan ran; exiting 0. If "
"this job gates merges, its success here does not reflect a scan."
)
sys.exit(0)

def post_comment(self, body: str) -> None:
Expand Down
11 changes: 8 additions & 3 deletions tests/core/test_cli_exit_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,14 +275,19 @@ def test_branch_full_scan_does_not_gate_on_findings(cli_runtime, monkeypatch, ou

@pytest.mark.parametrize("scm, event, action", [
("github", "pull_request", "closed"), ("github", "unsupported", ""),
("gitlab", "unsupported", ""),
("github", "pull_request_target", "opened"), ("gitlab", "unsupported", ""),
])
def test_scm_event_filters_skip_without_scanning(cli_runtime, monkeypatch, scm, event, action):
def test_scm_event_filters_skip_without_scanning(cli_runtime, monkeypatch, caplog, scm, event, action):
monkeypatch.setenv("GH_API_TOKEN", "test")
monkeypatch.setenv("GITLAB_TOKEN", "test")
monkeypatch.setenv("GITHUB_EVENT_NAME", event)
monkeypatch.setenv("EVENT_ACTION", action)
monkeypatch.setenv("CI_PIPELINE_SOURCE", event)

assert cli_runtime.run(["--scm", scm]) == 0
with caplog.at_level("INFO", logger="socketdev"):
assert cli_runtime.run(["--scm", scm]) == 0
cli_runtime.scan.assert_not_called()
assert any(
record.levelname == "WARNING" and "No scan ran" in record.getMessage()
for record in caplog.records
)
Loading