Skip to content
Draft
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
20 changes: 20 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,25 @@
# 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.
- 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

### Upgrade notes
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 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)
Expand Down
198 changes: 19 additions & 179 deletions docs/ci-cd.md
Original file line number Diff line number Diff line change
Expand Up @@ -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@v5
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@v5
with:
fetch-depth: 0
persist-credentials: false

- uses: actions/setup-python@v6
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,
Expand All @@ -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`,
Expand Down Expand Up @@ -559,6 +390,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:<digest>`, 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
Expand Down Expand Up @@ -651,7 +491,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-<version>
Expand Down Expand Up @@ -697,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)
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand Down
2 changes: 1 addition & 1 deletion socketsecurity/__init__.py
Original file line number Diff line number Diff line change
@@ -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__}'
96 changes: 96 additions & 0 deletions tests/unit/test_workflow_templates.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
"""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<action>[\w.-]+/[\w./-]+)@(?P<ref>\S+)(?P<comment>[^\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",
"github-actions-monorepo.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 _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
2 changes: 1 addition & 1 deletion uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading