From e5aebcc4c6774741011d067a479a01ce8b19ed36 Mon Sep 17 00:00:00 2001 From: "tbhb.dev Agent" Date: Wed, 25 Nov 2026 02:49:07 -0500 Subject: [PATCH] fix(ci): read tier 0 workflow runs with the job token Generated-by: LLM effort=high;harness=codex:0.166.0;model=openai:gpt-6.2-sol;session=sha-256-64:fef438e4839683a2;surface=exec --- .github/actions/README.md | 7 +- .github/workflows/tier0-approval.yml | 3 +- repo/private/tier0_approval/__main__.py | 22 ++++-- repo/private/tier0_approval/test_approval.py | 72 ++++++++++++++++---- 4 files changed, 82 insertions(+), 22 deletions(-) diff --git a/.github/actions/README.md b/.github/actions/README.md index 44f708e9..a8a8c92f 100644 --- a/.github/actions/README.md +++ b/.github/actions/README.md @@ -129,9 +129,10 @@ on: jobs: approve: permissions: + actions: read contents: write pull-requests: write - uses: tbhb-dev/rules/.github/workflows/tier0-approval.yml@bf77356b02e39e2e55d44848ebf5f51dd99a1b9a # main + uses: tbhb-dev/rules/.github/workflows/tier0-approval.yml@ # main with: mode: enforce check_workflows: | @@ -160,9 +161,9 @@ jobs: `check_workflows` takes one `context:workflow-id` pair per line. `tier0_paths` and `deny_paths` use the defaults shown above. Each path input takes one case-insensitive glob per line. `max_files` defaults to 50 and counts both paths in a rename. Set `design_paths` to require the exact head commit in `design_go_sha` or the caller's `DESIGN_GO_SHA` repository variable. -The caller needs the `pins-approver` environment and the installed `tbhb-dev-auto-reviews` GitHub App. The App needs read access to Actions, Checks, and Contents in both modes. The runner's `python3` must be 3.14 or newer. +The caller needs the `pins-approver` environment and the installed `tbhb-dev-auto-reviews` GitHub App. The App needs read access to Checks and Contents in both modes. The runner's `python3` must be 3.14 or newer. -The calling job must grant `contents: write` and `pull-requests: write` in both modes, including `evaluate`. The reusable workflow requests both permissions at startup and GitHub rejects the call if the caller grants less. +The calling job must grant `actions: read`, `contents: write`, and `pull-requests: write` in both modes, including `evaluate`. GitHub rejects the call if the caller grants less. The workflow reads Actions runs with `github.token`. In the default `mode: evaluate`, the App uses Pull requests read access. The workflow yields the decision artifact and outputs `decision`, `reason`, and `head_sha`. diff --git a/.github/workflows/tier0-approval.yml b/.github/workflows/tier0-approval.yml index a1016813..0caebb01 100644 --- a/.github/workflows/tier0-approval.yml +++ b/.github/workflows/tier0-approval.yml @@ -71,6 +71,7 @@ jobs: timeout-minutes: 10 environment: pins-approver permissions: + actions: read # Read workflow runs for the checked commit. contents: write # Merge the checked commit. pull-requests: write # Enqueue the approved pull request. outputs: @@ -105,7 +106,6 @@ jobs: with: client-id: ${{ secrets.PIN_APPROVER_CLIENT_ID }} private-key: ${{ secrets.PIN_APPROVER_PRIVATE_KEY }} - permission-actions: read permission-checks: read permission-contents: read permission-pull-requests: ${{ inputs.mode == 'enforce' && 'write' || 'read' }} @@ -114,6 +114,7 @@ jobs: id: decide env: GH_TOKEN: ${{ steps.app.outputs.token }} + ACTIONS_TOKEN: ${{ github.token }} APP_SLUG: ${{ steps.app.outputs.app-slug }} CHECK_WORKFLOWS: ${{ inputs.check_workflows }} TIER0_PATHS: ${{ inputs.tier0_paths }} diff --git a/repo/private/tier0_approval/__main__.py b/repo/private/tier0_approval/__main__.py index 9b3b056d..201a8446 100644 --- a/repo/private/tier0_approval/__main__.py +++ b/repo/private/tier0_approval/__main__.py @@ -32,10 +32,10 @@ class HoldError(Exception): pass -def command(*args: str) -> str: +def command(*args: str, env: Mapping[str, str] | None = None) -> str: # Fixed executables and argument vectors, without shell expansion. return subprocess.check_output( # nosec B603 # noqa: S603 - args, encoding="utf-8", stderr=subprocess.PIPE + args, encoding="utf-8", stderr=subprocess.PIPE, env=env ) @@ -45,9 +45,17 @@ def sha(value: str) -> str: return value -def api(repo: str, path: str, *flags: str, **query: str) -> object: +def api( + repo: str, path: str, *flags: str, auth_env: str | None = None, **query: str +) -> object: endpoint = f"repos/{repo}/{path}?{urlencode(query)}" - response: object = json.loads(command("gh", "api", endpoint, *flags)) + env = None + if auth_env is not None: + token = os.environ.get(auth_env) + if not token: + raise HoldError("missing-actions-token") + env = os.environ | {"GH_TOKEN": token} + response: object = json.loads(command("gh", "api", endpoint, *flags, env=env)) return response @@ -56,7 +64,11 @@ def context_pass(repo: str, head: str, spec: str) -> bool: if not (name and re.fullmatch(r"[1-9][0-9]*", workflow)): return False response = api( - repo, f"actions/workflows/{workflow}/runs", head_sha=head, per_page="1" + repo, + f"actions/workflows/{workflow}/runs", + auth_env="ACTIONS_TOKEN", + head_sha=head, + per_page="1", ) payload = cast("dict[str, list[Record]]", response) # pragma: no mutate runs = payload["workflow_runs"] diff --git a/repo/private/tier0_approval/test_approval.py b/repo/private/tier0_approval/test_approval.py index 675e49da..6ccf1915 100644 --- a/repo/private/tier0_approval/test_approval.py +++ b/repo/private/tier0_approval/test_approval.py @@ -4,6 +4,7 @@ # cspell:ignore textconv Adraft import json +import os import subprocess from pathlib import Path from unittest.mock import Mock, call @@ -129,26 +130,69 @@ def test_invalid_context(monkeypatch: pytest.MonkeyPatch, spec: str) -> None: def test_contexts(monkeypatch: pytest.MonkeyPatch) -> None: stage = CHECK | {"name": "CI: stage"} pages = [{"check_runs": [CHECK]}, {"check_runs": [stage]}] - api = Mock( - side_effect=[{"workflow_runs": [WORKFLOW_RUN]}, pages, {"workflow_runs": []}] - ) - monkeypatch.setattr(gate, "api", api) + runs = {"workflow_runs": [WORKFLOW_RUN]} + request = Mock(side_effect=map(json.dumps, (runs, pages, {"workflow_runs": []}))) + monkeypatch.setattr(gate.subprocess, "check_output", request) + app_credential = "app-token" + monkeypatch.setenv("GH_TOKEN", app_credential) + monkeypatch.setenv("ACTIONS_TOKEN", "job-token") + actions_env = os.environ | {"GH_TOKEN": "job-token"} assert not gate.contexts_pass(REPO, HEAD, " CI: stage : 123 \nOther:456") - assert api.call_args_list == [ - call(REPO, "actions/workflows/123/runs", head_sha=HEAD, per_page="1"), + assert request.call_args_list == [ call( - REPO, - "check-suites/3/check-runs", - "--paginate", - "--slurp", - check_name="CI: stage", + ( + "gh", + "api", + f"repos/{REPO}/actions/workflows/123/runs?head_sha={HEAD}&per_page=1", + ), + encoding="utf-8", + stderr=subprocess.PIPE, + env=actions_env, + ), + call( + ( + "gh", + "api", + f"repos/{REPO}/check-suites/3/check-runs?check_name=CI%3A+stage", + "--paginate", + "--slurp", + ), + encoding="utf-8", + stderr=subprocess.PIPE, + env=None, + ), + call( + ( + "gh", + "api", + f"repos/{REPO}/actions/workflows/456/runs?head_sha={HEAD}&per_page=1", + ), + encoding="utf-8", + stderr=subprocess.PIPE, + env=actions_env, ), - call(REPO, "actions/workflows/456/runs", head_sha=HEAD, per_page="1"), ] - api.configure_mock(side_effect=[{"workflow_runs": [WORKFLOW_RUN]}, pages]) + assert os.environ["GH_TOKEN"] == app_credential + request.configure_mock(side_effect=map(json.dumps, (runs, pages))) assert gate.contexts_pass(REPO, HEAD, "CI: stage:123") +@pytest.mark.parametrize("token", [None, ""]) +def test_missing_actions_token( + monkeypatch: pytest.MonkeyPatch, token: str | None +) -> None: + if token is None: + monkeypatch.delenv("ACTIONS_TOKEN", raising=False) + else: + monkeypatch.setenv("ACTIONS_TOKEN", token) + monkeypatch.setenv("GH_TOKEN", "app-token") + request = Mock() + monkeypatch.setattr(gate.subprocess, "check_output", request) + with pytest.raises(gate.HoldError, match=r"^missing-actions-token$"): + gate.context_pass(REPO, HEAD, "CI:123") + request.assert_not_called() + + @pytest.mark.parametrize( ("old", "new", "counts", "regular"), [ @@ -390,11 +434,13 @@ def test_main( ("gh", "api", endpoint, "--paginate", "--slurp"), encoding="utf-8", stderr=subprocess.PIPE, + env=None, ), call( ("gh", "api", f"repos/{REPO}/pulls/5?"), encoding="utf-8", stderr=subprocess.PIPE, + env=None, ), ] artifact = ARTIFACT.read_text(encoding="utf-8")