Skip to content
Closed
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
7 changes: 4 additions & 3 deletions .github/actions/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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@<sha> # main
with:
mode: enforce
check_workflows: |
Expand Down Expand Up @@ -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`.

Expand Down
3 changes: 2 additions & 1 deletion .github/workflows/tier0-approval.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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' }}
Expand All @@ -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 }}
Expand Down
22 changes: 17 additions & 5 deletions repo/private/tier0_approval/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
)


Expand All @@ -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


Expand All @@ -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"]
Expand Down
72 changes: 59 additions & 13 deletions repo/private/tier0_approval/test_approval.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
# cspell:ignore textconv Adraft

import json
import os
import subprocess
from pathlib import Path
from unittest.mock import Mock, call
Expand Down Expand Up @@ -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"),
[
Expand Down Expand Up @@ -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")
Expand Down
Loading