Skip to content

Build AI methods with your coding agent, then run them anywhere: as an MCP for chatbots, as a webapp for people, or via API for your software.

feature/Release-blocked-disallowed-action · L-261001-dfd2b7 (#1312)

Louis Choquela1edfd7e0d57
diff --git a/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.md
index 4adf8b676..a4bf6075a 100644
--- a/.claude/skills/release/SKILL.md
+++ b/.claude/skills/release/SKILL.md
@@ -23,7 +23,7 @@ One version, three artifacts, all from one run of `.github/workflows/publish-pyp
- **PyPI: `pipelex`.** `.github/workflows/publish-pypi.yml` builds and publishes through trusted publishing. It fires on the release pull request **closing merged into `main`** (`pull_request: types: [closed]`), not on the push to `main` — so the run is keyed to the release branch and its `headSha` is that branch's last commit, never the merge commit. Where the play says "the run on the merge SHA", read it here as the run on `release/vX.Y.Z`.
- **PyPI: `pipelex-api`.** The same workflow's `build-api` job builds the server's wheel and sdist and refuses them unless `api/scripts/check_lockstep_pin.py` finds `pipelex[...]==X.Y.Z` in both, the pin `api/hatch_build.py` writes, and `publish-to-pypi` waits for it, so a server that does not build stops the release before anything is uploaded; `publish-api-to-pypi` uploads them through trusted publishing in the same `pypi` environment, only after `github-release`, so the `pipelex` they pin is on PyPI and the tag guard has accepted the commit they were built from before a server file reaches PyPI.
-- **Docker Hub: `pipelex/pipelex-api:X.Y.Z`, and `latest`.** The `publish-docker-hub` job calls `.github/workflows/publish-docker-hub.yml` with the version once both distributions are on PyPI: it checks out the commit the `vX.Y.Z` tag names, runs `make -C api deploy-docker-hub` there (build for `linux/amd64` from the repository root, smoke-test that the image boots and reports X.Y.Z for the server and its pipelex, push the version tag, and `latest` when X.Y.Z is the newest stable release), confirms the tags through Docker Hub's tags API, and pushes `api/README.md` as the Docker Hub overview. A pre-release pushes its own tag and leaves `latest` alone, and so does a retry of an older release.
+- **Docker Hub: `pipelex/pipelex-api:X.Y.Z`, and `latest`.** The `publish-docker-hub` job calls `.github/workflows/publish-docker-hub.yml` with the version once both distributions are on PyPI: it checks out the commit the `vX.Y.Z` tag names, runs `make -C api deploy-docker-hub` there (build for `linux/amd64` from the repository root, smoke-test that the image boots and reports X.Y.Z for the server and its pipelex, push the version tag, and `latest` when X.Y.Z is the newest stable release), and confirms the tags through Docker Hub's tags API. A pre-release pushes its own tag and leaves `latest` alone, and so does a retry of an older release. The Docker Hub overview is not part of the release and is still updated by hand, by pasting `api/README.md` into the repository's overview on Docker Hub when it has changed.
- **The GitHub Release and the `vX.Y.Z` tag.** The same workflow's `github-release` job creates them, and the tag exists only as a side effect of `gh release create`. The release is created and the dists attached *before* Sigstore signing, which is allowed to fail: an unsigned release is reported as a warning, not a failure, because the tag is the record of what shipped.
- **The documentation site.** `.github/workflows/deploy-docs.yml` fires on the push to `main` and runs `make docs-deploy-stable`, which deploys the version read from `pyproject.toml` with the `latest` alias and republishes the root sitemap. The API server's pages are part of it, under `api-server/`, with the OpenAPI artifact beside them.
@@ -42,7 +42,7 @@ The run concludes `success` only when every job did, the image's included, so a
`gh release view vX.Y.Z` confirms the Release and its notes. A publish that failed *after* the merge is recovered by **re-running that run's failed jobs**, which keeps the successful ones, and that is the path to reach for. It is safe once the dists have reached PyPI: `skip-existing` opens on a re-run and on a dispatch, so the publish job no longer dies on the files already there, and the build job recovers the bytes this version published rather than rebuilding them — the artifact an attempt of the same run stored, else one an earlier run stored for the same commit, else the files PyPI serves — then refuses to go on unless what it holds is byte-for-byte what PyPI publishes. The Release step itself is idempotent: it edits an existing release rather than failing on one.
-The same goes for the server's two artifacts. A failed `publish-api-to-pypi` is re-run on its own, from the build its run stored. A failed `publish-docker-hub` is re-run on its own too: a version Docker Hub already serves is never built again, since a rebuild would be a different image under the same tag, so a retry that finds it there only moves `latest`, when the version is the newest stable release, and confirms the tags. When that failure needs a change to `publish-docker-hub.yml`, which a re-run would not pick up, dispatch it alone from the branch carrying the fix, `gh workflow run publish-docker-hub.yml --ref <branch> -f version=X.Y.Z`: whatever the ref, it builds the commit the `vX.Y.Z` tag names. The Dockerfile and the `deploy-docker-hub` recipe are that commit's too, so a fix there needs a new release. Docker Hub's tags API then confirms the push, as above. The overview step is allowed to fail: a warning in the run says so, usually because the token lacks the read/write/delete scope, and the cure is that scope and a re-run of the job, or pasting `api/README.md` into the overview on Docker Hub.
+The same goes for the server's two artifacts. A failed `publish-api-to-pypi` is re-run on its own, from the build its run stored. A failed `publish-docker-hub` is re-run on its own too: a version Docker Hub already serves is never built again, since a rebuild would be a different image under the same tag, so a retry that finds it there only moves `latest`, when the version is the newest stable release, and confirms the tags. When that failure needs a change to `publish-docker-hub.yml`, which a re-run would not pick up, dispatch it alone from the branch carrying the fix, `gh workflow run publish-docker-hub.yml --ref <branch> -f version=X.Y.Z`: whatever the ref, it builds the commit the `vX.Y.Z` tag names. The Dockerfile and the `deploy-docker-hub` recipe are that commit's too, so a fix there needs a new release. Docker Hub's tags API then confirms the push, as above. Such a fix must use only actions the organization's Actions allowlist accepts, or GitHub rejects the whole workflow at startup and nothing publishes; `make check-actions-allowlist` checks every workflow against `.github/actions-allowlist.toml` on every pull request, since pull-request CI never loads the publish workflows.
`workflow_dispatch` of `publish-pypi.yml` is the other path, needed when the failure calls for a change to the workflow file, since a re-run replays the file the run started with. **Once the release exists, a dispatch succeeds only from a ref whose head is the commit the release is tagged at** — the release pull request's base branch, `main` normally, while nothing further has landed on it. The tag names the merge commit, a dispatch ships the head of the ref it was dispatched from, and `github-release`'s tag guard refuses any other commit: a dispatch from `release/vX.Y.Z` is therefore always refused, although it is the ref the failed run is listed under. That dispatch recovers from PyPI rather than from an artifact, the release branch's build being keyed to a different commit, and the bytes are the same either way. A dispatch accepts `main`, `release/vX.Y.Z` and `pre-release/v*` and nothing else, and its run lists under the ref it was dispatched from rather than under the release branch.
diff --git a/.github/actions-allowlist.toml b/.github/actions-allowlist.toml
new file mode 100644
index 000000000..a2f533dc3
--- /dev/null
+++ b/.github/actions-allowlist.toml
@@ -0,0 +1,46 @@
+# The GitHub Actions policy of the Pipelex organization, mirrored for `make check-actions-allowlist`.
+#
+# GitHub refuses a whole workflow at startup when one of its `uses:` references is not allowed, and
+# the release workflows never run on a pull request, so a disallowed action there surfaces only when
+# a release is cut. The guard reads this file and refuses any reference the policy would refuse; the
+# specification is docs/contribute/actions-allowlist.md.
+#
+# The policy itself lives on GitHub, under the organization's Actions settings, and is enforced by
+# the enterprise. This file only mirrors it: when the policy changes, change this file to match what
+# `gh api orgs/Pipelex/actions/permissions/selected-actions` prints, keeping the patterns verbatim.
+
+# Actions created by GitHub, those of the `actions` and `github` owners.
+github_owned_allowed = true
+
+# Organizations the enterprise owns, whose actions the policy allows without a pattern.
+enterprise_owners = ["Pipelex"]
+
+# The policy's `patterns_allowed`, verbatim and in the order GitHub prints them.
+patterns_allowed = [
+ "Swatinem/rust-cache@*",
+ "PyO3/maturin-action@*",
+ "pypa/gh-action-pypi-publish@*",
+ "peaceiris/actions-gh-pages@*",
+ "sigstore/[email protected]",
+ "contributor-assistant/[email protected]",
+ "astral-sh/setup-uv@v3",
+ "softprops/action-gh-release@v2",
+ "astral-sh/setup-uv@v5",
+ "anthropics/claude-code-action@v1",
+ "oven-sh/setup-bun@*",
+ "aws-actions/configure-aws-credentials@v4",
+ "docker/setup-buildx-action@v3",
+ "dorny/paths-filter@v3",
+ "hashicorp/setup-terraform@v3",
+ "astral-sh/setup-uv@v4",
+ "astral-sh/setup-uv@*",
+ "dtolnay/rust-toolchain@*",
+ "terraform-linters/setup-tflint@v4",
+ "sigstore/gh-action-sigstore-python@f514d46b907ebcd5bedc05145c03b69c1edd8b46",
+ "pnpm/action-setup@v4",
+ "aws-actions/amazon-ecr-login@v2",
+ "docker/setup-qemu-action@v3",
+ "docker/build-push-action@v6",
+ "sigstore/gh-action-sigstore-python@790bc6befb9d733738f18d8f895854b453640ec9",
+ "softprops/action-gh-release@3d0d9888cb7fd7b750713d6e236d1fcb99157228",
+]
diff --git a/.github/workflows/lint-check.yml b/.github/workflows/lint-check.yml
index fc40d3fab..691654abf 100644
--- a/.github/workflows/lint-check.yml
+++ b/.github/workflows/lint-check.yml
@@ -180,6 +180,34 @@ jobs:
- name: Run Rich import check
run: make check-rich-imports
+# --------------------------------------------------------------------------
+# 6b. Actions allowlist — single job, version-independent. GitHub rejects a
+# whole workflow at startup when one of its actions is outside the
+# organization's Actions policy, and the release workflows never run on a
+# pull request, so this job reads every workflow against the policy's
+# mirror in .github/actions-allowlist.toml.
+# --------------------------------------------------------------------------
+ lint-actions-allowlist:
+ name: Lint (actions allowlist)
+ runs-on: ubuntu-latest
+ env:
+ VIRTUAL_ENV: ${{ github.workspace }}/.venv
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Install uv (with cache)
+ uses: astral-sh/setup-uv@v7
+ with:
+ enable-cache: true
+ cache-dependency-glob: "uv.lock"
+
+ - name: Install dependencies
+ run: PYTHON_VERSION=3.11 TEST_PROFILE=ci make install
+
+ - name: Run Actions allowlist check
+ run: make check-actions-allowlist
+
# --------------------------------------------------------------------------
# 7. Drift contracts — single job, version-independent
# BLOCKING, but through the ruleset rather than through lint-all: `Lint
@@ -280,15 +308,15 @@ jobs:
# --------------------------------------------------------------------------
# 10. Aggregator job — the required status check that covers every lint job,
# including the ones the rulesets do not name individually
-# (`Lint (hub layering)`, `Lint (rich imports)`, `Lint (agent-rules)`,
-# `Lint (api)`). It is not the only required lint check: the rulesets name
+# (`Lint (hub layering)`, `Lint (rich imports)`, `Lint (actions allowlist)`,
+# `Lint (agent-rules)`, `Lint (api)`). It is not the only required lint check: the rulesets name
# several of the jobs above by name as well. Anything added to `needs`
# becomes blocking through here.
# --------------------------------------------------------------------------
lint-all:
name: Lint (all)
runs-on: ubuntu-latest
- needs: [lint-ruff-plxt, lint-typecheck, lint-config-sync, lint-keyword-only, lint-hub-layering, lint-rich-imports, lint-agent-rules, lint-api]
+ needs: [lint-ruff-plxt, lint-typecheck, lint-config-sync, lint-keyword-only, lint-hub-layering, lint-rich-imports, lint-actions-allowlist, lint-agent-rules, lint-api]
if: always()
steps:
@@ -300,6 +328,7 @@ jobs:
[ "${{ needs.lint-keyword-only.result }}" != "success" ] || \
[ "${{ needs.lint-hub-layering.result }}" != "success" ] || \
[ "${{ needs.lint-rich-imports.result }}" != "success" ] || \
+ [ "${{ needs.lint-actions-allowlist.result }}" != "success" ] || \
[ "${{ needs.lint-agent-rules.result }}" != "success" ] || \
[ "${{ needs.lint-api.result }}" != "success" ]; then
echo "::error::At least one lint job failed."
diff --git a/.github/workflows/publish-docker-hub.yml b/.github/workflows/publish-docker-hub.yml
index e8934ce0c..8cd5225be 100644
--- a/.github/workflows/publish-docker-hub.yml
+++ b/.github/workflows/publish-docker-hub.yml
@@ -214,25 +214,3 @@ jobs:
echo "$SUMMARY."
echo "https://hub.docker.com/r/pipelex/pipelex-api"
} >> "$GITHUB_STEP_SUMMARY"
-
- # The Docker Hub overview is the server's README, pushed with the image of the newest stable
- # release so it never lags behind the repository. It is cosmetic beside the image, so a failure
- # here is a warning and not a failed release: the usual cause is a token without the
- # read/write/delete scope Docker Hub requires for editing a repository's description.
- - name: Update the Docker Hub overview from the server's README
- id: overview
- if: steps.release.outputs.push_latest == 'true'
- continue-on-error: true
- uses: peter-evans/dockerhub-description@1b9a80c056b620d92cedb9d9b5a223409c68ddfa # v5.0.0
- with:
- username: pipelex
- password: ${{ secrets.DOCKER_HUB_TOKEN }}
- repository: pipelex/pipelex-api
- readme-filepath: api/README.md
-
- - name: Report an overview that was not updated
- if: steps.release.outputs.push_latest == 'true' && steps.overview.outcome != 'success'
- run: >-
- echo "::warning::The image is published, but the Docker Hub overview was not updated from
- api/README.md. Check that DOCKER_HUB_TOKEN has the read/write/delete scope, then re-run this
- job, or paste the README into the repository's overview on Docker Hub."
diff --git a/AGENTS.md b/AGENTS.md
index edaf4b3bb..ce312b7ca 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -9,7 +9,7 @@
```bash
make agent-check
# If the current system doesn't have the `make` command,
- # lookup the "agent-check" target in the Makefile and run the commands one by one (targets fix-unused-imports fix-keyword-only format lint pyright mypy check-ledger check-keyword-only check-hub-layering check-rich-imports drift-check api-agent-check)
+ # lookup the "agent-check" target in the Makefile and run the commands one by one (targets fix-unused-imports fix-keyword-only format lint pyright mypy check-ledger check-keyword-only check-hub-layering check-rich-imports check-actions-allowlist drift-check api-agent-check)
```
This runs multiple code quality tools:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0e867efe2..76f9e50f5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -25,6 +25,7 @@
- **The API server refuses a deeply nested body the same way on every Python**: a JSON request body whose arrays and objects nest deeper than 128 levels, its own envelope included, is now refused before it is parsed, on every route that takes one, with a 422 `InvalidJSON` saying it is nested too deeply. On Python 3.14 whether the run routes refused such a body depended on the size of the thread's stack, so it could reach validation and fail as a `ValidationError` or be accepted, and the other routes answered it with a bare 400 rather than a problem document.
- **A client leaving mid-upload is a 400 in the API server's logs**: when a client disconnects before its request body arrived in full, the server answers a 400 `BadRequest` and logs it at warning level, where the run routes logged a 500 server fault with a traceback.
- **The API image runs methods by address**: the image carries `git`, which fetching a method named by `method_ref` needs, where the `0.33.2` image removed it with the build tools and failed every such run.
+- **A workflow action the organization does not allow is caught on its pull request**: GitHub rejects a whole workflow at startup when one of its actions is outside the organization's Actions policy, and pull-request CI never loads the release workflows, so such an action surfaced only as a release that published nothing. `make check-actions-allowlist` (alias `caa`), which `make agent-check` and the `Lint (actions allowlist)` CI job run, now refuses any workflow action outside the policy mirrored in `.github/actions-allowlist.toml`; see [Actions Allowlist](contribute/actions-allowlist.md).
## [v0.70.0] - 2026-09-29
diff --git a/CLAUDE.md b/CLAUDE.md
index 693fac15b..fb5be6159 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -4,7 +4,7 @@
`make` targets activate the virtual environment themselves; anything else (`pytest`, `pipelex`, `pipelex-dev`) runs from `.venv/bin/` (`.venv\Scripts\` on Windows), never bare. The Makefile is the reference for every target and alias; without `make`, read the target there and run its prerequisites one by one.
-- **`make agent-check` after every code change, and fix everything it reports.** Its prerequisites are `fix-unused-imports fix-keyword-only format lint pyright mypy check-ledger check-keyword-only check-hub-layering check-rich-imports drift-check api-agent-check`: the import and keyword-only fixers, ruff, pyright, mypy, `plxt` over TOML/MTHDS/PLX, the migration-ledger replay (`cl`), the hub-layering check, the Rich import check (`cri`: Rich is the `cli` extra, so no module outside `pipelex/cli/` imports it at module level or reaches it through a CLI module), the drift contracts, and the server's own gate. The drift digest reads the git index, so stage your changes before the check.
+- **`make agent-check` after every code change, and fix everything it reports.** Its prerequisites are `fix-unused-imports fix-keyword-only format lint pyright mypy check-ledger check-keyword-only check-hub-layering check-rich-imports check-actions-allowlist drift-check api-agent-check`: the import and keyword-only fixers, ruff, pyright, mypy, `plxt` over TOML/MTHDS/PLX, the migration-ledger replay (`cl`), the hub-layering check, the Rich import check (`cri`: Rich is the `cli` extra, so no module outside `pipelex/cli/` imports it at module level or reaches it through a CLI module), the Actions allowlist check (`caa`: every workflow action must be one `.github/actions-allowlist.toml` allows), the drift contracts, and the server's own gate. The drift digest reads the git index, so stage your changes before the check.
- **The Pipelex API server is the `api/` workspace member** (the `pipelex-api` distribution, package `pipelex_api`; its guide is `api/CLAUDE.md`). It runs the pipelex of the same commit from its own environment, `api/.venv`, which its targets provision themselves. `make agent-check` ends with `api-agent-check` (`make -C api agent-check`: its install, ruff, pyright, mypy, and the drift checks of its OpenAPI artifact and of its vendored inference tree) and `make agent-test` with `api-agent-test`, so a library change that breaks the server, moves its wire or leaves its inference tree behind fails in the same change. A kit change reaches the server's tree through `make up-kit-configs` (`ukc`); a change to the server's wire is committed with `make -C api openapi-export`.
- **Keyword-only arguments** (the convention is in the standards and in `docs/contribute/keyword-only-arguments.md`): `make check-keyword-only` (`cko`) is the gate, `make fix-keyword-only` (`fko`) inserts the bare `*` where it can — on ungranted subjects too — and reports the shapes it cannot fix, and `make subject-grant FUNC="<path>::<qualname>" RATIONALE="…"` (`sgr`) grants a positional subject. Grant before `make agent-check`, which runs the fixer.
- **Drift contracts.** When `make drift-check` reports an open contract: `make drift-plan`, review and fix the stale targets, `git add` the trigger files, then `make drift-ack CONTRACT=<id> RATIONALE="<verdict>: …"`, the rationale opening with its verdict, `real-catch`, `clean-pass` or `friction`. No bypass flag; "clean-pass: reviewed, no doc change needed" is a legitimate rationale. See `docs/contribute/drift-contracts.md` and the `/drift-review` skill.
diff --git a/Makefile b/Makefile
index 76bd92879..f82618121 100644
--- a/Makefile
+++ b/Makefile
@@ -188,6 +188,8 @@ make check-hub-layering - Enforce the runtime_hub / interpreter_hub layeri
make chl - Shorthand -> check-hub-layering
make check-rich-imports - Refuse a module-level Rich import or reach outside pipelex/cli/ (Rich is the cli extra)
make cri - Shorthand -> check-rich-imports
+make check-actions-allowlist - Refuse a workflow action outside the committed Actions allowlist
+make caa - Shorthand -> check-actions-allowlist
make check-TODOs - Check for TODOs
make docs - Serve documentation locally with mkdocs
@@ -227,7 +229,7 @@ export HELP
.PHONY: \
all help env env-verbose check-uv check-uv-verbose lock install update build \
format lint ruff-format ruff-lint pyright mypy pylint plxt plxt-format plxt-lint \
- rules rules-claude-standalone up-kit-configs ukc check-config-sync ccs check-keyword-only cko fix-keyword-only fko subject-grant sgr check-hub-layering chl check-rich-imports cri check-rules check-urls cu insert-skeleton \
+ rules rules-claude-standalone up-kit-configs ukc check-config-sync ccs check-keyword-only cko fix-keyword-only fko subject-grant sgr check-hub-layering chl check-rich-imports cri check-actions-allowlist caa check-rules check-urls cu insert-skeleton \
drift-plan dp drift-check dc drift-ack da \
cleanderived cleanenv cleanall \
test test-xdist t test-quiet tq test-with-prints tp test-inference ti \
@@ -413,6 +415,13 @@ check-rich-imports: env
cri: check-rich-imports
@echo "> done: cri = check-rich-imports"
+check-actions-allowlist: env
+ $(call PRINT_TITLE,"Refusing workflow actions the Actions allowlist does not name")
+ $(VENV_PIPELEX_DEV) check-actions-allowlist --quiet
+
+caa: check-actions-allowlist
+ @echo "> done: caa = check-actions-allowlist"
+
drift-plan: env
$(VENV_PIPELEX_DEV) drift plan $(CONTRACT)
@@ -1302,10 +1311,10 @@ cc: cleanderived regenerate-test-models-quiet generate-mthds-schema-quiet genera
up: generate-mthds-schema-quiet generate-corpus-vocabulary-quiet update-gateway-models-quiet up-kit-configs rules
@echo "> done: up = generate-mthds-schema generate-corpus-vocabulary update-gateway-models up-kit-configs rules"
-check: cleanderived regenerate-test-models-quiet generate-mthds-schema-quiet update-gateway-models-quiet check-unused-imports check-config-sync check-rules check-urls check-gateway-models check-mthds-schema check-ledger check-migration-schemas check-keyword-only check-hub-layering check-rich-imports drift-check format lint pyright mypy pylint
+check: cleanderived regenerate-test-models-quiet generate-mthds-schema-quiet update-gateway-models-quiet check-unused-imports check-config-sync check-rules check-urls check-gateway-models check-mthds-schema check-ledger check-migration-schemas check-keyword-only check-hub-layering check-rich-imports check-actions-allowlist drift-check format lint pyright mypy pylint
@echo "> done: check"
-agent-check: fix-unused-imports fix-keyword-only format lint pyright mypy check-ledger check-keyword-only check-hub-layering check-rich-imports drift-check api-agent-check
+agent-check: fix-unused-imports fix-keyword-only format lint pyright mypy check-ledger check-keyword-only check-hub-layering check-rich-imports check-actions-allowlist drift-check api-agent-check
@echo "> done: agent-check"
v: validate
diff --git a/api/CLAUDE.md b/api/CLAUDE.md
index cc2ad557b..159c83abc 100644
--- a/api/CLAUDE.md
+++ b/api/CLAUDE.md
@@ -12,7 +12,7 @@ This directory is the `api/` member of the pipelex repository's uv workspace: th
- **It has its own environment.** Every uv command in the Makefile targets `api/.venv` (`UV_PROJECT_ENVIRONMENT`), where `uv sync` installs this member with its extras and pipelex, in editable mode, with the server's extras and without `cli`. The targets that need the environment provision it, so a fresh worktree needs nothing run by hand first.
- **Its gate runs from the root.** The root `make agent-check` ends with `make -C api agent-check` and the root `make agent-test` with `make -C api agent-test`; run them here directly while working on the server. Upgrading dependencies is done for the whole workspace, at the root.
- **The image is built from the repository root** as its context, `docker build -f api/Dockerfile .`, which is what `make docker-build` runs, so the image installs the pipelex of the same commit. The root `.dockerignore` keeps that context to the files the build reads. `make docker-smoke` boots the image and checks that `/v1/version` reports this version for both the server and its pipelex.
-- **A pipelex release ships it.** The root's `.github/workflows/publish-pypi.yml` publishes the `pipelex-api` wheel and sdist once the `pipelex` wheel is on PyPI and the release is tagged, then calls `publish-docker-hub.yml` to push `pipelex/pipelex-api:X.Y.Z` from the commit the tag names through `make deploy-docker-hub`, which smoke-tests before it pushes. `latest` moves only to the newest stable release, and a version already on Docker Hub is never rebuilt. A failed push is retried by re-running the failed job, or by dispatching `publish-docker-hub.yml` with the version. `docs/contribute/api-server.md` at the root describes the whole chain.
+- **A pipelex release ships it.** The root's `.github/workflows/publish-pypi.yml` publishes the `pipelex-api` wheel and sdist once the `pipelex` wheel is on PyPI and the release is tagged, then calls `publish-docker-hub.yml` to push `pipelex/pipelex-api:X.Y.Z` from the commit the tag names through `make deploy-docker-hub`, which smoke-tests before it pushes. `latest` moves only to the newest stable release, and a version already on Docker Hub is never rebuilt. A failed push is retried by re-running the failed job, or by dispatching `publish-docker-hub.yml` with the version. The Docker Hub overview is not part of the chain and is still updated by hand from `README.md`. `docs/contribute/api-server.md` at the root describes the whole chain.
- **Its documentation is part of the pipelex docs site**: the pages are `docs/api-server/` at the repository root, served by the root `make docs` and checked by `make docs-check`, and published on docs.pipelex.com with each release. The committed OpenAPI artifact sits among them, at `docs/api-server/openapi/pipelex-api.openapi.yaml`.
## Project Structure
diff --git a/docs/contribute/actions-allowlist.md b/docs/contribute/actions-allowlist.md
new file mode 100644
index 000000000..060f9e765
--- /dev/null
+++ b/docs/contribute/actions-allowlist.md
@@ -0,0 +1,49 @@
+---
+title: "Actions Allowlist"
+description: "Why every action a workflow of this repository uses must be on the organization's Actions allowlist, the committed mirror of that allowlist, and the guard that checks every workflow against it on each pull request."
+---
+
+# Actions allowlist
+
+The Pipelex organization allows only some GitHub Actions to run, under a policy its enterprise enforces: actions created by GitHub, actions owned by the enterprise's organizations, and actions matching a list of patterns. GitHub applies that policy when it creates a run, and a workflow using an action the policy refuses does not run at all. GitHub ends it in `startup_failure`, with a message such as "The action … is not allowed in Pipelex/pipelex because all actions must be from a repository owned by your enterprise, created by GitHub, or match one of the patterns: …", before any of its jobs starts.
+
+Most workflows would show such a refusal on the pull request that introduced the action. The release workflows do not: `publish-pypi.yml` fires only when a release pull request closes into `main`, and `publish-docker-hub.yml` runs only from it or by hand, so pull-request CI never loads them. An action the policy refuses there surfaces only when a release is cut, as a release that publishes nothing. This is how a Docker Hub overview step once stopped a release.
+
+## The mirror: `.github/actions-allowlist.toml`
+
+The policy lives on GitHub, in the organization's Actions settings, and this repository cannot read it without an administrator's token. So the repository commits a mirror of it, `.github/actions-allowlist.toml`, with three keys:
+
+- `github_owned_allowed`: whether actions created by GitHub, those of the `actions` and `github` owners, are allowed.
+- `enterprise_owners`: the organizations the enterprise owns, whose actions are allowed without a pattern.
+- `patterns_allowed`: the policy's patterns, verbatim and in the order GitHub prints them.
+
+When the policy changes, the mirror changes with it. An administrator reads the policy with:
+
+```bash
+gh api orgs/Pipelex/actions/permissions/selected-actions
+```
+
+and copies `github_owned_allowed` and `patterns_allowed` into the mirror. The mirror only follows the policy: adding a pattern to it does not make GitHub run the action, so a new third-party action needs the policy changed first, and the mirror second.
+
+## The guard: `make check-actions-allowlist`
+
+```bash
+make check-actions-allowlist # alias: make caa
+```
+
+The guard (`pipelex-dev check-actions-allowlist`, core in `pipelex/cli/dev_cli/commands/actions_allowlist_guard.py`) runs in `make agent-check`, in the `make check` aggregate, and in CI as the `Lint (actions allowlist)` job, which the required `Lint (all)` aggregate waits for. It reads every workflow directly under `.github/workflows/`, every local action definition under `.github/actions/`, and every local action a `./` reference names wherever it lives in the repository, takes each `uses:` reference from where GitHub reads one (`jobs.<job>.steps[].uses` and `jobs.<job>.uses` in a workflow, `runs.steps[].uses` in a composite action), and allows it when it is:
+
+1. local, starting with `./`: an action or reusable workflow of this repository, whose own references the guard then reads in turn, since the policy applies to the actions a local composite action uses as well;
+2. created by GitHub, when `github_owned_allowed` is true;
+3. owned by an organization in `enterprise_owners`;
+4. matched by a pattern of `patterns_allowed`.
+
+Anything else fails the check, with the file, the line, the reference and the reason. A `docker://` image is refused as well, since no pattern can name one, and so is a `./` reference the guard cannot read: one that leaves the repository, names nothing, or names a directory with no `action.yml` or `action.yaml`.
+
+Patterns follow GitHub's syntax, and where that syntax leaves a doubt the guard takes the stricter reading, so that a pass here is a pass on GitHub: `*` matches any run of characters except `/`, `**` matches any run at all, and every comparison respects case, the owner and repository included, since GitHub does not document whether its policy check ignores case. A workflow therefore spells an owner as the mirror does, `PyO3/maturin-action`, never `pyo3/maturin-action`. `astral-sh/setup-uv@*` therefore allows every ref of that action, and `sigstore/gh-action-sigstore-python@790bc6befb9d733738f18d8f895854b453640ec9` allows that one commit only.
+
+The guard refuses to pass vacuously: a missing or malformed mirror, a workflow that is not valid YAML, or a scan that finds no workflow or no `uses:` reference at all fails the check instead of reporting a pass.
+
+## When the check fails
+
+Use an action GitHub created, one an organization of the enterprise owns, or one a pattern allows. When no allowed action does the job, a `run:` step calling the tool or the API directly usually does. When the action is worth allowing, ask an administrator to add it to the organization's policy, then mirror the new pattern in `.github/actions-allowlist.toml` in the same pull request as the workflow that uses it.
diff --git a/docs/contribute/api-server.md b/docs/contribute/api-server.md
index 44774ba10..a86c05794 100644
--- a/docs/contribute/api-server.md
+++ b/docs/contribute/api-server.md
@@ -68,8 +68,8 @@ A pipelex release publishes three artifacts under its one version, all from `.gi
1. **`pipelex` on PyPI**, as before: `build`, then `publish-to-pypi`, then `github-release`, which tags the release commit and refuses a commit an existing tag does not name.
2. **`pipelex-api` on PyPI**: `build-api` builds the server's wheel and sdist and refuses them unless `check_lockstep_pin.py` finds `pipelex[...]==X.Y.Z` in both. `publish-to-pypi` waits for it, so a server that does not build stops the release before `pipelex` is uploaded, while the version can still ship from a fixed commit. Then `publish-api-to-pypi` uploads them through trusted publishing in the same `pypi` environment. It waits for `github-release`, so the `pipelex` wheel they pin is on PyPI and the tag guard has accepted the commit they were built from before a file reaches PyPI, where it can never be replaced.
-3. **`pipelex/pipelex-api:X.Y.Z` on Docker Hub**: once both distributions are on PyPI, `publish-docker-hub` calls `.github/workflows/publish-docker-hub.yml` with the version. It checks out the commit the `vX.Y.Z` tag names, runs `make -C api deploy-docker-hub`, which builds the image, smoke-tests it and pushes it, confirms the tags through Docker Hub's API, and pushes `api/README.md` as the Docker Hub overview. `latest` moves only when the version is the newest stable release, so a pre-release, or a retry of an older release, leaves it where it is.
+3. **`pipelex/pipelex-api:X.Y.Z` on Docker Hub**: once both distributions are on PyPI, `publish-docker-hub` calls `.github/workflows/publish-docker-hub.yml` with the version. It checks out the commit the `vX.Y.Z` tag names, runs `make -C api deploy-docker-hub`, which builds the image, smoke-tests it and pushes it, and confirms the tags through Docker Hub's API. `latest` moves only when the version is the newest stable release, so a pre-release, or a retry of an older release, leaves it where it is. The Docker Hub overview is not part of the release: it is still updated by hand, by pasting `api/README.md` into the repository's overview on Docker Hub when it has changed.
-A failed publish is retried with "Re-run failed jobs" on the release run, which re-runs only what failed. A version Docker Hub already serves is never built again, because a rebuild would be a different image under the same tag: a retry that finds it there only moves `latest`, when the version is the newest stable release, and confirms the tags. The image can also be published on its own with `gh workflow run publish-docker-hub.yml --ref <branch> -f version=X.Y.Z`, which helps when the fix is a change to that workflow file, which a re-run would not pick up: dispatched from the branch carrying the fix, it still builds the commit the tag names.
+A failed publish is retried with "Re-run failed jobs" on the release run, which re-runs only what failed. A version Docker Hub already serves is never built again, because a rebuild would be a different image under the same tag: a retry that finds it there only moves `latest`, when the version is the newest stable release, and confirms the tags. The image can also be published on its own with `gh workflow run publish-docker-hub.yml --ref <branch> -f version=X.Y.Z`, which helps when the fix is a change to that workflow file, which a re-run would not pick up: dispatched from the branch carrying the fix, it still builds the commit the tag names. Such a fix must use only actions the organization's Actions policy allows, or GitHub rejects the whole workflow at startup and nothing publishes; pull-request CI never loads these workflows, so [`make check-actions-allowlist`](actions-allowlist.md) checks every workflow against the policy's mirror on each pull request.
-What the release needs configured on GitHub and PyPI: the `DOCKER_HUB_TOKEN` secret on the repository, a token for the `pipelex` Docker Hub account that can push the image and, for the overview, has the read/write/delete scope; and a PyPI trusted publisher for the `pipelex-api` project with owner `Pipelex`, repository `pipelex`, workflow `publish-pypi.yml` and environment `pypi`, the same as `pipelex`'s.
+What the release needs configured on GitHub and PyPI: the `DOCKER_HUB_TOKEN` secret on the repository, a token for the `pipelex` Docker Hub account that can push the image; and a PyPI trusted publisher for the `pipelex-api` project with owner `Pipelex`, repository `pipelex`, workflow `publish-pypi.yml` and environment `pypi`, the same as `pipelex`'s.
diff --git a/mkdocs.yml b/mkdocs.yml
index 37002be6b..6c15d031c 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -365,6 +365,7 @@ plugins:
- contribute/keyword-only-arguments.md: "Keyword-Only Arguments"
- contribute/hub-layering.md: "Hub Layering"
- contribute/rich-imports.md: "Rich Imports"
+ - contribute/actions-allowlist.md: "Actions Allowlist"
- contribute/test-duration-map.md: "Test Duration Map"
- contribute/registration-surface.md: "Registration Surface"
- contribute/drift-contracts.md: "Drift Contracts"
@@ -616,6 +617,7 @@ nav:
- Keyword-Only Arguments: contribute/keyword-only-arguments.md
- Hub Layering: contribute/hub-layering.md
- Rich Imports: contribute/rich-imports.md
+ - Actions Allowlist: contribute/actions-allowlist.md
- Test Duration Map: contribute/test-duration-map.md
- Registration Surface: contribute/registration-surface.md
- Drift Contracts: contribute/drift-contracts.md
diff --git a/pipelex/cli/dev_cli/_dev_cli.py b/pipelex/cli/dev_cli/_dev_cli.py
index db1f6030a..1d6487853 100644
--- a/pipelex/cli/dev_cli/_dev_cli.py
+++ b/pipelex/cli/dev_cli/_dev_cli.py
@@ -10,6 +10,7 @@ from rich.traceback import Traceback
from typer.core import TyperGroup
from typing_extensions import override
+from pipelex.cli.dev_cli.commands.check_actions_allowlist_cmd import check_actions_allowlist_cmd
from pipelex.cli.dev_cli.commands.check_config_sync_cmd import LeadingConfig, check_config_sync_cmd
from pipelex.cli.dev_cli.commands.check_gateway_models_cmd import check_gateway_models_cmd
from pipelex.cli.dev_cli.commands.check_hub_layering_cmd import check_hub_layering_cmd
@@ -47,6 +48,7 @@ class PipelexDevCLI(TyperGroup):
def list_commands(self, ctx: Context) -> list[str]:
"""List commands in proper order."""
return [
+ "check-actions-allowlist",
"check-config-sync",
"check-gateway-models",
"check-hub-layering",
@@ -402,6 +404,28 @@ def check_hub_layering_command(
sys.exit(1)
[email protected](name="check-actions-allowlist", help="Refuse a workflow action the organization's Actions policy would refuse")
+def check_actions_allowlist_command(
+ quiet: Annotated[
+ bool, typer.Option("--quiet", "-q", help="Light output on success (single line); the full violation list still prints on failure")
+ ] = False,
+) -> None:
+ """Refuse a workflow action outside the Actions allowlist mirrored in .github/actions-allowlist.toml."""
+ try:
+ check_actions_allowlist_cmd(quiet=quiet)
+ except (typer.Exit, typer.Abort):
+ # Typer control-flow exits carry an intended exit code — not a failure. Let them through.
+ raise
+ except Exception: # ruff: ignore[blind-except]
+ # Dev CLI command root: print a traceback for any unexpected failure and exit non-zero.
+ console = get_console()
+ console.print()
+ console.print("[bold red]Unexpected error occurred[/bold red]")
+ console.print()
+ console.print(Traceback())
+ sys.exit(1)
+
+
@app.command(name="check-rich-imports", help="Refuse a module-level Rich import or reach outside pipelex/cli/ (Rich is the cli extra)")
def check_rich_imports_command(
quiet: Annotated[
diff --git a/pipelex/cli/dev_cli/commands/actions_allowlist_exceptions.py b/pipelex/cli/dev_cli/commands/actions_allowlist_exceptions.py
new file mode 100644
index 000000000..387d4c3be
--- /dev/null
+++ b/pipelex/cli/dev_cli/commands/actions_allowlist_exceptions.py
@@ -0,0 +1,7 @@
+class ActionsAllowlistGuardError(Exception):
+ """The Actions allowlist guard cannot run as configured: a missing or malformed allowlist, an unreadable workflow, or nothing to scan.
+
+ A plain ``Exception`` rather than a ``PipelexError``: it never leaves the ``pipelex-dev check-actions-allowlist``
+ command, which reports it as a failed check, so it carries no ``error_type`` on any wire and has no page in the
+ error reference.
+ """
diff --git a/pipelex/cli/dev_cli/commands/actions_allowlist_guard.py b/pipelex/cli/dev_cli/commands/actions_allowlist_guard.py
new file mode 100644
index 000000000..9cdd2f7d5
--- /dev/null
+++ b/pipelex/cli/dev_cli/commands/actions_allowlist_guard.py
@@ -0,0 +1,380 @@
+"""Core of the Actions allowlist guard.
+
+GitHub checks every action a workflow uses against the organization's Actions policy when it creates
+the run, and a workflow using one the policy refuses does not run at all: GitHub ends it in
+``startup_failure`` before any job starts. The release workflows fire only when a release pull request
+closes into ``main``, so pull-request CI never loads them, and an action the policy refuses there
+surfaces only when a release is cut, as a release that publishes nothing.
+
+This guard reads every workflow directly under ``.github/workflows/``, every local action under
+``.github/actions/``, and every local action a ``./…`` reference names wherever it lives in the repository,
+and refuses each ``uses:`` reference the policy mirrored in ``.github/actions-allowlist.toml`` would refuse.
+A reference is allowed when it is:
+
+1. local (``./…``), an action or reusable workflow of this repository, whose own ``uses:`` references are
+ then read in turn, since the policy applies to the actions a local composite action uses as well;
+2. created by GitHub (the ``actions`` and ``github`` owners), when the policy allows GitHub's actions;
+3. owned by one of the enterprise's organizations listed in ``enterprise_owners``;
+4. matched by one of ``patterns_allowed``.
+
+Patterns follow GitHub's syntax. Where that syntax leaves a doubt, the guard takes the stricter reading,
+so that a pass here is a pass on GitHub: ``*`` matches any run of characters except ``/`` and ``**`` any
+run at all, and every comparison respects case, the owner and repository included, since GitHub does not
+document whether its policy check ignores case. A ``docker://`` image is refused too, since no pattern can
+name one.
+
+The human-readable specification lives in ``docs/contribute/actions-allowlist.md``. The presentation
+layer wired into the ``pipelex-dev`` Typer app lives in ``check_actions_allowlist_cmd.py``.
+"""
+
+from __future__ import annotations
+
+import re
+import tomllib
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, NamedTuple, cast
+
+import yaml
+
+from pipelex.cli.dev_cli.commands.actions_allowlist_exceptions import ActionsAllowlistGuardError
+
+if TYPE_CHECKING:
+ from collections.abc import Iterator
+
+#: The committed mirror of the organization's Actions policy, relative to the repo root.
+ALLOWLIST_FILE = Path(".github/actions-allowlist.toml")
+
+#: Where GitHub reads workflows from: the files directly in this directory, never in a subdirectory.
+WORKFLOWS_DIR = Path(".github/workflows")
+
+#: Where this repository would keep its own composite actions, each in an ``action.yml``.
+LOCAL_ACTIONS_DIR = Path(".github/actions")
+
+#: The suffixes GitHub reads a workflow or an action definition from.
+YAML_SUFFIXES = frozenset({".yml", ".yaml"})
+
+#: The file names of an action definition.
+ACTION_FILE_NAMES = frozenset({"action.yml", "action.yaml"})
+
+#: The owners of the actions GitHub creates, which ``github_owned_allowed`` allows.
+GITHUB_OWNERS = frozenset({"actions", "github"})
+
+#: The prefix of a reference to an action or reusable workflow of this repository.
+LOCAL_PREFIX = "./"
+
+#: The prefix of a step that runs a Docker image rather than an action.
+DOCKER_PREFIX = "docker://"
+
+#: The complete set of keys the allowlist file carries; anything else fails the check.
+_ALLOWLIST_KEYS = frozenset({"github_owned_allowed", "enterprise_owners", "patterns_allowed"})
+
+REMEDY = (
+ "use an action GitHub created, one an organization of the enterprise owns or one a pattern allows, or replace the step "
+ "with a `run:` script; when the organization's policy itself changed, mirror it in .github/actions-allowlist.toml"
+)
+
+
+class ActionsAllowlist(NamedTuple):
+ """The organization's Actions policy, as mirrored in ``.github/actions-allowlist.toml``.
+
+ Attributes:
+ github_owned_allowed: Whether actions created by GitHub are allowed.
+ enterprise_owners: The enterprise's organizations, as GitHub spells them, whose actions are allowed.
+ patterns_allowed: The policy's patterns, verbatim.
+ """
+
+ github_owned_allowed: bool
+ enterprise_owners: frozenset[str]
+ patterns_allowed: tuple[str, ...]
+
+
+class ActionReference(NamedTuple):
+ """One ``uses:`` value found in a workflow or an action definition, located for a report line."""
+
+ relative_path: str
+ lineno: int
+ reference: str
+
+
+class ActionsAllowlistViolation(NamedTuple):
+ """One ``uses:`` reference the policy would refuse, with the reason."""
+
+ relative_path: str
+ lineno: int
+ reference: str
+ detail: str
+
+ @property
+ def key(self) -> str:
+ """Stable sort key: file, then line."""
+ return f"{self.relative_path}:{self.lineno:06d}"
+
+
+def _string_list(*, raw: dict[str, Any], key: str, path: Path) -> list[str]:
+ """Return ``raw[key]`` as a list of non-empty strings, or raise naming the file and the key."""
+ value = raw.get(key)
+ if not isinstance(value, list):
+ msg = f"the Actions allowlist '{path}' must set `{key}` to a list of strings"
+ raise ActionsAllowlistGuardError(msg)
+ items = cast("list[Any]", value)
+ strings: list[str] = []
+ for item in items:
+ if not isinstance(item, str) or not item.strip():
+ msg = f"the Actions allowlist '{path}' holds {item!r} in `{key}`, where every entry must be a non-empty string"
+ raise ActionsAllowlistGuardError(msg)
+ strings.append(item)
+ return strings
+
+
+def load_allowlist(*, path: Path) -> ActionsAllowlist:
+ """Load and validate the committed mirror of the organization's Actions policy.
+
+ Args:
+ path: The allowlist file.
+
+ Returns:
+ The policy.
+
+ Raises:
+ ActionsAllowlistGuardError: When the file is missing, is not valid TOML, carries an unknown key, or
+ misses or mistypes one of the keys it must carry. A missing allowlist is an error, never an empty
+ policy, which would refuse every action in the repository.
+ """
+ if not path.is_file():
+ msg = f"the Actions allowlist was not found at '{path}'. It is committed in the repository; run the check from the repo root."
+ raise ActionsAllowlistGuardError(msg)
+ try:
+ raw = tomllib.loads(path.read_text(encoding="utf-8"))
+ except tomllib.TOMLDecodeError as exc:
+ msg = f"the Actions allowlist '{path}' is not valid TOML: {exc}"
+ raise ActionsAllowlistGuardError(msg) from exc
+ unknown_keys = set(raw) - _ALLOWLIST_KEYS
+ if unknown_keys:
+ msg = f"the Actions allowlist '{path}' has unknown key(s): {sorted(unknown_keys)}"
+ raise ActionsAllowlistGuardError(msg)
+ github_owned_allowed = raw.get("github_owned_allowed")
+ if not isinstance(github_owned_allowed, bool):
+ msg = f"the Actions allowlist '{path}' must set `github_owned_allowed` to true or false"
+ raise ActionsAllowlistGuardError(msg)
+ enterprise_owners = _string_list(raw=raw, key="enterprise_owners", path=path)
+ patterns_allowed = _string_list(raw=raw, key="patterns_allowed", path=path)
+ return ActionsAllowlist(
+ github_owned_allowed=github_owned_allowed,
+ enterprise_owners=frozenset(enterprise_owners),
+ patterns_allowed=tuple(patterns_allowed),
+ )
+
+
+def _pattern_regex(*, pattern: str) -> re.Pattern[str]:
+ """Translate a policy pattern into a regular expression: ``**`` matches anything, ``*`` anything but ``/``."""
+ parts: list[str] = []
+ index = 0
+ while index < len(pattern):
+ if pattern.startswith("**", index):
+ parts.append(".*")
+ index += 2
+ elif pattern[index] == "*":
+ parts.append("[^/]*")
+ index += 1
+ else:
+ parts.append(re.escape(pattern[index]))
+ index += 1
+ return re.compile("".join(parts))
+
+
+def pattern_matches(*, pattern: str, reference: str) -> bool:
+ """Whether a policy pattern allows a reference, read the strict way the module docstring describes."""
+ return _pattern_regex(pattern=pattern).fullmatch(reference) is not None
+
+
+def refusal_reason(*, reference: str, allowlist: ActionsAllowlist) -> str | None:
+ """Say why the policy would refuse a ``uses:`` reference, or return ``None`` when it allows it.
+
+ Args:
+ reference: The ``uses:`` value, as written in the workflow.
+ allowlist: The policy to check it against.
+
+ Returns:
+ ``None`` for an allowed reference, else a short reason for the report line.
+ """
+ if reference.startswith(LOCAL_PREFIX):
+ return None
+ if reference.startswith(DOCKER_PREFIX):
+ return "is a Docker image, which no pattern of the policy can name"
+ name, separator, ref = reference.partition("@")
+ segments = name.split("/")
+ if not separator or not ref or len(segments) < 2 or not all(segments):
+ return "is not of the form `owner/repository[/path]@ref`"
+ owner = segments[0]
+ if allowlist.github_owned_allowed and owner in GITHUB_OWNERS:
+ return None
+ if owner in allowlist.enterprise_owners:
+ return None
+ for pattern in allowlist.patterns_allowed:
+ if pattern_matches(pattern=pattern, reference=reference):
+ return None
+ return "is not created by GitHub, not owned by the enterprise, and matched by no pattern of the policy"
+
+
+def _mapping_value(*, node: yaml.Node | None, key: str) -> yaml.Node | None:
+ """Return the value under ``key`` when ``node`` is a mapping holding it, else ``None``."""
+ if not isinstance(node, yaml.MappingNode):
+ return None
+ pairs = cast("list[tuple[yaml.Node, yaml.Node]]", node.value)
+ for key_node, value_node in pairs:
+ if isinstance(key_node, yaml.ScalarNode) and key_node.value == key:
+ return value_node
+ return None
+
+
+def _uses_in_steps(*, steps: yaml.Node | None) -> Iterator[yaml.Node]:
+ """Yield the ``uses:`` value of every step in a ``steps:`` sequence."""
+ if not isinstance(steps, yaml.SequenceNode):
+ return
+ step_nodes = cast("list[yaml.Node]", steps.value)
+ for step in step_nodes:
+ uses = _mapping_value(node=step, key="uses")
+ if uses is not None:
+ yield uses
+
+
+def _uses_nodes(*, document: yaml.Node) -> Iterator[yaml.Node]:
+ """Yield every ``uses:`` value of a workflow or an action definition.
+
+ A workflow names actions in ``jobs.<job>.steps[].uses`` and reusable workflows in ``jobs.<job>.uses``;
+ a composite action names actions in ``runs.steps[].uses``. A ``uses`` key anywhere else, under a step's
+ ``with:`` for instance, is an input and not a reference, so the walk follows that structure rather than
+ every key of the document.
+ """
+ jobs = _mapping_value(node=document, key="jobs")
+ if isinstance(jobs, yaml.MappingNode):
+ job_pairs = cast("list[tuple[yaml.Node, yaml.Node]]", jobs.value)
+ for _job_key, job in job_pairs:
+ job_uses = _mapping_value(node=job, key="uses")
+ if job_uses is not None:
+ yield job_uses
+ yield from _uses_in_steps(steps=_mapping_value(node=job, key="steps"))
+ yield from _uses_in_steps(steps=_mapping_value(node=_mapping_value(node=document, key="runs"), key="steps"))
+
+
+def find_references_in_source(*, source: str, relative_path: str) -> list[ActionReference]:
+ """Return every ``uses:`` reference of one workflow or action definition, with its line.
+
+ Args:
+ source: The YAML text.
+ relative_path: The file's repo-root-relative posix path, for the report.
+
+ Returns:
+ The references in document order. A ``uses:`` that is not a string is returned with its YAML text,
+ so that the check refuses it rather than skipping it.
+
+ Raises:
+ ActionsAllowlistGuardError: When the file is not valid YAML, since an unread file is an unchecked one.
+ """
+ # The loader's own composer, which is what `yaml.compose_all` drives: it keeps each node's line.
+ loader = yaml.SafeLoader(source)
+ documents: list[yaml.Node] = []
+ try:
+ while loader.check_node():
+ document = loader.get_node()
+ if document is not None:
+ documents.append(document)
+ except yaml.YAMLError as exc:
+ msg = f"'{relative_path}' is not valid YAML, so its actions cannot be checked: {exc}"
+ raise ActionsAllowlistGuardError(msg) from exc
+ references: list[ActionReference] = []
+ for document in documents:
+ for node in _uses_nodes(document=document):
+ reference = node.value if isinstance(node, yaml.ScalarNode) else f"<{node.tag}>"
+ references.append(ActionReference(relative_path=relative_path, lineno=node.start_mark.line + 1, reference=str(reference)))
+ return references
+
+
+def iter_workflow_files(*, root: Path) -> Iterator[Path]:
+ """Yield, sorted, every workflow GitHub would read and every local action definition under ``root``."""
+ workflows_dir = root / WORKFLOWS_DIR
+ if workflows_dir.is_dir():
+ for path in sorted(workflows_dir.iterdir()):
+ if path.is_file() and path.suffix in YAML_SUFFIXES:
+ yield path
+ actions_dir = root / LOCAL_ACTIONS_DIR
+ if actions_dir.is_dir():
+ for path in sorted(actions_dir.rglob("*")):
+ if path.is_file() and path.name in ACTION_FILE_NAMES:
+ yield path
+
+
+def _local_definition(*, root: Path, reference: str) -> tuple[Path | None, str | None]:
+ """Find the file a ``./…`` reference names, so that its own references can be read in turn.
+
+ A reference to a workflow file names that file; any other names a directory holding ``action.yml`` or
+ ``action.yaml``, which is how GitHub finds a local action wherever it lives in the repository.
+
+ Args:
+ root: The repo root.
+ reference: The ``uses:`` value, starting with ``./``.
+
+ Returns:
+ The file to read and no reason, or no file and the reason the guard cannot read the definition, which
+ the check reports, since an action it cannot read is an action it has not checked.
+ """
+ root_resolved = root.resolve()
+ target = (root / reference.removeprefix(LOCAL_PREFIX)).resolve()
+ if not target.is_relative_to(root_resolved):
+ return None, "names a path outside the repository"
+ relative_target = target.relative_to(root_resolved)
+ if target.is_file() and target.suffix in YAML_SUFFIXES:
+ return root / relative_target, None
+ if target.is_dir():
+ for file_name in sorted(ACTION_FILE_NAMES):
+ if (target / file_name).is_file():
+ return root / relative_target / file_name, None
+ return None, "names a local action with no action.yml or action.yaml, which the guard cannot read"
+ return None, "names a local action or workflow that does not exist"
+
+
+def collect_violations(*, root: Path) -> list[ActionsAllowlistViolation]:
+ """Check every ``uses:`` reference under ``root`` against the committed allowlist, and return the refusals sorted.
+
+ The scan starts from the workflows and the ``.github/actions/`` definitions, and reads every local action or
+ reusable workflow a ``./…`` reference names as well, once each, wherever it lives in the repository.
+
+ Args:
+ root: The repo root, which holds ``.github/``.
+
+ Raises:
+ ActionsAllowlistGuardError: When the allowlist cannot be loaded, a workflow is not valid YAML, or the scan
+ finds no workflow or no reference at all. The last two mean the root is not the repo root or the walk
+ no longer reads GitHub's structure, and the guard would otherwise report a pass having checked nothing.
+ """
+ allowlist = load_allowlist(path=root / ALLOWLIST_FILE)
+ violations: list[ActionsAllowlistViolation] = []
+ pending = list(iter_workflow_files(root=root))
+ seen = {path.resolve() for path in pending}
+ nb_files = 0
+ nb_references = 0
+ while pending:
+ path = pending.pop(0)
+ nb_files += 1
+ relative_path = path.relative_to(root).as_posix()
+ for found in find_references_in_source(source=path.read_text(encoding="utf-8"), relative_path=relative_path):
+ nb_references += 1
+ reason: str | None
+ if found.reference.startswith(LOCAL_PREFIX):
+ definition, reason = _local_definition(root=root, reference=found.reference)
+ if definition is not None and definition.resolve() not in seen:
+ seen.add(definition.resolve())
+ pending.append(definition)
+ else:
+ reason = refusal_reason(reference=found.reference, allowlist=allowlist)
+ if reason is not None:
+ violations.append(
+ ActionsAllowlistViolation(relative_path=found.relative_path, lineno=found.lineno, reference=found.reference, detail=reason)
+ )
+ if nb_files == 0 or nb_references == 0:
+ msg = (
+ f"the Actions allowlist guard read {nb_files} workflow file(s) under `{root / WORKFLOWS_DIR}` and found "
+ f"{nb_references} `uses:` reference(s), so it checked nothing. Run it from the repo root."
+ )
+ raise ActionsAllowlistGuardError(msg)
+ return sorted(violations, key=lambda violation: violation.key)
diff --git a/pipelex/cli/dev_cli/commands/check_actions_allowlist_cmd.py b/pipelex/cli/dev_cli/commands/check_actions_allowlist_cmd.py
new file mode 100644
index 000000000..72832a751
--- /dev/null
+++ b/pipelex/cli/dev_cli/commands/check_actions_allowlist_cmd.py
@@ -0,0 +1,85 @@
+"""Command refusing any GitHub Actions ``uses:`` reference the organization's Actions policy would refuse.
+
+The scan lives in the ``actions_allowlist_guard`` module; this module is the presentation layer wired into the
+``pipelex-dev`` Typer app (``make check-actions-allowlist`` / ``make agent-check`` / ``make check`` / CI). The
+human-readable specification lives in ``docs/contribute/actions-allowlist.md``.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+from rich.markup import escape
+from rich.panel import Panel
+
+from pipelex.cli.dev_cli.commands.actions_allowlist_exceptions import ActionsAllowlistGuardError
+from pipelex.cli.dev_cli.commands.actions_allowlist_guard import (
+ ALLOWLIST_FILE,
+ REMEDY,
+ ActionsAllowlistViolation,
+ collect_violations,
+)
+from pipelex.runtime_hub import get_console
+
+
+def check_actions_allowlist_cmd(*, quiet: bool = False) -> None:
+ """Refuse every workflow action the organization's Actions policy, mirrored in the repository, would refuse.
+
+ Args:
+ quiet: If True, keep the success output to a single line (for Make targets / CI). Quiet only trims
+ the happy path: a failure still prints every offending reference.
+ """
+ console = get_console()
+
+ try:
+ violations = collect_violations(root=Path())
+ except ActionsAllowlistGuardError as exc:
+ # An error is always loud: quiet only trims success output, never failures.
+ console.print(f"[red]✗ Actions allowlist check: FAILED[/red] - {escape(str(exc))}")
+ sys.exit(1)
+
+ if not violations:
+ if quiet:
+ console.print("[green]✓ Actions allowlist check: PASSED[/green]")
+ else:
+ console.print()
+ console.print(
+ Panel(
+ f"[green]✓[/green] Every action the workflows use is one the policy mirrored in [cyan]{escape(ALLOWLIST_FILE.as_posix())}[/cyan] "
+ "allows.",
+ title="[bold green]Actions Allowlist Check: PASSED[/bold green]",
+ border_style="green",
+ padding=(1, 2),
+ )
+ )
+ console.print()
+ return
+
+ if quiet:
+ console.print(f"[red]✗ Actions allowlist check: FAILED[/red] - {len(violations)} refused action(s):")
+ else:
+ console.print()
+ console.print(
+ Panel(
+ f"[red]✗[/red] {len(violations)} action(s) the policy mirrored in [cyan]{escape(ALLOWLIST_FILE.as_posix())}[/cyan] refuses.\n\n"
+ "[dim]GitHub rejects a whole workflow at startup when one of its actions is not allowed.[/dim]",
+ title="[bold red]Actions Allowlist Check: FAILED[/bold red]",
+ border_style="red",
+ padding=(1, 2),
+ )
+ )
+ console.print()
+ _print_violations(violations=violations)
+ sys.exit(1)
+
+
+def _print_violations(*, violations: list[ActionsAllowlistViolation]) -> None:
+ """Print each refused reference, then the remedy once."""
+ console = get_console()
+ for violation in violations:
+ console.print(
+ f" [red]{escape(violation.relative_path)}:{violation.lineno}[/red] [cyan]{escape(violation.reference)}[/cyan] "
+ f"[yellow]{escape(violation.detail)}[/yellow]"
+ )
+ console.print(f"[dim]Remedy: {escape(REMEDY)}. See docs/contribute/actions-allowlist.md[/dim]")
diff --git a/pipelex/kit/agent_rules/codex_commands.md b/pipelex/kit/agent_rules/codex_commands.md
index 5e1696ef3..c9afa27e9 100644
--- a/pipelex/kit/agent_rules/codex_commands.md
+++ b/pipelex/kit/agent_rules/codex_commands.md
@@ -7,7 +7,7 @@
```bash
make agent-check
# If the current system doesn't have the `make` command,
- # lookup the "agent-check" target in the Makefile and run the commands one by one (targets fix-unused-imports fix-keyword-only format lint pyright mypy check-ledger check-keyword-only check-hub-layering check-rich-imports drift-check api-agent-check)
+ # lookup the "agent-check" target in the Makefile and run the commands one by one (targets fix-unused-imports fix-keyword-only format lint pyright mypy check-ledger check-keyword-only check-hub-layering check-rich-imports check-actions-allowlist drift-check api-agent-check)
```
This runs multiple code quality tools:
diff --git a/pipelex/kit/agent_rules/commands.md b/pipelex/kit/agent_rules/commands.md
index 6b4fb6c01..832a24a4d 100644
--- a/pipelex/kit/agent_rules/commands.md
+++ b/pipelex/kit/agent_rules/commands.md
@@ -2,7 +2,7 @@
`make` targets activate the virtual environment themselves; anything else (`pytest`, `pipelex`, `pipelex-dev`) runs from `.venv/bin/` (`.venv\Scripts\` on Windows), never bare. The Makefile is the reference for every target and alias; without `make`, read the target there and run its prerequisites one by one.
-- **`make agent-check` after every code change, and fix everything it reports.** Its prerequisites are `fix-unused-imports fix-keyword-only format lint pyright mypy check-ledger check-keyword-only check-hub-layering check-rich-imports drift-check api-agent-check`: the import and keyword-only fixers, ruff, pyright, mypy, `plxt` over TOML/MTHDS/PLX, the migration-ledger replay (`cl`), the hub-layering check, the Rich import check (`cri`: Rich is the `cli` extra, so no module outside `pipelex/cli/` imports it at module level or reaches it through a CLI module), the drift contracts, and the server's own gate. The drift digest reads the git index, so stage your changes before the check.
+- **`make agent-check` after every code change, and fix everything it reports.** Its prerequisites are `fix-unused-imports fix-keyword-only format lint pyright mypy check-ledger check-keyword-only check-hub-layering check-rich-imports check-actions-allowlist drift-check api-agent-check`: the import and keyword-only fixers, ruff, pyright, mypy, `plxt` over TOML/MTHDS/PLX, the migration-ledger replay (`cl`), the hub-layering check, the Rich import check (`cri`: Rich is the `cli` extra, so no module outside `pipelex/cli/` imports it at module level or reaches it through a CLI module), the Actions allowlist check (`caa`: every workflow action must be one `.github/actions-allowlist.toml` allows), the drift contracts, and the server's own gate. The drift digest reads the git index, so stage your changes before the check.
- **The Pipelex API server is the `api/` workspace member** (the `pipelex-api` distribution, package `pipelex_api`; its guide is `api/CLAUDE.md`). It runs the pipelex of the same commit from its own environment, `api/.venv`, which its targets provision themselves. `make agent-check` ends with `api-agent-check` (`make -C api agent-check`: its install, ruff, pyright, mypy, and the drift checks of its OpenAPI artifact and of its vendored inference tree) and `make agent-test` with `api-agent-test`, so a library change that breaks the server, moves its wire or leaves its inference tree behind fails in the same change. A kit change reaches the server's tree through `make up-kit-configs` (`ukc`); a change to the server's wire is committed with `make -C api openapi-export`.
- **Keyword-only arguments** (the convention is in the standards and in `docs/contribute/keyword-only-arguments.md`): `make check-keyword-only` (`cko`) is the gate, `make fix-keyword-only` (`fko`) inserts the bare `*` where it can — on ungranted subjects too — and reports the shapes it cannot fix, and `make subject-grant FUNC="<path>::<qualname>" RATIONALE="…"` (`sgr`) grants a positional subject. Grant before `make agent-check`, which runs the fixer.
- **Drift contracts.** When `make drift-check` reports an open contract: `make drift-plan`, review and fix the stale targets, `git add` the trigger files, then `make drift-ack CONTRACT=<id> RATIONALE="<verdict>: …"`, the rationale opening with its verdict, `real-catch`, `clean-pass` or `friction`. No bypass flag; "clean-pass: reviewed, no doc change needed" is a legitimate rationale. See `docs/contribute/drift-contracts.md` and the `/drift-review` skill.
diff --git a/tests/unit/pipelex/cli/dev/test_actions_allowlist_guard.py b/tests/unit/pipelex/cli/dev/test_actions_allowlist_guard.py
new file mode 100644
index 000000000..f4f626c99
--- /dev/null
+++ b/tests/unit/pipelex/cli/dev/test_actions_allowlist_guard.py
@@ -0,0 +1,259 @@
+from __future__ import annotations
+
+import textwrap
+from pathlib import Path
+
+import pytest
+
+from pipelex.cli.dev_cli.commands.actions_allowlist_exceptions import ActionsAllowlistGuardError
+from pipelex.cli.dev_cli.commands.actions_allowlist_guard import (
+ ALLOWLIST_FILE,
+ ActionsAllowlist,
+ collect_violations,
+ find_references_in_source,
+ iter_workflow_files,
+ load_allowlist,
+ pattern_matches,
+ refusal_reason,
+)
+
+#: Anchored on `tests/` by name rather than by a parent count, for the reason `test_hub_layering_guard.py` gives.
+_REPO_ROOT = next(parent for parent in Path(__file__).resolve().parents if parent.name == "tests").parent
+
+#: The action that stopped a release at startup, refused by the organization's policy.
+REFUSED_ACTION = "peter-evans/dockerhub-description@1b9a80c056b620d92cedb9d9b5a223409c68ddfa"
+
+POLICY = ActionsAllowlist(
+ github_owned_allowed=True,
+ enterprise_owners=frozenset({"Pipelex"}),
+ patterns_allowed=("astral-sh/setup-uv@*", "dorny/paths-filter@v3", "octo-org/*", "space-org*/**"),
+)
+
+ALLOWLIST_TOML = 'github_owned_allowed = true\nenterprise_owners = ["Pipelex"]\npatterns_allowed = ["astral-sh/setup-uv@*"]\n'
+
+WORKFLOW = """\
+name: Sample
+on: pull_request
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - name: A step that names an input called uses
+ uses: astral-sh/setup-uv@v7
+ with:
+ uses: not-a-reference
+ - run: echo done
+ reuse:
+ uses: ./.github/workflows/other.yml
+"""
+
+#: The reusable workflow `WORKFLOW` calls with `./.github/workflows/other.yml`.
+OTHER_WORKFLOW = "on: workflow_call\njobs:\n build:\n steps:\n - uses: actions/checkout@v4\n"
+
+COMPOSITE_ACTION = """\
+name: Local action
+runs:
+ using: composite
+ steps:
+ - uses: dorny/paths-filter@v3
+ - run: echo done
+ shell: bash
+"""
+
+
+def _write_tree(*, root: Path, workflows: dict[str, str], allowlist: str | None = ALLOWLIST_TOML) -> None:
+ """Lay out a repository holding the given workflows and, unless None, the given allowlist."""
+ workflows_dir = root / ".github" / "workflows"
+ workflows_dir.mkdir(parents=True)
+ for name, content in workflows.items():
+ (workflows_dir / name).write_text(textwrap.dedent(content), encoding="utf-8")
+ if allowlist is not None:
+ (root / ALLOWLIST_FILE).write_text(allowlist, encoding="utf-8")
+
+
+class TestActionsAllowlistGuard:
+ @pytest.mark.parametrize(
+ ("topic", "pattern", "reference", "expected"),
+ [
+ ("any ref of one action", "astral-sh/setup-uv@*", "astral-sh/setup-uv@v7", True),
+ ("any ref, a commit SHA", "pypa/gh-action-pypi-publish@*", "pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33", True),
+ ("one exact tag", "dorny/paths-filter@v3", "dorny/paths-filter@v3", True),
+ ("another tag than the pinned one", "dorny/paths-filter@v3", "dorny/paths-filter@v4", False),
+ ("a ref merely starting like the pinned one", "dorny/paths-filter@v3", "dorny/[email protected]", False),
+ ("owner and repository compare with case", "PyO3/maturin-action@*", "pyo3/maturin-action@v1", False),
+ ("the ref compares with case", "dorny/paths-filter@v3", "dorny/paths-filter@V3", False),
+ ("one star stops at a slash", "octo-org/*", "octo-org/repo/sub/path@v1", False),
+ ("one star crosses the ref", "octo-org/*", "octo-org/repo@v1", True),
+ ("two stars cross slashes", "space-org*/**", "space-org-x/repo/sub@v1", True),
+ ("another owner", "astral-sh/setup-uv@*", "evil-sh/setup-uv@v7", False),
+ ],
+ )
+ def test_patterns_read_strictly(self, topic: str, pattern: str, reference: str, expected: bool) -> None:
+ """Where GitHub's pattern syntax leaves a doubt the guard takes the stricter reading."""
+ assert pattern_matches(pattern=pattern, reference=reference) is expected, topic
+
+ @pytest.mark.parametrize(
+ ("topic", "reference", "allowed"),
+ [
+ ("a local action", "./.github/actions/setup", True),
+ ("a local reusable workflow", "./.github/workflows/publish-docker-hub.yml", True),
+ ("an action GitHub created", "actions/checkout@v4", True),
+ ("another action GitHub created", "github/codeql-action/init@v3", True),
+ ("an enterprise-owned action", "Pipelex/some-action@v1", True),
+ ("an enterprise owner spelled with another case", "pipelex/some-action@v1", False),
+ ("an action a pattern allows", "astral-sh/setup-uv@v7", True),
+ ("the action that stopped a release", REFUSED_ACTION, False),
+ ("a Docker image", "docker://alpine:3.20", False),
+ ("a reference without a ref", "astral-sh/setup-uv", False),
+ ("a reference without a repository", "astral-sh@v7", False),
+ ],
+ )
+ def test_refusal_reason(self, topic: str, reference: str, allowed: bool) -> None:
+ """Local, GitHub-created, enterprise-owned and pattern-matched references pass; anything else is refused with a reason."""
+ reason = refusal_reason(reference=reference, allowlist=POLICY)
+ assert (reason is None) is allowed, f"{topic}: {reason}"
+
+ def test_github_owned_actions_need_the_policy_to_allow_them(self) -> None:
+ """`github_owned_allowed = false` withdraws the allowance the owner alone gave."""
+ policy = POLICY._replace(github_owned_allowed=False)
+ assert refusal_reason(reference="actions/checkout@v4", allowlist=policy) is not None
+
+ def test_reads_references_where_github_reads_them(self) -> None:
+ """Steps and job-level reusable workflows count, with their lines; a `uses` key under `with:` is an input, not a reference."""
+ references = find_references_in_source(source=WORKFLOW, relative_path=".github/workflows/sample.yml")
+ assert [(found.lineno, found.reference) for found in references] == [
+ (7, "actions/checkout@v4"),
+ (9, "astral-sh/setup-uv@v7"),
+ (14, "./.github/workflows/other.yml"),
+ ]
+
+ def test_reads_the_steps_of_a_composite_action(self) -> None:
+ references = find_references_in_source(source=COMPOSITE_ACTION, relative_path=".github/actions/local/action.yml")
+ assert [found.reference for found in references] == ["dorny/paths-filter@v3"]
+
+ def test_a_non_string_uses_is_reported_rather_than_skipped(self) -> None:
+ source = "jobs:\n build:\n steps:\n - uses: {owner: someone}\n"
+ references = find_references_in_source(source=source, relative_path=".github/workflows/odd.yml")
+ assert len(references) == 1
+ assert refusal_reason(reference=references[0].reference, allowlist=POLICY) is not None
+
+ def test_invalid_yaml_is_an_error(self) -> None:
+ with pytest.raises(ActionsAllowlistGuardError, match="not valid YAML"):
+ find_references_in_source(source="jobs: [unclosed\n", relative_path=".github/workflows/broken.yml")
+
+ @pytest.mark.parametrize(
+ ("content", "message"),
+ [
+ pytest.param(ALLOWLIST_TOML + "verified_allowed = false\n", "unknown key", id="an unknown key"),
+ pytest.param('github_owned_allowed = true\nenterprise_owners = ["Pipelex"]\n', "patterns_allowed", id="a missing key"),
+ pytest.param(
+ 'github_owned_allowed = "yes"\nenterprise_owners = []\npatterns_allowed = []\n', "github_owned_allowed", id="a mistyped flag"
+ ),
+ pytest.param('github_owned_allowed = true\nenterprise_owners = []\npatterns_allowed = [""]\n', "non-empty string", id="an empty pattern"),
+ pytest.param("github_owned_allowed = \n", "not valid TOML", id="invalid TOML"),
+ ],
+ )
+ def test_a_malformed_allowlist_is_an_error(self, tmp_path: Path, content: str, message: str) -> None:
+ path = tmp_path / "actions-allowlist.toml"
+ path.write_text(content, encoding="utf-8")
+ with pytest.raises(ActionsAllowlistGuardError, match=message):
+ load_allowlist(path=path)
+
+ def test_a_missing_allowlist_is_an_error_not_an_empty_policy(self, tmp_path: Path) -> None:
+ _write_tree(root=tmp_path, workflows={"ci.yml": WORKFLOW}, allowlist=None)
+ with pytest.raises(ActionsAllowlistGuardError, match="not found"):
+ collect_violations(root=tmp_path)
+
+ def test_collects_the_refused_references_of_a_tree(self, tmp_path: Path) -> None:
+ """A refused action is reported at its file and line, and the allowed ones beside it are not."""
+ release = f"jobs:\n publish:\n steps:\n - uses: Pipelex/some-action@v1\n - uses: {REFUSED_ACTION}\n"
+ _write_tree(root=tmp_path, workflows={"ci.yml": WORKFLOW, "other.yml": OTHER_WORKFLOW, "release.yml": release})
+ violations = collect_violations(root=tmp_path)
+ assert [(violation.relative_path, violation.lineno, violation.reference) for violation in violations] == [
+ (".github/workflows/release.yml", 5, REFUSED_ACTION),
+ ]
+
+ @pytest.mark.parametrize(
+ ("reference", "action_files", "expected"),
+ [
+ pytest.param(
+ "./ci/my-action",
+ {"ci/my-action/action.yml": f"runs:\n using: composite\n steps:\n - uses: {REFUSED_ACTION}\n"},
+ [("ci/my-action/action.yml", 4, REFUSED_ACTION, "matched by no pattern")],
+ id="a refused action inside a local action outside .github/actions",
+ ),
+ pytest.param(
+ "./ci/my-action",
+ {"ci/my-action/action.yaml": "runs:\n using: composite\n steps:\n - uses: actions/checkout@v4\n"},
+ [],
+ id="an allowed action inside a local action named action.yaml",
+ ),
+ pytest.param(
+ "./ci/loop",
+ {"ci/loop/action.yml": "runs:\n using: composite\n steps:\n - uses: ./ci/loop\n"},
+ [],
+ id="a local action naming itself is read once",
+ ),
+ pytest.param(
+ "./ci/missing",
+ {},
+ [(".github/workflows/ci.yml", 5, "./ci/missing", "does not exist")],
+ id="a local action that does not exist",
+ ),
+ pytest.param(
+ "./ci/empty",
+ {"ci/empty/README.md": "no definition here"},
+ [(".github/workflows/ci.yml", 5, "./ci/empty", "no action.yml or action.yaml")],
+ id="a local directory with no action definition",
+ ),
+ pytest.param(
+ "./../outside",
+ {},
+ [(".github/workflows/ci.yml", 5, "./../outside", "outside the repository")],
+ id="a local reference leaving the repository",
+ ),
+ ],
+ )
+ def test_follows_local_references_to_their_definitions(
+ self, tmp_path: Path, reference: str, action_files: dict[str, str], expected: list[tuple[str, int, str, str]]
+ ) -> None:
+ """GitHub runs a `./` action from anywhere in the repository and applies the policy to the actions it uses, so the guard reads it too."""
+ workflow = f"jobs:\n build:\n steps:\n - uses: actions/checkout@v4\n - uses: {reference}\n"
+ root = tmp_path / "repo"
+ _write_tree(root=root, workflows={"ci.yml": workflow})
+ for relative_path, content in action_files.items():
+ target = root / relative_path
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(content, encoding="utf-8")
+ violations = collect_violations(root=root)
+ assert [(violation.relative_path, violation.lineno, violation.reference) for violation in violations] == [
+ (relative_path, lineno, found) for relative_path, lineno, found, _detail in expected
+ ]
+ for violation, (_relative_path, _lineno, _found, detail) in zip(violations, expected, strict=True):
+ assert detail in violation.detail
+
+ def test_reads_only_the_files_github_reads(self, tmp_path: Path) -> None:
+ """Workflows directly under `.github/workflows/` and action definitions under `.github/actions/`; nothing else."""
+ _write_tree(root=tmp_path, workflows={"ci.yml": WORKFLOW, "notes.md": "not a workflow"})
+ (tmp_path / ".github" / "workflows" / "nested").mkdir()
+ (tmp_path / ".github" / "workflows" / "nested" / "ignored.yml").write_text(WORKFLOW, encoding="utf-8")
+ (tmp_path / ".github" / "actions" / "local").mkdir(parents=True)
+ (tmp_path / ".github" / "actions" / "local" / "action.yml").write_text(COMPOSITE_ACTION, encoding="utf-8")
+ scanned = [path.relative_to(tmp_path).as_posix() for path in iter_workflow_files(root=tmp_path)]
+ assert scanned == [".github/workflows/ci.yml", ".github/actions/local/action.yml"]
+
+ def test_refuses_to_pass_having_checked_nothing(self, tmp_path: Path) -> None:
+ _write_tree(root=tmp_path, workflows={"empty.yml": "name: Empty\non: push\njobs: {}\n"})
+ with pytest.raises(ActionsAllowlistGuardError, match="checked nothing"):
+ collect_violations(root=tmp_path)
+
+ def test_the_committed_allowlist_refuses_the_action_that_stopped_a_release(self) -> None:
+ allowlist = load_allowlist(path=_REPO_ROOT / ALLOWLIST_FILE)
+ assert refusal_reason(reference=REFUSED_ACTION, allowlist=allowlist) is not None
+
+ def test_the_repository_reads_its_release_workflows_and_passes(self) -> None:
+ """The release workflows, which pull-request CI never runs, are among the files read, and every workflow passes."""
+ scanned = {path.relative_to(_REPO_ROOT).as_posix() for path in iter_workflow_files(root=_REPO_ROOT)}
+ assert {".github/workflows/publish-pypi.yml", ".github/workflows/publish-docker-hub.yml"} <= scanned
+ assert collect_violations(root=_REPO_ROOT) == []
diff --git a/tests/unit/pipelex/cli/dev/test_check_actions_allowlist_cmd.py b/tests/unit/pipelex/cli/dev/test_check_actions_allowlist_cmd.py
new file mode 100644
index 000000000..902e80b2a
--- /dev/null
+++ b/tests/unit/pipelex/cli/dev/test_check_actions_allowlist_cmd.py
@@ -0,0 +1,77 @@
+from __future__ import annotations
+
+import io
+from typing import TYPE_CHECKING
+
+import pytest
+from rich.console import Console
+
+from pipelex.cli.dev_cli.commands import check_actions_allowlist_cmd as cmd_mod
+from pipelex.cli.dev_cli.commands.actions_allowlist_exceptions import ActionsAllowlistGuardError
+from pipelex.cli.dev_cli.commands.actions_allowlist_guard import REMEDY, ActionsAllowlistViolation
+from pipelex.cli.dev_cli.commands.check_actions_allowlist_cmd import check_actions_allowlist_cmd
+
+if TYPE_CHECKING:
+ from pytest_mock import MockerFixture
+
+#: Wide enough that no assertion below depends on where Rich decides to wrap.
+CONSOLE_WIDTH = 400
+
+VIOLATION = ActionsAllowlistViolation(
+ relative_path=".github/workflows/publish-docker-hub.yml",
+ lineno=226,
+ reference="peter-evans/dockerhub-description@1b9a80c056b620d92cedb9d9b5a223409c68ddfa",
+ detail="is not created by GitHub, not owned by the enterprise, and matched by no pattern of the policy",
+)
+
+
+class TestCheckActionsAllowlistCmd:
+ @pytest.fixture
+ def console_buffer(self, mocker: MockerFixture) -> io.StringIO:
+ """Route every `get_console()` call in the command module to one StringIO-backed console."""
+ buffer = io.StringIO()
+ mocker.patch.object(cmd_mod, "get_console", return_value=Console(file=buffer, force_terminal=False, width=CONSOLE_WIDTH))
+ return buffer
+
+ @pytest.mark.parametrize(
+ ("quiet", "expected_verdict"),
+ [
+ (True, "Actions allowlist check: PASSED"),
+ (False, "Actions Allowlist Check: PASSED"),
+ ],
+ )
+ def test_a_clean_tree_passes(self, mocker: MockerFixture, console_buffer: io.StringIO, quiet: bool, expected_verdict: str) -> None:
+ """A clean tree returns normally, which is exit 0, and a quiet run says so in one line."""
+ mocker.patch.object(cmd_mod, "collect_violations", return_value=[])
+ check_actions_allowlist_cmd(quiet=quiet)
+ output = console_buffer.getvalue()
+ assert expected_verdict in output
+ if quiet:
+ assert output.strip().splitlines() == [f"✓ {expected_verdict}"]
+
+ @pytest.mark.parametrize("quiet", [True, False])
+ def test_a_refused_action_exits_1_with_its_site_and_the_remedy(self, mocker: MockerFixture, console_buffer: io.StringIO, quiet: bool) -> None:
+ """The gate: any refused action is exit 1, and a quiet CI run still carries the site, the reference and the remedy."""
+ mocker.patch.object(cmd_mod, "collect_violations", return_value=[VIOLATION])
+
+ with pytest.raises(SystemExit) as exit_info:
+ check_actions_allowlist_cmd(quiet=quiet)
+
+ assert exit_info.value.code == 1
+ output = console_buffer.getvalue()
+ assert ".github/workflows/publish-docker-hub.yml:226" in output
+ assert VIOLATION.reference in output
+ assert REMEDY in output
+
+ @pytest.mark.parametrize("quiet", [True, False])
+ def test_a_guard_error_exits_1_with_its_message(self, mocker: MockerFixture, console_buffer: io.StringIO, quiet: bool) -> None:
+ """A missing or malformed allowlist fails loudly, whatever the verbosity, rather than passing."""
+ mocker.patch.object(cmd_mod, "collect_violations", side_effect=ActionsAllowlistGuardError("the Actions allowlist was not found"))
+
+ with pytest.raises(SystemExit) as exit_info:
+ check_actions_allowlist_cmd(quiet=quiet)
+
+ assert exit_info.value.code == 1
+ output = console_buffer.getvalue()
+ assert "Actions allowlist check: FAILED" in output
+ assert "the Actions allowlist was not found" in output