From 18fc901e9771acf2745907d0d587ad81d1716b89 Mon Sep 17 00:00:00 2001 From: lelia <2418071+lelia@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:06:30 -0500 Subject: [PATCH 1/2] Pin, scope and audit the GitHub Actions examples Pin actions/checkout to a commit, drop default token permissions, explain each job permission and name every job while keeping the socket-security check name. The ignore-command example now runs only for ignore commands. A test keeps the examples' action pins in step with the commits the repository's CI uses. --- CHANGELOG.md | 17 ++++++ docs/ci-cd.md | 17 ++++-- pyproject.toml | 2 +- socketsecurity/__init__.py | 2 +- tests/unit/test_workflow_templates.py | 78 +++++++++++++++++++++++++++ uv.lock | 2 +- workflows/github-actions-comments.yml | 38 +++++++++---- workflows/github-actions-push.yml | 24 ++++++--- workflows/github-actions.yml | 33 ++++++++---- 9 files changed, 179 insertions(+), 34 deletions(-) create mode 100644 tests/unit/test_workflow_templates.py diff --git a/CHANGELOG.md b/CHANGELOG.md index fa8a0703..df2f1109 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,22 @@ # Changelog +## 2.14.1 + +### Changed + +- The GitHub Actions examples pin `actions/checkout` to a commit (v7.0.1), set + `permissions: {}` and explain each job permission, and pass `zizmor` and + `actionlint`. The `socket-security` required check name is unchanged. +- The ignore-command example runs only for comments that contain a + `@SocketSecurity ignore` command instead of for every pull request comment. + +### Documentation + +- The [CI guide](docs/ci-cd.md#required-github-checks) explains that an ignore + command doesn't update the required check until the pull request workflow runs + again, and how to pin the `socketdev/cli` image to a release. The guide's own + examples pin their actions to commits. + ## 2.14.0 ### Upgrade notes diff --git a/docs/ci-cd.md b/docs/ci-cd.md index 1c53760d..e0226c4f 100644 --- a/docs/ci-cd.md +++ b/docs/ci-cd.md @@ -207,7 +207,7 @@ jobs: count: ${{ steps.select.outputs.count }} matrix: ${{ steps.select.outputs.matrix }} steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 persist-credentials: false @@ -293,12 +293,12 @@ jobs: name: Socket scan (${{ matrix.name }}) runs-on: ubuntu-latest steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 persist-credentials: false - - uses: actions/setup-python@v6 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: '3.12' @@ -559,6 +559,15 @@ 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. +An ignore command updates the Socket comment but not the required check, which +keeps the result of the last PR scan. Re-run the PR workflow, or push a commit, +to apply the ignore to the check. + +The examples pin actions by commit SHA and use the `socketdev/cli:latest` +image so they stay current. For reproducible runs, pin the image to a release +tag and digest, such as `socketdev/cli:2.14.0@sha256:`, and update it +when you upgrade. + 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 @@ -651,7 +660,7 @@ provider caches instead, and key that cache on the CLI version, which determines the engine version. In GitHub Actions: ```yaml -- uses: actions/cache@v4 +- uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ${{ runner.temp }}/socket-cache key: socket-cli- diff --git a/pyproject.toml b/pyproject.toml index 4da80233..521c4aaf 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ build-backend = "hatchling.build" [project] name = "socketsecurity" -version = "2.14.0" +version = "2.14.1" requires-python = ">= 3.11" license = {"file" = "LICENSE"} dependencies = [ diff --git a/socketsecurity/__init__.py b/socketsecurity/__init__.py index 0f2224d3..47fe8747 100644 --- a/socketsecurity/__init__.py +++ b/socketsecurity/__init__.py @@ -1,4 +1,4 @@ __author__ = 'socket.dev' -__version__ = '2.14.0' +__version__ = '2.14.1' USER_AGENT_NAME = 'socket-python-cli' USER_AGENT = f'{USER_AGENT_NAME}/{__version__}' diff --git a/tests/unit/test_workflow_templates.py b/tests/unit/test_workflow_templates.py new file mode 100644 index 00000000..b0234007 --- /dev/null +++ b/tests/unit/test_workflow_templates.py @@ -0,0 +1,78 @@ +"""The GitHub Actions examples stay pinned, current, and safe to require. + +Dependabot updates the actions in `.github/workflows`, but not the copy-paste +templates in `workflows/` or the snippets in the docs, which is how the templates +fell four majors behind. These tests fail when an example uses an unpinned action +or a different commit than the repository's own CI, so a Dependabot bump surfaces +the examples that need the same update. +""" +import re +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[2] +TEMPLATES = sorted((ROOT / "workflows").glob("github-actions*.yml")) +EXAMPLES = TEMPLATES + [ROOT / "docs" / "ci-cd.md"] +USES = re.compile(r"uses:\s*(?P[\w.-]+/[\w./-]+)@(?P\S+)(?P[^\n]*)") +PINNED = re.compile(r"^[0-9a-f]{40}$") + + +def _uses(path): + return [m.groupdict() | {"path": path.relative_to(ROOT)} for m in USES.finditer(path.read_text())] + + +def _ci_pins(): + pins = {} + files = list((ROOT / ".github" / "workflows").glob("*.yml")) + files += list((ROOT / ".github" / "actions").glob("*/action.yml")) + for path in files: + for use in _uses(path): + if PINNED.match(use["ref"]): + pins.setdefault(use["action"], set()).add(use["ref"]) + return pins + + +def test_the_templates_exist(): + assert {path.name for path in TEMPLATES} == { + "github-actions.yml", + "github-actions-push.yml", + "github-actions-comments.yml", + } + + +@pytest.mark.parametrize("path", EXAMPLES, ids=lambda path: path.name) +def test_examples_pin_actions_to_a_commit_with_its_version(path): + unpinned = [ + f"{use['path']}: {use['action']}@{use['ref']}" + for use in _uses(path) + if not PINNED.match(use["ref"]) or not re.search(r"#\s*v\d", use["comment"]) + ] + assert not unpinned, "pin these to a full commit SHA with a `# vX.Y.Z` comment: " + ", ".join(unpinned) + + +@pytest.mark.parametrize("path", EXAMPLES, ids=lambda path: path.name) +def test_examples_use_the_same_commit_as_ci(path): + pins = _ci_pins() + stale = [ + f"{use['path']}: {use['action']}@{use['ref'][:12]} (CI uses " + f"{', '.join(sorted(ref[:12] for ref in pins[use['action']]))})" + for use in _uses(path) + if use["action"] in pins and use["ref"] not in pins[use["action"]] + ] + assert not stale, "update these to the commit .github/workflows uses: " + "; ".join(stale) + + +def test_only_the_pull_request_workflow_reports_the_required_check(): + """GitHub counts a skipped job as passing, so the required check needs its own workflow.""" + pr_workflow = (ROOT / "workflows" / "github-actions.yml").read_text() + on_block = re.search(r"^on:\n((?:[ \t]+.*\n|\n)*)", pr_workflow, re.M).group(1) + triggers = re.findall(r"^ (\w+):", on_block, re.M) + assert triggers == ["pull_request"] + for path in TEMPLATES: + names = re.findall(r"^ ([\w-]+):\n|^ name: ([\w-]+)$", path.read_text(), re.M) + reported = {job or name for job, name in names} + if path.name == "github-actions.yml": + assert "socket-security" in reported + else: + assert "socket-security" not in reported, f"{path.name} reports the required check name" diff --git a/uv.lock b/uv.lock index d509bbc9..15119bd8 100644 --- a/uv.lock +++ b/uv.lock @@ -1334,7 +1334,7 @@ wheels = [ [[package]] name = "socketsecurity" -version = "2.14.0" +version = "2.14.1" source = { editable = "." } dependencies = [ { name = "beautifulsoup4" }, diff --git a/workflows/github-actions-comments.yml b/workflows/github-actions-comments.yml index 9bef3e44..7d7b8360 100644 --- a/workflows/github-actions-comments.yml +++ b/workflows/github-actions-comments.yml @@ -1,30 +1,46 @@ -# Copy this workflow to .github/workflows/ to handle PR ignore commands. +# Socket Security ignore commands (optional). +# +# Copy to .github/workflows/ if reviewers reply `@SocketSecurity ignore ` +# or `@SocketSecurity ignore-all` to accept alerts. This run updates the Socket +# comment only. The required `socket-security` check keeps its result until the +# pull request workflow runs again, so re-run that check (or push a commit) after +# an ignore command. name: Socket Security Ignore Commands on: - issue_comment: + # issue_comment runs on the default branch with this repository's secrets. + # This workflow never checks out pull request code, runs only for ignore + # commands, and the CLI honors a command only from a commenter with write access. + issue_comment: # zizmor: ignore[dangerous-triggers] types: [created] +permissions: {} + concurrency: - group: socket-ignore-${{ github.event.issue.number }} + group: socket-security-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 + name: socket-security-ignore + # Skip ordinary comments. contains() is case-insensitive and also matches + # `ignore-all`; the CLI reads the command from the comment's first line. + if: github.event.issue.pull_request && contains(github.event.comment.body, 'SocketSecurity ignore') runs-on: ubuntu-latest - container: socketdev/cli:latest + permissions: + contents: read # check out the default branch + issues: write # update the Socket comment and react to the command + pull-requests: write # read the pull request's comments + # Pinning: see the image comment in github-actions.yml. + container: socketdev/cli:latest # zizmor: ignore[unpinned-images] steps: - - uses: actions/checkout@v4 + - name: Check out the default branch + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 persist-credentials: false - - name: Handle Socket Security Ignore Commands + - name: Apply Socket ignore commands env: SOCKET_SECURITY_API_KEY: ${{ secrets.SOCKET_SECURITY_API_KEY }} GH_API_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/workflows/github-actions-push.yml b/workflows/github-actions-push.yml index 018feb57..0ccb2fc0 100644 --- a/workflows/github-actions-push.yml +++ b/workflows/github-actions-push.yml @@ -1,27 +1,37 @@ -# Copy this workflow to .github/workflows/ to scan pushes and update the baseline. +# Socket Security push scans. +# +# Copy to .github/workflows/ alongside github-actions.yml. Default-branch scans +# are the baseline pull request comparisons run against, so without this +# workflow those comparisons use an increasingly old scan. Push scans never +# block; they report to the Socket Dashboard. name: Socket Security Pushes on: push: branches: ['**'] +permissions: {} + concurrency: - group: socket-push-${{ github.ref }}-${{ github.sha }} + group: socket-security-push-${{ github.ref }}-${{ github.sha }} cancel-in-progress: true jobs: socket-security-push: - permissions: - contents: read + name: socket-security-push runs-on: ubuntu-latest - container: socketdev/cli:latest + permissions: + contents: read # check out the repository + # Pinning: see the image comment in github-actions.yml. + container: socketdev/cli:latest # zizmor: ignore[unpinned-images] steps: - - uses: actions/checkout@v4 + - name: Check out the repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 persist-credentials: false - - name: Run Socket Security Push Scan + - name: Run the Socket push scan env: SOCKET_SECURITY_API_KEY: ${{ secrets.SOCKET_SECURITY_API_KEY }} GH_API_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/workflows/github-actions.yml b/workflows/github-actions.yml index 23b8885b..7b80674f 100644 --- a/workflows/github-actions.yml +++ b/workflows/github-actions.yml @@ -1,29 +1,44 @@ -# Copy this workflow to .github/workflows/ to enable the PR scan. +# Socket Security pull request scan. +# +# Copy to .github/workflows/ and make the `socket-security` job a required status +# check. Keep that job name exclusive to this workflow: GitHub counts a skipped +# job as passing, so another workflow reporting the same name could satisfy the +# check without scanning the pull request. +# +# Companion workflows: github-actions-push.yml keeps the default-branch baseline +# current, and github-actions-comments.yml (optional) handles ignore commands. name: Socket Security Pull Requests on: pull_request: types: [opened, synchronize, reopened, ready_for_review] +permissions: {} + concurrency: - group: socket-pr-${{ github.event.pull_request.number }} + group: socket-security-pr-${{ github.event.pull_request.number }} cancel-in-progress: true jobs: socket-security: - permissions: - contents: read - issues: write - pull-requests: write + name: socket-security runs-on: ubuntu-latest - container: socketdev/cli:latest + permissions: + contents: read # check out the repository + issues: write # post the Socket comments and react to ignore commands + pull-requests: write # read the pull request and update its comments + # `latest` keeps this template current with every release. For reproducible + # runs, pin a release tag and digest instead, for example + # socketdev/cli:2.14.0@sha256:, and update it when you upgrade. + container: socketdev/cli:latest # zizmor: ignore[unpinned-images] steps: - - uses: actions/checkout@v4 + - name: Check out the repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 persist-credentials: false - - name: Run Socket Security PR Scan + - name: Run the Socket pull request scan env: SOCKET_SECURITY_API_KEY: ${{ secrets.SOCKET_SECURITY_API_KEY }} GH_API_TOKEN: ${{ secrets.GITHUB_TOKEN }} From 6f2090ec2ad6dab4b5c78cd32883576ea3ad39f2 Mon Sep 17 00:00:00 2001 From: lelia <2418071+lelia@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:13:37 -0500 Subject: [PATCH 2/2] Move the monorepo example into workflows/ The 171-line per-workspace workflow lived only in docs/ci-cd.md, where no linter checked it. It's now a template alongside the others, covered by actionlint, zizmor and the pin test, and the guide links to it. --- CHANGELOG.md | 3 + README.md | 2 +- docs/ci-cd.md | 187 ++----------------------- tests/unit/test_workflow_templates.py | 44 ++++-- workflows/github-actions-monorepo.yml | 191 ++++++++++++++++++++++++++ 5 files changed, 235 insertions(+), 192 deletions(-) create mode 100644 workflows/github-actions-monorepo.yml diff --git a/CHANGELOG.md b/CHANGELOG.md index df2f1109..2e332aad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,9 @@ command doesn't update the required check until the pull request workflow runs again, and how to pin the `socketdev/cli` image to a release. The guide's own examples pin their actions to commits. +- The per-workspace monorepo example moved from the CI guide to + [`workflows/github-actions-monorepo.yml`](workflows/github-actions-monorepo.yml), + so it's linted and kept current with the other examples. The guide links to it. ## 2.14.0 diff --git a/README.md b/README.md index a143c62d..aaf91739 100644 --- a/README.md +++ b/README.md @@ -205,7 +205,7 @@ JSON: Prebuilt workflow examples: -- 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) +- 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), or [per-workspace monorepo scans](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/github-actions-monorepo.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 e0226c4f..12609c68 100644 --- a/docs/ci-cd.md +++ b/docs/ci-cd.md @@ -182,185 +182,16 @@ logical graph. If root workspace metadata governs most or all of the repository, smaller coverage-preserving split may not be representable with `--sub-path` alone. Also define `SOCKETCLI_VERSION` as the exact package version validated for the -workflow. The workflow below logs that version, uses full Git history for reliable -base/head selection, creates one matrix job (and therefore one graph and baseline) -per selected workspace, and fails closed on CLI/API/timeout failures. It uses API +workflow. The [monorepo workflow](../workflows/github-actions-monorepo.yml) logs +that version, uses full Git history for reliable base/head selection, creates one +matrix job (and therefore one graph and baseline) per selected workspace, and +fails closed on CLI/API/timeout failures. It uses API SCM mode plus `--enable-diff` because parallel `--scm github` jobs can race while updating the same PR comments; the matrix checks and report links are the gate. -```yaml -name: Socket Security - -on: - pull_request: - types: [opened, synchronize, reopened] - push: - branches: [main] - -permissions: - contents: read - -jobs: - select-workspaces: - runs-on: ubuntu-latest - outputs: - count: ${{ steps.select.outputs.count }} - matrix: ${{ steps.select.outputs.matrix }} - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - fetch-depth: 0 - persist-credentials: false - - - id: select - name: Select changed workspaces - env: - WORKSPACES_JSON: ${{ vars.SOCKET_MONOREPO_WORKSPACES_JSON }} - BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.before }} - HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} - shell: bash - run: | - python - <<'PY' - import fnmatch - import json - import os - import re - import subprocess - - workspaces = json.loads(os.environ["WORKSPACES_JSON"]) - if not isinstance(workspaces, list): - raise SystemExit("SOCKET_MONOREPO_WORKSPACES_JSON must be a JSON array") - - base = os.environ["BASE_SHA"] - head = os.environ["HEAD_SHA"] - if not base or set(base) == {"0"}: - base = subprocess.check_output( - ["git", "rev-parse", f"{head}^"], text=True - ).strip() - changed_output = subprocess.check_output( - ["git", "diff", "--name-only", "-z", base, head] - ) - changed = [ - item.decode("utf-8", "surrogateescape") - for item in changed_output.split(b"\0") - if item - ] - - selected = [] - for workspace in workspaces: - name = workspace.get("name", "") - sub_paths = workspace.get("sub_paths") or [] - watch_globs = workspace.get("watch_globs") or [] - if not re.fullmatch(r"[A-Za-z0-9._-]+", name): - raise SystemExit(f"Invalid workspace name: {name!r}") - if not sub_paths or any( - not isinstance(path, str) - or path.startswith("/") - or ".." in path.split("/") - for path in sub_paths - ): - raise SystemExit(f"Invalid sub_paths for workspace {name!r}") - if not watch_globs: - watch_globs = [ - pattern - for path in sub_paths - for pattern in ( - ["*"] - if path.strip("/") in ("", ".") - else [path.rstrip("/"), f"{path.rstrip('/')}/*"] - ) - ] - if any( - fnmatch.fnmatchcase(path, pattern) - for path in changed - for pattern in watch_globs - ): - selected.append({"name": name, "sub_paths": sub_paths}) - - matrix = json.dumps({"include": selected}, separators=(",", ":")) - with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output: - output.write(f"count={len(selected)}\n") - output.write(f"matrix={matrix}\n") - PY - - scan-workspace: - needs: select-workspaces - if: needs.select-workspaces.outputs.count != '0' - timeout-minutes: 20 - strategy: - fail-fast: false - matrix: ${{ fromJSON(needs.select-workspaces.outputs.matrix) }} - name: Socket scan (${{ matrix.name }}) - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - fetch-depth: 0 - persist-credentials: false - - - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 - with: - python-version: '3.12' - - - name: Install pinned Socket CLI - env: - SOCKETCLI_VERSION: ${{ vars.SOCKETCLI_VERSION }} - run: | - python -m pip install "socketsecurity==$SOCKETCLI_VERSION" - socketcli --version - - - name: Scan workspace - env: - SOCKET_SECURITY_API_KEY: ${{ secrets.SOCKET_SECURITY_API_KEY }} - PR_NUMBER: ${{ github.event.pull_request.number || 0 }} - WORKSPACE_NAME: ${{ matrix.name }} - SUB_PATHS_JSON: ${{ toJSON(matrix.sub_paths) }} - shell: bash - run: | - set +e - args=( - --target-path "$GITHUB_WORKSPACE" - --workspace-name "$WORKSPACE_NAME" - --enable-diff - --pr-number "$PR_NUMBER" - --exit-code-on-api-error 3 - --report-link-file socket-report-link.txt - --summary-file socket-summary.txt - ) - while IFS= read -r sub_path; do - args+=(--sub-path "$sub_path") - done < <(jq -r '.[]' <<<"$SUB_PATHS_JSON") - - socketcli "${args[@]}" 2>&1 | tee socket-output.log - code=${PIPESTATUS[0]} - - { - echo "## Socket scan: $WORKSPACE_NAME" - if [ -s socket-report-link.txt ]; then - echo "[View the report]($(cat socket-report-link.txt))" - fi - if [ -s socket-summary.txt ]; then - echo '```' - cat socket-summary.txt - echo '```' - fi - } >> "$GITHUB_STEP_SUMMARY" - - exit "$code" - - socket-security: - if: always() - needs: [select-workspaces, scan-workspace] - runs-on: ubuntu-latest - steps: - - name: Enforce matrix result - env: - SELECT_RESULT: ${{ needs.select-workspaces.result }} - SCAN_RESULT: ${{ needs.scan-workspace.result }} - run: | - test "$SELECT_RESULT" = success - [[ "$SCAN_RESULT" = success || "$SCAN_RESULT" = skipped ]] -``` +Copy it to `.github/workflows/` in place of the [PR workflow](../workflows/github-actions.yml) +and require its `socket-security` job, the aggregate gate. It reports a result +even when no workspace changed, so the required check never stays pending. Each configuration object may intentionally contain several `sub_paths` when those directories are one logical dependency graph. To split backend resolution, @@ -369,7 +200,7 @@ when the Socket organization requires API workspace association; it is not a sca scope control. Use `--save-submitted-files-list` in a non-required canary to verify the exact manifests selected before adopting workspace-level scans as a merge gate. -The job has an explicit 20-minute total budget. Tune that value from observed +Its scan job has an explicit 20-minute total budget. Tune that value from observed workspace-level latency after the split; a five-minute cap can still be too close to a slow request plus local startup. The CLI's `--timeout` is different: it defaults to 1,200 seconds **per API request**. If an operator adds GNU `timeout`, @@ -706,7 +537,7 @@ listed thinly or not at all. Prebuilt examples in this repo: -- GitHub Actions for [pull requests](../workflows/github-actions.yml), [pushes](../workflows/github-actions-push.yml), and [ignore commands](../workflows/github-actions-comments.yml) +- GitHub Actions for [pull requests](../workflows/github-actions.yml), [pushes](../workflows/github-actions-push.yml), and [ignore commands](../workflows/github-actions-comments.yml), or [per-workspace monorepo scans](../workflows/github-actions-monorepo.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/tests/unit/test_workflow_templates.py b/tests/unit/test_workflow_templates.py index b0234007..b92723df 100644 --- a/tests/unit/test_workflow_templates.py +++ b/tests/unit/test_workflow_templates.py @@ -38,6 +38,7 @@ def test_the_templates_exist(): "github-actions.yml", "github-actions-push.yml", "github-actions-comments.yml", + "github-actions-monorepo.yml", } @@ -63,16 +64,33 @@ def test_examples_use_the_same_commit_as_ci(path): assert not stale, "update these to the commit .github/workflows uses: " + "; ".join(stale) -def test_only_the_pull_request_workflow_reports_the_required_check(): - """GitHub counts a skipped job as passing, so the required check needs its own workflow.""" - pr_workflow = (ROOT / "workflows" / "github-actions.yml").read_text() - on_block = re.search(r"^on:\n((?:[ \t]+.*\n|\n)*)", pr_workflow, re.M).group(1) - triggers = re.findall(r"^ (\w+):", on_block, re.M) - assert triggers == ["pull_request"] - for path in TEMPLATES: - names = re.findall(r"^ ([\w-]+):\n|^ name: ([\w-]+)$", path.read_text(), re.M) - reported = {job or name for job, name in names} - if path.name == "github-actions.yml": - assert "socket-security" in reported - else: - assert "socket-security" not in reported, f"{path.name} reports the required check name" +def _triggers(text): + on_block = re.search(r"^on:\n((?:[ \t]+.*\n|\n)*)", text, re.M).group(1) + return re.findall(r"^ (\w+):", on_block, re.M), on_block + + +def _reports_required_check(text): + names = re.findall(r"^ ([\w-]+):\n|^ name: ([\w-]+)$", text, re.M) + return "socket-security" in {job or name for job, name in names} + + +def test_the_pull_request_workflow_owns_the_required_check(): + """GitHub counts a skipped job as passing, so the required check needs a PR-only workflow.""" + text = (ROOT / "workflows" / "github-actions.yml").read_text() + assert _triggers(text)[0] == ["pull_request"] + assert _reports_required_check(text) + + +@pytest.mark.parametrize("name", ["github-actions-push.yml", "github-actions-comments.yml"]) +def test_companion_workflows_never_report_the_required_check(name): + assert not _reports_required_check((ROOT / "workflows" / name).read_text()) + + +def test_the_monorepo_gate_always_reports_and_never_runs_on_every_push(): + """The alternative workflow's gate must not be skipped or reported by branch pushes.""" + text = (ROOT / "workflows" / "github-actions-monorepo.yml").read_text() + gate = re.search(r"^ socket-security:\n((?: .*\n|\n)*)", text, re.M).group(1) + assert re.search(r"^ if: always\(\)$", gate, re.M) + triggers, on_block = _triggers(text) + assert "pull_request" in triggers + assert "'**'" not in on_block and '"**"' not in on_block diff --git a/workflows/github-actions-monorepo.yml b/workflows/github-actions-monorepo.yml new file mode 100644 index 00000000..88d3bb9a --- /dev/null +++ b/workflows/github-actions-monorepo.yml @@ -0,0 +1,191 @@ +# Socket Security scans per monorepo workspace. +# +# An alternative to github-actions.yml for monorepos: a selector job picks the +# workspaces a change touches, and each one gets its own scan, dashboard entry and +# baseline. Copy to .github/workflows/ and make the `socket-security` job (the +# aggregate gate at the end) the required check. It runs with `if: always()`, so +# it reports a result even when no workspace changed. This workflow updates +# baselines on pushes to `main` and doesn't post PR comments, so the push and +# ignore-command examples don't apply. +# +# Configure two repository variables first; docs/ci-cd.md explains both: +# SOCKET_MONOREPO_WORKSPACES_JSON the workspaces, their scan roots and the +# changed-file globs that select them +# SOCKETCLI_VERSION the exact socketsecurity version to install +name: Socket Security + +on: + pull_request: + types: [opened, synchronize, reopened] + push: + branches: [main] + +permissions: + contents: read + +concurrency: + group: socket-security-monorepo-${{ github.event.pull_request.number || github.sha }} + cancel-in-progress: true + +jobs: + select-workspaces: + name: Select changed workspaces + runs-on: ubuntu-latest + outputs: + count: ${{ steps.select.outputs.count }} + matrix: ${{ steps.select.outputs.matrix }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + + - id: select + name: Select changed workspaces + env: + WORKSPACES_JSON: ${{ vars.SOCKET_MONOREPO_WORKSPACES_JSON }} + BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.before }} + HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + shell: bash + run: | + python - <<'PY' + import fnmatch + import json + import os + import re + import subprocess + + workspaces = json.loads(os.environ["WORKSPACES_JSON"]) + if not isinstance(workspaces, list): + raise SystemExit("SOCKET_MONOREPO_WORKSPACES_JSON must be a JSON array") + + base = os.environ["BASE_SHA"] + head = os.environ["HEAD_SHA"] + if not base or set(base) == {"0"}: + base = subprocess.check_output( + ["git", "rev-parse", f"{head}^"], text=True + ).strip() + changed_output = subprocess.check_output( + ["git", "diff", "--name-only", "-z", base, head] + ) + changed = [ + item.decode("utf-8", "surrogateescape") + for item in changed_output.split(b"\0") + if item + ] + + selected = [] + for workspace in workspaces: + name = workspace.get("name", "") + sub_paths = workspace.get("sub_paths") or [] + watch_globs = workspace.get("watch_globs") or [] + if not re.fullmatch(r"[A-Za-z0-9._-]+", name): + raise SystemExit(f"Invalid workspace name: {name!r}") + if not sub_paths or any( + not isinstance(path, str) + or path.startswith("/") + or ".." in path.split("/") + for path in sub_paths + ): + raise SystemExit(f"Invalid sub_paths for workspace {name!r}") + if not watch_globs: + watch_globs = [ + pattern + for path in sub_paths + for pattern in ( + ["*"] + if path.strip("/") in ("", ".") + else [path.rstrip("/"), f"{path.rstrip('/')}/*"] + ) + ] + if any( + fnmatch.fnmatchcase(path, pattern) + for path in changed + for pattern in watch_globs + ): + selected.append({"name": name, "sub_paths": sub_paths}) + + matrix = json.dumps({"include": selected}, separators=(",", ":")) + with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output: + output.write(f"count={len(selected)}\n") + output.write(f"matrix={matrix}\n") + PY + + scan-workspace: + needs: select-workspaces + if: needs.select-workspaces.outputs.count != '0' + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: ${{ fromJSON(needs.select-workspaces.outputs.matrix) }} + name: Socket scan (${{ matrix.name }}) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: '3.12' + + - name: Install pinned Socket CLI + env: + SOCKETCLI_VERSION: ${{ vars.SOCKETCLI_VERSION }} + run: | + python -m pip install "socketsecurity==$SOCKETCLI_VERSION" + socketcli --version + + - name: Scan workspace + env: + SOCKET_SECURITY_API_KEY: ${{ secrets.SOCKET_SECURITY_API_KEY }} + PR_NUMBER: ${{ github.event.pull_request.number || 0 }} + WORKSPACE_NAME: ${{ matrix.name }} + SUB_PATHS_JSON: ${{ toJSON(matrix.sub_paths) }} + shell: bash + run: | + set +e + args=( + --target-path "$GITHUB_WORKSPACE" + --workspace-name "$WORKSPACE_NAME" + --enable-diff + --pr-number "$PR_NUMBER" + --exit-code-on-api-error 3 + --report-link-file socket-report-link.txt + --summary-file socket-summary.txt + ) + while IFS= read -r sub_path; do + args+=(--sub-path "$sub_path") + done < <(jq -r '.[]' <<<"$SUB_PATHS_JSON") + + socketcli "${args[@]}" 2>&1 | tee socket-output.log + code=${PIPESTATUS[0]} + + { + echo "## Socket scan: $WORKSPACE_NAME" + if [ -s socket-report-link.txt ]; then + echo "[View the report]($(cat socket-report-link.txt))" + fi + if [ -s socket-summary.txt ]; then + echo '```' + cat socket-summary.txt + echo '```' + fi + } >> "$GITHUB_STEP_SUMMARY" + + exit "$code" + + socket-security: + name: socket-security + if: always() + needs: [select-workspaces, scan-workspace] + runs-on: ubuntu-latest + steps: + - name: Enforce matrix result + env: + SELECT_RESULT: ${{ needs.select-workspaces.result }} + SCAN_RESULT: ${{ needs.scan-workspace.result }} + run: | + test "$SELECT_RESULT" = success + [[ "$SCAN_RESULT" = success || "$SCAN_RESULT" = skipped ]]