diff --git a/CHANGELOG.md b/CHANGELOG.md index 4bdc33ab..9fd7d533 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 @@ -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 diff --git a/README.md b/README.md index aa22735c..70152cfc 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/docs/ci-cd.md b/docs/ci-cd.md index 7eb26af9..ebb6e6c4 100644 --- a/docs/ci-cd.md +++ b/docs/ci-cd.md @@ -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 @@ -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 @@ -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 @@ -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) diff --git a/socketsecurity/core/scm/github.py b/socketsecurity/core/scm/github.py index 5248fc87..0dd45f01 100644 --- a/socketsecurity/core/scm/github.py +++ b/socketsecurity/core/scm/github.py @@ -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: @@ -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: diff --git a/socketsecurity/core/scm/gitlab.py b/socketsecurity/core/scm/gitlab.py index a7b2bd3a..4c9cdbf6 100644 --- a/socketsecurity/core/scm/gitlab.py +++ b/socketsecurity/core/scm/gitlab.py @@ -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: diff --git a/tests/core/test_cli_exit_contract.py b/tests/core/test_cli_exit_contract.py index d3988f91..0ac35be9 100644 --- a/tests/core/test_cli_exit_contract.py +++ b/tests/core/test_cli_exit_contract.py @@ -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 + ) diff --git a/tests/unit/test_github_event_filter.py b/tests/unit/test_github_event_filter.py new file mode 100644 index 00000000..b394ffb6 --- /dev/null +++ b/tests/unit/test_github_event_filter.py @@ -0,0 +1,269 @@ +"""GitHub and GitLab event routing and the CLI outcomes for GitHub PR actions.""" + +import json +import logging +import sys +from contextlib import nullcontext +from unittest.mock import MagicMock, Mock + +import pytest + +from socketsecurity import socketcli +from socketsecurity.core.classes import Diff, Issue +from socketsecurity.core.scm.github import ( + PULL_REQUEST_SCAN_ACTIONS, + Github, + GithubConfig, +) +from socketsecurity.core.scm.gitlab import Gitlab, GitlabConfig +from socketsecurity.core.scm_comments import Comments + +CONTEXT_VARIABLES = ( + "BUILDKITE", + "BUILDKITE_PULL_REQUEST", + "DEFAULT_BRANCH", + "EVENT_ACTION", + "CI_MERGE_REQUEST_IID", + "CI_PIPELINE_SOURCE", + "GITHUB_EVENT_NAME", + "GITHUB_EVENT_PATH", + "GITHUB_REPOSITORY", + "PR_NUMBER", + "SOCKET_SECURITY_API_KEY", + "SOCKET_SECURITY_API_TOKEN", + "SOCKET_API_KEY", + "SOCKET_API_TOKEN", +) + + +@pytest.fixture(autouse=True) +def clear_context(monkeypatch): + for variable in CONTEXT_VARIABLES: + monkeypatch.delenv(variable, raising=False) + monkeypatch.setenv("GH_API_TOKEN", "test-token") + monkeypatch.setenv("GITHUB_REPOSITORY", "acme/repo") + + +def _github(monkeypatch, event_name, action=None, pr_number="7"): + if event_name is not None: + monkeypatch.setenv("GITHUB_EVENT_NAME", event_name) + if action is not None: + monkeypatch.setenv("EVENT_ACTION", action) + return Github(client=object(), config=GithubConfig.from_env(pr_number=pr_number)) + + +def _skip_warnings(scm, caplog) -> list[str]: + with ( + caplog.at_level(logging.INFO, logger="socketdev"), + pytest.raises(SystemExit) as result, + ): + scm.check_event_type() + assert result.value.code == 0 + return [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING] + + +@pytest.mark.parametrize( + "action", ["opened", "synchronize", "reopened", "ready_for_review", "Reopened"] +) +def test_pull_request_actions_that_change_the_head_result_are_scanned( + monkeypatch, action +): + assert _github(monkeypatch, "pull_request", action).check_event_type() == "diff" + + +def test_scanned_actions_are_the_documented_set(): + assert PULL_REQUEST_SCAN_ACTIONS == ( + "opened", + "synchronize", + "reopened", + "ready_for_review", + ) + + +@pytest.mark.parametrize( + "event_name, pr_number, expected", + [ + ("push", None, "main"), + ("push", "7", "diff"), + ("workflow_dispatch", None, "main"), + ("workflow_dispatch", "7", "diff"), + ("issue_comment", "7", "comment"), + ], +) +def test_other_handled_events_are_unchanged( + monkeypatch, event_name, pr_number, expected +): + github = _github(monkeypatch, event_name, pr_number=pr_number) + assert github.check_event_type() == expected + + +@pytest.mark.parametrize("action", ["closed", "labeled", "edited"]) +def test_other_pull_request_actions_skip_with_a_warning(monkeypatch, caplog, action): + warnings = _skip_warnings(_github(monkeypatch, "pull_request", action), caplog) + + assert any( + f"'{action}' is not scanned" in m and "No scan ran" in m for m in warnings + ) + + +@pytest.mark.parametrize("has_payload", [False, True]) +def test_missing_pull_request_action_says_it_could_not_be_determined( + monkeypatch, caplog, tmp_path, has_payload +): + if has_payload: + event_path = tmp_path / "event.json" + event_path.write_text("{}", encoding="utf-8") + monkeypatch.setenv("GITHUB_EVENT_PATH", str(event_path)) + warnings = _skip_warnings(_github(monkeypatch, "pull_request"), caplog) + + assert any( + "Could not determine the pull_request action" in m and "No scan ran" in m + for m in warnings + ) + assert not any("is not scanned" in m for m in warnings) + + +def test_missing_event_name_says_it_could_not_be_determined(monkeypatch, caplog): + warnings = _skip_warnings(_github(monkeypatch, None), caplog) + + assert any( + "GITHUB_EVENT_NAME is not set" in m and "No scan ran" in m for m in warnings + ) + + +@pytest.mark.parametrize( + "event_name, expected", + [ + ("pull_request_target", "runs in the base repository context"), + ("merge_group", "A required merge queue check must scan the merge group commit"), + ("schedule", "'schedule' is not scanned"), + ], +) +def test_unscanned_events_skip_with_a_warning( + monkeypatch, caplog, event_name, expected +): + warnings = _skip_warnings(_github(monkeypatch, event_name, "opened"), caplog) + + assert any(expected in message and "No scan ran" in message for message in warnings) + if event_name == "schedule": + assert any("issue_comment (ignore commands)" in message for message in warnings) + + +def _gitlab(monkeypatch, pipeline_source): + monkeypatch.setenv("GITLAB_TOKEN", "test-token") + if pipeline_source is not None: + monkeypatch.setenv("CI_PIPELINE_SOURCE", pipeline_source) + return Gitlab(client=object(), config=GitlabConfig.from_env()) + + +@pytest.mark.parametrize( + "pipeline_source, expected", + [ + ("schedule", "'schedule' is not scanned"), + (None, "CI_PIPELINE_SOURCE is not set"), + ], +) +def test_gitlab_skipped_sources_warn(monkeypatch, caplog, pipeline_source, expected): + warnings = _skip_warnings(_gitlab(monkeypatch, pipeline_source), caplog) + + assert any(expected in message and "No scan ran" in message for message in warnings) + + +def _blocking_alert() -> Issue: + return Issue( + pkg_name="lodash", + pkg_version="4.17.11", + pkg_type="npm", + severity="critical", + title="Critical CVE", + description="", + type="criticalCVE", + url="https://socket.dev/test", + manifests="package.json", + props={}, + key="key", + purl="pkg:npm/lodash@4.17.11", + error=True, + warn=False, + ignore=False, + monitor=False, + ) + + +@pytest.mark.parametrize( + "action, has_blocker, scanned, expected_exit", + [ + ("reopened", True, True, 1), + ("reopened", False, True, 0), + ("ready_for_review", True, True, 1), + ("ready_for_review", False, True, 0), + ("synchronize", True, True, 1), + ("closed", True, False, 0), + ], +) +def test_pull_request_payload_drives_scan_and_exit( + monkeypatch, tmp_path, action, has_blocker, scanned, expected_exit +): + monkeypatch.setattr( + sys, + "argv", + [ + "socketcli", + "--api-token", + "test", + "--scm", + "github", + "--strict-blocking", + "--repo", + "repo", + "--branch", + "feature", + "--pr-number", + "7", + "--files", + '["package.json"]', + ], + ) + monkeypatch.setenv("GITHUB_EVENT_NAME", "pull_request") + event_path = tmp_path / "event.json" + event_path.write_text(json.dumps({"action": action}), encoding="utf-8") + monkeypatch.setenv("GITHUB_EVENT_PATH", str(event_path)) + monkeypatch.setenv("DEFAULT_BRANCH", "false") + + existing_alerts = [_blocking_alert()] if has_blocker else [] + diff = Diff(id="scan", new_alerts=[], unchanged_alerts=existing_alerts) + diff.diff_url = "https://socket.dev/diff" + monkeypatch.setattr( + Github, + "get_comments_for_pr", + lambda self: Comments.check_for_socket_comments({}), + ) + posted = Mock() + monkeypatch.setattr(Github, "add_socket_comments", posted) + monkeypatch.setattr(Github, "handle_ignore_reactions", Mock()) + sdk = MagicMock() + sdk.org.get.return_value = {"organizations": {"org-id": {"slug": "acme"}}} + monkeypatch.setattr(socketcli, "build_socket_sdk", Mock(return_value=sdk)) + monkeypatch.setattr(socketcli, "CliClient", Mock(return_value=Mock())) + monkeypatch.setattr( + socketcli, "StreamingLogs", lambda **kwargs: nullcontext(Mock()) + ) + monkeypatch.setattr(socketcli, "apply_git_context", lambda config: (False, None)) + scan = Mock(return_value=diff) + monkeypatch.setattr(socketcli.Core, "create_new_diff", scan) + full_scan = Mock() + monkeypatch.setattr(socketcli.Core, "create_full_scan_with_report_url", full_scan) + monkeypatch.setattr(socketcli.Core, "has_manifest_files", Mock(return_value=True)) + monkeypatch.setattr(socketcli.OutputHandler, "handle_output", Mock()) + + with pytest.raises(SystemExit) as result: + socketcli.cli() + + assert result.value.code == expected_exit + full_scan.assert_not_called() + assert scan.called is scanned + assert posted.called is scanned + if scanned: + scan.assert_called_once() + posted.assert_called_once() + assert posted.call_args.args[3] is has_blocker diff --git a/workflows/github-actions-comments.yml b/workflows/github-actions-comments.yml new file mode 100644 index 00000000..9bef3e44 --- /dev/null +++ b/workflows/github-actions-comments.yml @@ -0,0 +1,36 @@ +# Copy this workflow to .github/workflows/ to handle PR ignore commands. +name: Socket Security Ignore Commands + +on: + issue_comment: + types: [created] + +concurrency: + group: socket-ignore-${{ github.event.issue.number }} + cancel-in-progress: false + +jobs: + socket-security-ignore: + if: github.event.issue.pull_request + permissions: + contents: read + issues: write + pull-requests: write + runs-on: ubuntu-latest + container: socketdev/cli:latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Handle Socket Security Ignore Commands + env: + SOCKET_SECURITY_API_KEY: ${{ secrets.SOCKET_SECURITY_API_KEY }} + GH_API_TOKEN: ${{ secrets.GITHUB_TOKEN }} + PR_NUMBER: ${{ github.event.issue.number }} + run: | + socketcli \ + --target-path "$GITHUB_WORKSPACE" \ + --scm github \ + --pr-number "$PR_NUMBER" diff --git a/workflows/github-actions-push.yml b/workflows/github-actions-push.yml new file mode 100644 index 00000000..018feb57 --- /dev/null +++ b/workflows/github-actions-push.yml @@ -0,0 +1,32 @@ +# Copy this workflow to .github/workflows/ to scan pushes and update the baseline. +name: Socket Security Pushes + +on: + push: + branches: ['**'] + +concurrency: + group: socket-push-${{ github.ref }}-${{ github.sha }} + cancel-in-progress: true + +jobs: + socket-security-push: + permissions: + contents: read + runs-on: ubuntu-latest + container: socketdev/cli:latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Run Socket Security Push Scan + env: + SOCKET_SECURITY_API_KEY: ${{ secrets.SOCKET_SECURITY_API_KEY }} + GH_API_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + socketcli \ + --target-path "$GITHUB_WORKSPACE" \ + --scm github \ + --pr-number 0 diff --git a/workflows/github-actions.yml b/workflows/github-actions.yml index 422eb253..23b8885b 100644 --- a/workflows/github-actions.yml +++ b/workflows/github-actions.yml @@ -1,63 +1,35 @@ -# Socket Security GitHub Actions Workflow -# This workflow runs Socket Security scans on every commit to any branch -# It automatically detects git repository information and handles different event types - -name: socket-security-workflow -run-name: Socket Security Github Action +# Copy this workflow to .github/workflows/ to enable the PR scan. +name: Socket Security Pull Requests on: - push: - branches: ['**'] # Run on all branches, all commits pull_request: - types: [opened, synchronize, reopened] - issue_comment: - types: [created] + types: [opened, synchronize, reopened, ready_for_review] -# Prevent concurrent runs for the same commit concurrency: - group: socket-scan-${{ github.sha }} + group: socket-pr-${{ github.event.pull_request.number }} cancel-in-progress: true jobs: socket-security: permissions: - issues: write contents: read + issues: write pull-requests: write runs-on: ubuntu-latest - - # Option 1: Use the official Socket CLI container (faster, more reliable) container: socketdev/cli:latest - steps: - uses: actions/checkout@v4 with: - # For PRs, fetch one additional commit for proper diff analysis fetch-depth: 0 - - - name: Run Socket Security Scan + persist-credentials: false + + - name: Run Socket Security PR Scan env: SOCKET_SECURITY_API_KEY: ${{ secrets.SOCKET_SECURITY_API_KEY }} GH_API_TOKEN: ${{ secrets.GITHUB_TOKEN }} + PR_NUMBER: ${{ github.event.pull_request.number }} run: | - # Determine PR number based on event type - PR_NUMBER=0 - if [ "${{ github.event_name }}" == "pull_request" ]; then - PR_NUMBER=${{ github.event.pull_request.number }} - elif [ "${{ github.event_name }}" == "issue_comment" ]; then - PR_NUMBER=${{ github.event.issue.number }} - fi - - # Run Socket CLI with minimal required parameters - # The CLI automatically detects: - # - Repository name from git - # - Branch name from git - # - Commit SHA from git - # - Commit message from git - # - Committer information from git - # - Default branch status from git and GitHub environment - # - Changed files from git commit socketcli \ - --target-path $GITHUB_WORKSPACE \ + --target-path "$GITHUB_WORKSPACE" \ --scm github \ - --pr-number $PR_NUMBER + --pr-number "$PR_NUMBER"