diff --git a/.github/workflows/code-monkey-cron.yaml b/.github/workflows/code-monkey-cron.yaml index 261b1dc0..19f641b7 100644 --- a/.github/workflows/code-monkey-cron.yaml +++ b/.github/workflows/code-monkey-cron.yaml @@ -253,6 +253,7 @@ jobs: github_app_private_key: "${{ secrets.BOT_APP_PRIVATE_KEY }}" copilot_review_token: "${{ secrets.COPILOT_REVIEW_TOKEN }}" antagonistic_dispatch_token: "${{ secrets.CODE_REVIEW_DISPATCH_TOKEN }}" + fork_pool_token: "${{ secrets.FORK_POOL_TOKEN }}" # Dispatch the next round of each pull request whose round left work # outstanding (docs/DESIGN.md section 20.6). The job holds one diff --git a/.github/workflows/code-monkey.yaml b/.github/workflows/code-monkey.yaml index bbb7a5c9..8fc0ad3b 100644 --- a/.github/workflows/code-monkey.yaml +++ b/.github/workflows/code-monkey.yaml @@ -226,6 +226,12 @@ on: Fine-grained PAT with Actions write on antagonistic_repository and nothing else; used by the antagonistic request step alone required: false + fork_pool_token: + description: >- + Classic PAT with the public_repo scope alone, of a machine + account that belongs to the bot fork organisations and no + other; the forks job creates and renames forks with it + required: false outputs: pull_requests: description: >- @@ -1490,12 +1496,88 @@ jobs: echo "Cleared $removed spilled tool-output file(s), the CLI home" \ "and the checkout." + # Creating or renaming a fork needs Administration: write, which an + # App can hold only App-wide: on the target organisation as much as + # on the fork pools. A machine account that belongs to the fork pools + # alone does it here instead, with a classic token scoped to + # public_repo, so no App mint ever administers (docs/DESIGN.md + # section 4.3). The job runs beside the author matrix, checks out + # the trusted assets and nothing else, and its token reaches one + # step. A fork it could not ready fails that target's publish alone. + forks: + name: 'Prepare forks' + needs: 'select' + if: >- + needs.select.outputs.run_agent == 'true' && + !inputs.dry_run && inputs.mode != 'select' + runs-on: 'ubuntu-latest' + # Every missing fork is requested before any is awaited, against one + # one-minute deadline, so the budget is the API calls: four or so + # per new fork, across a matrix of up to 256 targets. + timeout-minutes: 30 + permissions: + contents: read # Checkout trusted assets + steps: + - name: 'Load egress allow-list' + if: inputs.harden_runner_egress == 'block' + # yamllint disable-line rule:line-length + uses: lfreleng-actions/harden-runner-block-action@65ff87957e1cac2de3203a85dbb07c31810321cb # v0.16.4 + with: + config: "${{ inputs.harden_runner_allowlist }}" + # yamllint disable-line rule:line-length + supplemental_config: "${{ inputs.harden_runner_supplemental_allowlist }}" + # A caller naming a list depends on it, so its absence fails + # here rather than at the first blocked connection. + # yamllint disable-line rule:line-length + supplemental_required: "${{ inputs.harden_runner_supplemental_allowlist != '' && 'true' || 'false' }}" + # yamllint disable-line rule:line-length + supplemental_unpinned: "${{ inputs.harden_runner_supplemental_unpinned && 'true' || 'false' }}" + extra_endpoints: "${{ inputs.harden_runner_extra_endpoints }}" + allow_list_summary: 'false' + + - name: 'Harden runner' + # yamllint disable-line rule:line-length + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: "${{ inputs.harden_runner_egress }}" + allowed-endpoints: "${{ env.CONNECTION_ALLOW_LIST }}" + + - name: 'Require trusted provenance' + env: + ASSETS_SHA: "${{ needs.select.outputs.assets_sha }}" + run: | + [[ "$ASSETS_SHA" =~ ^[0-9a-f]{40}$ ]] + + - name: 'Checkout trusted assets' + # yamllint disable-line rule:line-length + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: "${{ inputs.assets_repository }}" + ref: "${{ needs.select.outputs.assets_sha }}" + path: 'monkey-assets' + persist-credentials: false + + # The matrix is the select job's trusted output; fork_pool.py + # still proves each entry against the committed mapping, and + # refuses a token that is not classic and scoped to public_repo. + - name: 'Find, create or rename forks' + id: prepare + env: + GH_TOKEN: "${{ secrets.fork_pool_token }}" + ORG: "${{ inputs.org }}" + MATRIX: "${{ needs.select.outputs.matrix }}" + run: | + python3 monkey-assets/scripts/fork_pool.py prepare \ + --config monkey-assets/config/fork-orgs.json --org "$ORG" \ + --matrix-env MATRIX --summary "$GITHUB_STEP_SUMMARY" + publish: name: 'Publish (${{ matrix.key }})' - needs: [select, author] + needs: [select, author, forks] # Runs after every author entry, including failed ones, so each # issue gets a verdict; never after cancellation or a failed - # selection. + # selection. A failed or skipped forks job does not stop it: a + # target without its fork fails its own publish, naming that job. if: >- !cancelled() && needs.select.result == 'success' && needs.select.outputs.run_agent == 'true' @@ -1788,7 +1870,8 @@ jobs: echo "$resolved" >> "$GITHUB_OUTPUT" # Forks are public, so the native token can see whether one - # exists; the answer picks which of the two fork mints runs. + # exists. The forks job has readied it by now; when it could not, + # no fork token is minted and the push reports the missing fork. - name: 'Check fork exists' id: fork-state env: @@ -1808,14 +1891,13 @@ jobs: exit 1 fi - # Two mints, one per fork state, because a token scoped to a - # repository that does not exist yet cannot be minted. The - # creation token is the sole holder of administration, and it - # runs only when there is no fork to administer. Both always - # grant workflows: syncing the fork fast-forwards over whatever - # upstream merged, workflow changes included, whether or not the - # proposal edits one. Fork organisations hold bot forks alone and - # have Actions disabled, so the grant runs nothing there. + # A token scoped to the one fork, minted only once it exists: the + # forks job creates and renames forks, so no mint here needs + # administration. It always grants workflows: syncing the fork + # fast-forwards over whatever upstream merged, workflow changes + # included, whether or not the proposal edits one. Fork + # organisations hold bot forks alone and have Actions disabled, + # so the grant runs nothing there. - name: 'Mint fork write token' id: fork-token if: >- @@ -1835,33 +1917,12 @@ jobs: permission-metadata: 'read' permission-workflows: 'write' - - name: 'Mint fork creation token' - id: fork-create-token - if: >- - !inputs.dry_run && steps.check.outputs.verdict == 'proposed' && - inputs.github_app_client_id != '' && - steps.fork-state.outputs.exists == 'false' - # yamllint disable-line rule:line-length - uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 - with: - client-id: "${{ inputs.github_app_client_id }}" - private-key: "${{ secrets.github_app_private_key }}" - # yamllint disable-line rule:line-length - owner: "${{ matrix.fork_org }}" # zizmor: ignore[github-app] no repository exists yet to scope to; the fork pool holds only bot forks - permission-administration: 'write' - permission-contents: 'write' - permission-metadata: 'read' - permission-workflows: 'write' - # Every write token is checked against the configured App before # it is used; a key for another App fails here rather than acts. - name: 'Pre-flight: fork token identity' - if: >- - steps.fork-token.outcome == 'success' || - steps.fork-create-token.outcome == 'success' + if: steps.fork-token.outcome == 'success' env: - # yamllint disable-line rule:line-length - MINTED_SLUG: "${{ steps.fork-token.outputs.app-slug || steps.fork-create-token.outputs.app-slug }}" + MINTED_SLUG: "${{ steps.fork-token.outputs.app-slug }}" run: | python3 monkey-assets/scripts/preflight.py identity \ --config monkey-assets/config/bot.json --minted-slug "$MINTED_SLUG" @@ -1915,8 +1976,10 @@ jobs: - name: 'Push branch to fork' id: push env: - # yamllint disable-line rule:line-length - GH_TOKEN: "${{ steps.fork-token.outputs.token || steps.fork-create-token.outputs.token }}" + GH_TOKEN: "${{ steps.fork-token.outputs.token }}" + # 'false' when the forks job could not ready the fork: no fork + # token exists then, and the push fails naming that job. + FORK_EXISTS: "${{ steps.fork-state.outputs.exists }}" MODE: "${{ inputs.mode }}" DRY_RUN: "${{ inputs.dry_run }}" RUN_ATTEMPT: "${{ github.run_attempt }}" @@ -1926,6 +1989,7 @@ jobs: run: | extra=() if [ "$DRY_RUN" = true ]; then extra+=(--dry-run); fi + if [ "$FORK_EXISTS" = false ]; then extra+=(--fork-missing); fi python3 monkey-assets/scripts/publish.py push \ --check artefacts/check.json --workdir work \ --run-attempt "$RUN_ATTEMPT" \ diff --git a/README.md b/README.md index 7d1dd2d4..aaef3bb8 100644 --- a/README.md +++ b/README.md @@ -143,6 +143,7 @@ jobs: copilot_token: ${{ secrets.COPILOT_CLI_TOKEN }} github_app_private_key: ${{ secrets.BOT_APP_PRIVATE_KEY }} copilot_review_token: ${{ secrets.COPILOT_REVIEW_TOKEN }} + fork_pool_token: ${{ secrets.FORK_POOL_TOKEN }} ``` Live runs need a GitHub App installed on the organisation with the @@ -155,6 +156,14 @@ requests: write on the organisation, which bills the reviews to that seat (section 10.4). Without it the request falls back to the App's token and the review stays `pending (not requested)`. +The App never creates or renames a fork, so it needs no +Administration permission. A caller that targets repositories whose +fork does not exist yet passes `fork_pool_token`: a classic token, +scoped to `public_repo` alone, of a machine account that belongs to +the bot fork organisations and no other (section 10.6). Without it, +existing forks keep working and a target with no fork fails its +publish. + New pull requests leave `.github/workflows/` alone unless the caller sets `allow_workflow_edits: true`; the publisher rejects a proposal that changes a workflow file without it. A revision round may change diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 1f6f9feb..d0082633 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -116,7 +116,9 @@ produces. Triage's agent emits JSON that a trusted applier turns into label writes. This agent emits **commits**: a git bundle and a manifest. The trusted publisher turns those into a branch and a pull request. The agent job never holds a credential that can write to -any repository, and it never holds the App key. +any repository, and it never holds the App key. A fourth job, +`forks`, runs beside the author matrix with a machine account's +token and readies the forks the publisher writes into (§4.3, §10.6). ### 4.1 Why tool policy cannot contain this agent @@ -253,20 +255,25 @@ names agreed, the organisation `AGENTS.md` is its right home. Publishing then works as follows, with the §5 signing unchanged: -1. The publisher resolves the fork organisation for the target's - owner from the table, and finds or creates the fork there. It - looks the fork up by the target's name first, then by parent - among the target's forks: a fork made before a rename of the - target keeps its old name, and the publisher renames it after the +1. The forks job (`Prepare forks`) resolves the fork organisation + for the target's owner from the table, and finds or creates the + fork there, beside the author matrix and before the publish job + starts. It looks the fork up by the target's name first, then by + parent among the target's forks: a fork made before a rename of + the target keeps its old name, and the job renames it after the target. A `422` because another repository holds that name fails - the publish. GitHub answers a fork request for a parent the + that target alone. GitHub answers a fork request for a parent the organisation already forks with the existing fork, and the reply's name, not the target's, is the one renamed or polled. - Creating or renaming a fork through the API needs the App - installed on the fork organisation with access to all its - repositories and Administration: write, plus Contents: read on - the source. A fork under an old name reads as missing by name, - and the creation token of §8 step 6 is the one that renames it. + Creating or renaming a fork needs Administration: write on the + fork organisation, and a GitHub App holds its permissions on + every installation at once: an App able to create forks could + administer every repository in the target organisation too. The + job holds the fork pool token of §10.6, a machine + account's, and the App holds no Administration grant at all. The + publisher requires the fork and never makes one: with no fork it + mints no fork token, and the push fails that issue, naming the + forks job. 2. It syncs the fork's default branch with the target (`merge-upstream`), so the recorded base commit is present. The sync fast-forwards over every commit upstream merged since the @@ -307,8 +314,9 @@ Publishing then works as follows, with the §5 signing unchanged: **Installation.** The publisher has no same-repository path. The four organisations exist and each holds an installation of the App -on all repositories with Contents: write, Workflows: write and -Administration: write (§10.1). Every fork organisation has Actions +on all repositories with Contents: write and Workflows: write +(§10.1), and the machine account of §10.6 as a member. Every fork +organisation has Actions switched off, which means a bot branch triggers no workflow where it lands, and Workflows: write on a fork token can run nothing there; the target organisation requires approval before workflows @@ -1217,15 +1225,15 @@ For each selected issue: from the target organisation, and to equal what the committed mapping (`config/fork-orgs.json`) resolves for the target's owner. It then reads, with the native token, whether the public fork - exists. Dry-run and `select` mode go no further than this step. -6. **Mint a fork token** on the fork organisation's installation: - for an existing fork, `repositories:` the bare `repo_name` with - `contents: write` and `metadata: read`; for a missing fork, no - repository (none exists to name) and `administration: write` - besides, the sole mint in the pipeline that holds it. Both always - add `workflows: write`, since the step 7 sync can fast-forward - over upstream workflow changes (§4.3). The two - mints exclude each other on the fork's existence. + exists; the forks job has readied it by now (§4.3). Dry-run and + `select` mode go no further than this step. +6. **Mint a fork token** on the fork organisation's installation, + once the fork exists: `repositories:` the bare `repo_name` with + `contents: write`, `metadata: read` and `workflows: write`, since + the step 8 sync can fast-forward over upstream workflow changes + (§4.3). No mint in the pipeline requests Administration. A + missing fork gets no token; the push then fails that issue before + any read, naming the forks job. 7. **Mint a pull request token** on the target organisation's installation for that repository alone, with `pull_requests: write` and `metadata: read`: the one token in the pipeline that @@ -1250,13 +1258,13 @@ For each selected issue: lets through is the bot's own carrying this proposal's chain: a rerun after an earlier attempt opened it, which the adoption below records. The re-read takes the fork's name as GitHub - holds it now, before anything renames it: a fork kept from before - a rename of the target still carries the old name, so the re-read - finds it by parent as `ensure_fork` does and counts its pull + holds it now: a fork kept from before a rename of the target + carries the old name until the forks job renames it, so the + re-read finds it by parent as that job does and counts its pull requests and chain under that name. A read by name that GitHub redirects to a renamed fork takes the name its reply carries. A failed read is a failed step: nothing publishes on trust. A - `branches` run makes the same reads. Then find or create the fork + `branches` run makes the same reads. Then require the fork (§4.3), sync its default branch, create `code-monkey/issue-` there at the base SHA (an existing branch is a rejection unless it holds this proposal's own chain, or is a @@ -1679,8 +1687,9 @@ For each selected issue: Secrets: `copilot_token` (model PAT, §10.2), `github_app_private_key` (select and publish alone), `copilot_review_token` (the review request step alone, §10.4), `antagonistic_dispatch_token` (the -antagonistic request job's dispatch step alone, §10.5). All four are -optional. +antagonistic request job's dispatch step alone, §10.5), +`fork_pool_token` (the forks job's prepare step alone, §10.6). All +five are optional. Numeric inputs are strings because reusable-workflow `number` inputs cannot carry validation and `fromJSON` handles the @@ -1796,17 +1805,22 @@ OAuth and webhooks stay off. Its permissions: | Contents | write | publish | Fork sync, branch, commits (fork organisations alone) | | Pull requests | write | publish | Open PR, label | | Workflows | write | publish | Fork sync over upstream workflow changes; commits that touch `.github/workflows/` (fork organisations alone) | -| Administration | write | publish | Create a missing fork (fork organisations alone) | +The App holds no Administration permission and no mint requests one: +an App holds its permissions on every installation at once, so the +grant that would let it create a fork would let it administer every +repository in the target organisation as well. The forks job creates +and renames forks with the fork pool token instead (§10.6). + The App holds two kinds of installation. On the target organisation the publisher mints Pull requests: write to open the pull request and Issues: write for the comment, and no mint there ever requests -Contents, Workflows or Administration. On each fork organisation it +Contents or Workflows. On each fork organisation it mints the writes that build the branch; the installation covers all -repositories of the organisation, since the fork it writes to may -not exist until the run creates it. +repositories of the organisation, since the forks job may create the +fork it writes to during the run. | Fork organisation | Installed | Actions | | ----------------- | --------- | ------- | @@ -1820,7 +1834,6 @@ not exist until the run creates it. | Metadata | read | Repository listing | | Contents | write | Sync the fork, branch, commits | | Workflows | write | Fork sync; commits under `.github/workflows/` | -| Administration | write | Create a missing fork | The App holds no Actions permission and no mint requests one: job logs stay out of every trusted job (§20.1). Checks: read is a later @@ -1844,7 +1857,7 @@ change with the widest reach, so a new proposal may make one when the operator sets `allow_workflow_edits` and not otherwise (§9.1, §8 step 3); a revision round stays within the workflow files its pull request -already changes (§20.3). Both fork mints request +already changes (§20.3). The fork mint requests `workflows: write` on every run, whatever the verified diff holds: the fork sync (§4.3 step 2) fast-forwards over upstream workflow changes too, and a proposal that edits no workflow would @@ -1957,6 +1970,39 @@ step warns, dispatches nothing and succeeds, so the default stays harmless until a maintainer sets it. Its expiry needs the same owner and rotation reminder as the model PAT (§10.2). +### 10.6 The fork pool credential + +Creating a fork, or renaming one to follow a renamed target, needs +Administration: write on the fork organisation (§4.3 step 1). The +App cannot hold it without holding it on the target organisation +too, so a machine account does this one job: a dedicated +GitHub account, a member of the four fork organisations and of no +other, with no access to any target. Its classic token, scoped to +`public_repo` alone, is the repository secret `FORK_POOL_TOKEN`: with +that membership it can fork a public repository into a pool and +rename a fork there, and it can write to no target repository. A +classic token rather than fine-grained ones, because a fine-grained +token has one resource owner and the pools are four organisations. + +The dispatch caller passes it as the optional `fork_pool_token`, and +the forks job's `Find, create or rename forks` step is the one place +that reads it. That job holds `contents: read`, runs beside the +author matrix, and checks out the trusted assets at the pinned +commit and nothing else; no agent output or target code runs beside +it. `fork_pool.py` reads the token's `X-OAuth-Scopes` and refuses +one that is not classic or carries any scope besides `public_repo`, +so an operator's own token, which could reach far more, never makes +a write. It proves each matrix entry against `config/fork-orgs.json` +before touching a fork, requests every missing fork before it waits +for any, against one shared deadline, so a large first run waits +about as long as one fork, and writes each fork's row to the step +summary as its outcome is final. It tries every target and fails the +job when any fork is not ready; the publish job still runs, and the +targets without a fork fail alone. Without the secret the step warns, +reads nothing and succeeds, and every fork that already exists keeps +working. `tests/test_workflow.py` pins that reach. The token's expiry +needs the same owner and rotation reminder as the model PAT (§10.2). + ## 11. Dispatch and Concurrency - No schedule. The caller runs on `workflow_dispatch` alone, and @@ -2078,7 +2124,8 @@ conflicts while producer artifacts survive. | Hooks need network the runner blocks | Agent cannot pass gates | Author job runs in audit mode (§7.5) | | Task needs `sudo` or containers (an image build, a loop mount) in a target without the marker | Runner refuses both; the step cannot run | Prompt tells the agent not to work around it: it abstains, or leaves the step out and says so, naming `.enable-sudo-and-containers`; a maintainer adds the marker to the default branch where the repository needs it (§4.1, §7.3) | | `main` moves after selection | Branch created at old base | GitHub reports mergeability; reviewer rebases or agent retries later | -| Target repository renamed | Its fork keeps the old name, so the by-name lookups miss it | The publisher finds the fork by parent and renames it after the target (§4.3 step 1); selection reads the old name until that publish runs | +| Target repository renamed | Its fork keeps the old name, so the by-name lookups miss it | The forks job finds the fork by parent and renames it after the target (§4.3 step 1); selection reads the old name until that job runs | +| Fork pool token absent, expired or too broad | The forks job makes and renames no fork; a target without its fork fails its publish, naming the forks job | The job warns when the secret is absent and fails naming the scopes otherwise; existing forks keep working; restore the token (§10.6) | | Diff adds or edits an executable file, symlink or submodule, or changes a mode | Publish refused | Agent leaves such files untouched, checks every commit with `git log --raw` before the manifest, and abstains naming the file when it cannot avoid one (§5, §7.3) | | A revision's branch moves or vanishes after selection | Round's input is stale | Author job stands down with a `::warning::` and an `abstain` manifest; no session, run stays green (§20.2) | | Two runs overlap | A wasted session on one target; never a second pull request | Caller concurrency group for scans; named-issue dispatches lock per run; the selector skips targets another active run selected and waits for an older run still selecting (§6 "Overlapping runs"), failing open; the publisher re-reads the issue and the branch's pull requests before any write (§8 step 8), so a run that loses the race publishes nothing | @@ -2153,6 +2200,7 @@ scripts/workflow_gate.py which workflow files a proposal may cha scripts/publish.py replay, open PR, reconcile scripts/publish_cli.py its eight commands' command line scripts/branch_refs.py bot branch and its PR on GitHub +scripts/fork_pool.py the forks job: find, create, rename (§4.3) scripts/stale_branch.py a closed attempt's branch (§5) scripts/issue_recheck.py the issue re-read before a push (§8) scripts/branch_chain.py a branch read back as replayed work diff --git a/docs/index.md b/docs/index.md index d1e9f1f3..ecb0b762 100644 --- a/docs/index.md +++ b/docs/index.md @@ -23,9 +23,12 @@ author (untrusted, one runner per issue) | checkout + Copilot CLI; no credential that can write | git bundle + manifest v + (forks, trusted, beside the author jobs: a machine account's + token finds, creates or renames each target's fork) + v publish (trusted, one runner per issue) | verify the bundle offline - | fork token: find or create the fork, push the branch + | fork token: require the fork, push the branch | target token: open the pull request, comment on the issue v report (trusted) diff --git a/scripts/branch_refs.py b/scripts/branch_refs.py index 11e0e110..20a8e33a 100644 --- a/scripts/branch_refs.py +++ b/scripts/branch_refs.py @@ -4,7 +4,9 @@ """The fork, the bot branch and its pull request, as GitHub holds them. Branch writes address the fork (DESIGN.md section 4.3); the pull -request lives on the target with the fork branch as its head. +request lives on the target with the fork branch as its head. The +fork itself is the forks job's to make (``fork_pool.py``): the +publisher requires it and never creates or renames one. """ from __future__ import annotations @@ -23,8 +25,6 @@ import write_recovery as recovery from proposal_policy import PublishError, Rejection -FORK_WAIT_SECONDS = 60 -FORK_POLL_SECONDS = 5 # Two publishes in one run may sync the same fork at once: one # merge-upstream wins and the other answers 422 with the fork synced # all the same (issue #38). A concurrent sync finishes in seconds, @@ -58,18 +58,6 @@ def is_fork_of(data: dict[str, Any], target: str) -> bool: ) -def await_fork(fork: str) -> dict[str, Any]: - """Poll for a fork GitHub is still creating; forking is asynchronous.""" - deadline = time.monotonic() + FORK_WAIT_SECONDS - while True: - try: - return github.api_object(f"repos/{fork}") - except github.GitHubError as exc: - if not github.is_absent(exc) or time.monotonic() >= deadline: - raise PublishError(f"fork {fork} did not appear: {exc}") from exc - time.sleep(FORK_POLL_SECONDS) - - def listed_fork(target: str, fork_org: str) -> str | None: """The full name of the target's fork in the pool, under any name.""" try: @@ -93,56 +81,30 @@ def listed_fork(target: str, fork_org: str) -> str | None: return None -def create_fork(target: str, fork_org: str) -> str: - """Fork the target into the pool; return the name GitHub replies with. +def missing_fork(fork: str) -> str: + """The reason a publish fails when the fork it needs does not exist.""" + return ( + f"fork {fork} does not exist; the Prepare forks job creates it, " + "so read that job's log, or create the fork by hand" + ) - GitHub never holds two forks of one parent in one organisation, and - answers a repeat request with the existing fork, so the reply, not - the target's name, says where the fork is. Forking is asynchronous: - the caller polls for a new fork before using it. - """ - try: - reply = github.api_write( - "POST", - f"repos/{target}/forks", - {"organization": fork_org, "default_branch_only": True}, - ) - except github.GitHubError as exc: - raise PublishError(f"could not fork {target} into {fork_org}: {exc}") from exc - name = reply.get("full_name") - if not isinstance(name, str) or not name.lower().startswith(f"{fork_org.lower()}/"): - raise PublishError(f"forking {target} named no fork in {fork_org}: {name!r}") - return name - - -def ensure_fork(target: str, fork_org: str, repo_name: str) -> str: - """Find or create the target's fork in the fork organisation. - - A fork kept from before the target was renamed still carries the - old name; it is found by parent and renamed after the target, so - everything that reads ``/`` finds it again. - A repository of that name which is not a fork of the target is a - failure, never a push destination: the publisher writes only into - forks it can prove are its own. + +def require_fork(fork: str, target: str) -> None: + """Require the target's fork as the forks job left it; never make one. + + The forks job finds, creates or renames the fork before the publish + job starts (DESIGN.md section 4.3). A repository of that name which + is not a fork of the target is a failure, never a push destination: + the publisher writes only into forks it can prove are the target's. """ - fork = f"{fork_org}/{repo_name}" try: data = github.api_object(f"repos/{fork}") except github.GitHubError as exc: - if not github.is_absent(exc): - raise PublishError(f"could not read fork {fork}: {exc}") from exc - found = listed_fork(target, fork_org) or create_fork(target, fork_org) - if found.lower() != fork.lower(): - try: - github.api_write("PATCH", f"repos/{found}", {"name": repo_name}) - except github.GitHubError as failure: - raise PublishError( - f"could not rename fork {found} to {repo_name}: {failure}" - ) from failure - data = await_fork(fork) + if github.is_absent(exc): + raise PublishError(missing_fork(fork)) from exc + raise PublishError(f"could not read fork {fork}: {exc}") from exc if not is_fork_of(data, target): raise PublishError(f"{fork} exists but is not a fork of {target}") - return fork def sync_fork(fork: str, default_branch: str, base_sha: str) -> None: diff --git a/scripts/fork_pool.py b/scripts/fork_pool.py new file mode 100644 index 00000000..8c91501b --- /dev/null +++ b/scripts/fork_pool.py @@ -0,0 +1,341 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: 2026 The Linux Foundation + +"""Find, create or rename the bot forks a run's selection needs. + +The forks job runs this beside the author matrix (DESIGN.md section +4.3). Creating or renaming a fork needs Administration: write, which +a GitHub App can hold only App-wide, on the target organisation as +much as on the fork pools. A machine account that belongs to the bot +fork organisations alone does it instead, through a classic token +with the ``public_repo`` scope and nothing more; the token check +below refuses any other kind, so an operator's own token, or one +with broader scopes, never reaches a write. + +``fork_pool.py prepare --config FILE --org ORG --matrix-env NAME`` +reads the select job's matrix from the environment variable ``NAME`` +and readies one fork per target repository in it. Every target is +attempted; a failure on one is reported and the rest go ahead, so the +publisher can still publish to the forks that are ready. The exit +status is 1 when any target failed, and 0 with a warning when no +token was provided at all. +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +import time +from pathlib import Path +from typing import Any, NamedTuple, cast + +import bot_github as github +import branch_refs as refs +import fork_orgs as forks +from proposal_policy import PublishError + +# The one scope the token may carry: enough to fork a public repository +# into, and rename it within, an organisation the account belongs to. +REQUIRED_SCOPES = frozenset({"public_repo"}) +SCOPES_HEADER = "x-oauth-scopes" +FORK_WAIT_SECONDS = 60 +FORK_POLL_SECONDS = 5 + + +class PoolError(Exception): + """The matrix, the mapping or the token rules out preparing forks.""" + + +class Target(NamedTuple): + """One repository whose fork the run needs, and where that fork lives.""" + + repository: str + fork_org: str + repo_name: str + + @property + def fork(self) -> str: + """The fork's full name in its pool.""" + return f"{self.fork_org}/{self.repo_name}" + + +def text_field(entry: dict[str, Any], key: str) -> str: + """A non-empty string field of a matrix entry, or a PoolError.""" + value = entry.get(key) + if not isinstance(value, str) or not value: + raise PoolError(f"matrix entry has no {key}") + return value + + +def targets(matrix: str, config: dict[str, Any], org: str) -> list[Target]: + """The distinct targets of the select job's matrix, each one proven. + + The matrix is trusted output of the select job, but every entry + must still agree with the committed mapping: a fork organisation + the mapping does not name for ``org`` is never written to. + """ + try: + parsed: Any = json.loads(matrix) + except (ValueError, RecursionError) as exc: + raise PoolError(f"the matrix is not valid JSON: {exc}") from exc + include = ( + cast("dict[str, Any]", parsed).get("include") + if isinstance(parsed, dict) + else None + ) + if not isinstance(include, list): + raise PoolError("the matrix carries no include list") + try: + fork_org = forks.resolve(config, org) + except forks.ForkOrgError as exc: + raise PoolError(str(exc)) from exc + if not forks.ALLOWED_RE.fullmatch(fork_org) or fork_org.lower() == org.lower(): + raise PoolError(f"{fork_org} is not a bot fork organisation for {org}") + found: dict[str, Target] = {} + for raw in cast("list[Any]", include): + if not isinstance(raw, dict): + raise PoolError("a matrix entry is not an object") + entry = cast("dict[str, Any]", raw) + repo_name = text_field(entry, "repo_name") + target = Target(text_field(entry, "repository"), fork_org, repo_name) + if target.repository.lower() != f"{org}/{repo_name}".lower(): + raise PoolError(f"{target.repository} is not {repo_name} in {org}") + if text_field(entry, "fork_org").lower() != fork_org.lower(): + raise PoolError(f"{target.repository} names another fork organisation") + if text_field(entry, "fork_repository").lower() != target.fork.lower(): + raise PoolError(f"{target.repository} names another fork repository") + found.setdefault(target.fork.lower(), target) + return list(found.values()) + + +def token_scopes() -> frozenset[str] | None: + """The classic token's scopes, or None for a token that reports none. + + GitHub reports a classic token's scopes in the X-OAuth-Scopes + header of any API reply; fine-grained and App tokens carry none. + """ + raw = github.run_gh(["api", "--include", "user"]) + for line in raw.splitlines(): + if not line.strip(): + break + name, sep, value = line.partition(":") + if sep and name.strip().lower() == SCOPES_HEADER: + return frozenset(s.strip() for s in value.split(",") if s.strip()) + return None + + +def check_token() -> None: + """Refuse any token but a classic one scoped to public_repo alone.""" + try: + scopes = token_scopes() + except github.GitHubError as exc: + raise PoolError(f"could not read the fork pool token's scopes: {exc}") from exc + if scopes is None: + raise PoolError( + "the fork pool token reports no scopes; use a classic token " + "with the public_repo scope alone" + ) + if scopes != REQUIRED_SCOPES: + shown = ", ".join(sorted(scopes)) or "none" + raise PoolError( + f"the fork pool token carries scopes {shown}; it must carry " + "public_repo alone" + ) + + +def await_fork(fork: str, deadline: float) -> dict[str, Any]: + """Poll for a fork GitHub is still creating until ``deadline``. + + Forking is asynchronous. Every fork a run requested shares one + deadline, so the waits overlap rather than add up. + """ + while True: + try: + return github.api_object(f"repos/{fork}") + except github.GitHubError as exc: + if not github.is_absent(exc) or time.monotonic() >= deadline: + raise PublishError(f"fork {fork} did not appear: {exc}") from exc + time.sleep(FORK_POLL_SECONDS) + + +def create_fork(target: str, fork_org: str) -> str: + """Fork the target into the pool; return the name GitHub replies with. + + GitHub never holds two forks of one parent in one organisation, and + answers a repeat request with the existing fork, so the reply, not + the target's name, says where the fork is. Forking is asynchronous: + the caller polls for a new fork before using it. + """ + try: + reply = github.api_write( + "POST", + f"repos/{target}/forks", + {"organization": fork_org, "default_branch_only": True}, + ) + except github.GitHubError as exc: + raise PublishError(f"could not fork {target} into {fork_org}: {exc}") from exc + name = reply.get("full_name") + if not isinstance(name, str) or not name.lower().startswith(f"{fork_org.lower()}/"): + raise PublishError(f"forking {target} named no fork in {fork_org}: {name!r}") + return name + + +class Pending(NamedTuple): + """A fork requested or renamed, which GitHub may still be making.""" + + target: Target + outcome: str + + +def start(target: Target) -> str | Pending: + """Find the target's fork, or request or rename it; never wait. + + A fork kept from before the target was renamed still carries the + old name; it is found by parent and renamed after the target, so + the publisher's reads of ``/`` find it. A + repository of that name which is not a fork of the target is a + failure, never a push destination: the publisher writes only into + forks it can prove are the target's. A fork found ready returns + its outcome; one requested or renamed is Pending until + :func:`finish` reads it back. + """ + fork = target.fork + try: + data = github.api_object(f"repos/{fork}") + except github.GitHubError as exc: + if not github.is_absent(exc): + raise PublishError(f"could not read fork {fork}: {exc}") from exc + else: + if not refs.is_fork_of(data, target.repository): + raise PublishError( + f"{fork} exists but is not a fork of {target.repository}" + ) + return "present" + listed = refs.listed_fork(target.repository, target.fork_org) + found = listed or create_fork(target.repository, target.fork_org) + if found.lower() != fork.lower(): + try: + github.api_write("PATCH", f"repos/{found}", {"name": target.repo_name}) + except github.GitHubError as exc: + raise PublishError( + f"could not rename fork {found} to {target.repo_name}: {exc}" + ) from exc + if listed is not None: + return Pending(target, f"renamed from {listed}") + if found.lower() != fork.lower(): + return Pending(target, f"created as {found}, then renamed") + return Pending(target, "created") + + +def finish(pending: Pending, deadline: float) -> str: + """Wait for a pending fork and prove it is the target's.""" + target = pending.target + if not refs.is_fork_of(await_fork(target.fork, deadline), target.repository): + raise PublishError( + f"{target.fork} exists but is not a fork of {target.repository}" + ) + return pending.outcome + + +class Summary: + """Report each fork as its outcome is final, so a cut-short job keeps it.""" + + def __init__(self, path: Path | None) -> None: + """Start the step summary's table at ``path``, when there is one.""" + self.path = path + self.failed = 0 + if path is not None: + with path.open("a", encoding="utf-8") as handle: + handle.write("## Forks\n\n| Fork | Outcome |\n| ---- | ------- |\n") + + def record(self, fork: str, outcome: str) -> None: + """Log one fork's outcome and append its row.""" + print(f"{fork}: {outcome}") + self.write(fork, outcome) + + def fail(self, fork: str, exc: Exception) -> None: + """Log and append a fork that could not be readied.""" + self.failed += 1 + outcome = f"failed: {github.safe_message(exc)}" + print(f"::error title=Fork not ready::{fork}: {outcome}") + self.write(fork, outcome) + + def write(self, fork: str, outcome: str) -> None: + """Append one row to the step summary.""" + if self.path is not None: + with self.path.open("a", encoding="utf-8") as handle: + handle.write(f"| `{fork}` | {outcome} |\n") + + +def run_prepare(args: argparse.Namespace) -> int: + """Ready every target's fork; return the exit status. + + Every missing fork is requested first and then awaited against one + deadline: GitHub makes forks in parallel, so a large first run + against a new organisation waits about as long as a single fork. + """ + if not os.environ.get("GH_TOKEN"): + print( + "::warning title=No fork pool token::forks are neither created " + "nor renamed; a target without its fork fails to publish" + ) + return 0 + try: + config = forks.load(args.config) + except forks.ForkOrgError as exc: + raise PoolError(str(exc)) from exc + chosen = targets(os.environ.get(args.matrix_env, ""), config, args.org) + if not chosen: + print("No targets: no fork to prepare") + return 0 + check_token() + summary = Summary(args.summary) + waiting: list[Pending] = [] + for target in chosen: + try: + state = start(target) + except (PublishError, github.GitHubError) as exc: + summary.fail(target.fork, exc) + continue + if isinstance(state, Pending): + waiting.append(state) + else: + summary.record(target.fork, state) + if waiting: + deadline = time.monotonic() + FORK_WAIT_SECONDS + for pending in waiting: + try: + summary.record(pending.target.fork, finish(pending, deadline)) + except (PublishError, github.GitHubError) as exc: + summary.fail(pending.target.fork, exc) + return 1 if summary.failed else 0 + + +def build_parser() -> argparse.ArgumentParser: + """Describe the one command.""" + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + run = commands.add_parser("prepare", help="ready the selection's forks") + run.add_argument("--config", type=Path, required=True) + run.add_argument("--org", required=True) + run.add_argument("--matrix-env", default="MATRIX") + run.add_argument("--summary", type=Path, default=None) + run.set_defaults(handler=run_prepare) + return parser + + +def main(argv: list[str] | None = None) -> None: + """Run a command; a PoolError exits 1 with its message.""" + args = build_parser().parse_args(argv) + try: + status = args.handler(args) + except PoolError as exc: + print(f"::error title=Forks not prepared::{exc}") + sys.exit(1) + sys.exit(status) + + +if __name__ == "__main__": + main() diff --git a/scripts/issue_recheck.py b/scripts/issue_recheck.py index e7980bac..ded50f66 100644 --- a/scripts/issue_recheck.py +++ b/scripts/issue_recheck.py @@ -207,9 +207,9 @@ def fork_identity(check: dict[str, Any]) -> str: """The target's fork as GitHub names it now, found with reads alone. A fork kept from before the target was renamed still carries the - old name until ``ensure_fork`` renames it, after this check, and - its pull requests name it so. Found by parent, as ``ensure_fork`` - finds it; with no fork at all, the designated name stands. The + old name until the forks job renames it (``fork_pool.py``), and its + pull requests name it so. Found by parent, as the forks job finds + it; with no fork at all, the designated name stands. The read by name follows a rename's redirect, so the name kept is the one the reply carries, not the one asked for. """ diff --git a/scripts/publish.py b/scripts/publish.py index 6de88e20..5ba3445a 100644 --- a/scripts/publish.py +++ b/scripts/publish.py @@ -56,10 +56,11 @@ branch_matches, create_branch, delete_branch, - ensure_fork, existing_pull_request, + missing_fork, open_pull_request, replay_commits, + require_fork, sync_fork, ) from proposal_policy import PublishError, Rejection @@ -109,7 +110,7 @@ def base_result(args: argparse.Namespace, check: dict[str, Any]) -> dict[str, An def run_push(args: argparse.Namespace) -> dict[str, Any]: - """Find or create the fork, create the branch there and replay commits. + """Require the fork, create the branch there and replay commits. A write recovered from a transient failure adds a result warning. """ @@ -120,10 +121,15 @@ def run_push(args: argparse.Namespace) -> dict[str, Any]: return revision_publish.run_push(args, check, result, fail=fail) if result["verdict"] != "proposed" or args.dry_run or args.mode == "select": return result + fork = str(check["fork_repository"]) + if args.fork_missing: + # No fork token was minted for a fork that does not exist, + # so this fails before the issue re-read that needs one. + reason = missing_fork(fork) + fail(args, result, reason, PublishError(reason)) if recheck.rejected(args, check, result, fail=fail): return result target = str(check["repository"]) - fork = str(check["fork_repository"]) branch = str(check["branch"]) attempted = False created = False @@ -131,7 +137,7 @@ def run_push(args: argparse.Namespace) -> dict[str, Any]: progress: list[str] = [] owned: list[bool] = [] try: - ensure_fork(target, str(check["fork_org"]), target.partition("/")[2]) + require_fork(fork, target) sync_fork(fork, str(check["default_branch"]), str(check["base_sha"])) # Inside the rollback boundary, but a create without a clear # answer, or found only by reading it back, leaves ``created`` diff --git a/scripts/publish_cli.py b/scripts/publish_cli.py index 99705268..643bd854 100644 --- a/scripts/publish_cli.py +++ b/scripts/publish_cli.py @@ -53,6 +53,9 @@ def build_parser( "--mode", required=True, choices=("select", "branches", "pull-requests") ) push.add_argument("--dry-run", action="store_true") + # The publish job found no fork, so it minted no fork token; the + # forks job creates forks, and the push reports the gap. + push.add_argument("--fork-missing", action="store_true") push.add_argument("--run-attempt", type=int, default=1) # The proposal's artifact ID; empty when none arrived. push.add_argument("--author-session", default="") diff --git a/scripts/revision_publish.py b/scripts/revision_publish.py index af03482c..74566f17 100644 --- a/scripts/revision_publish.py +++ b/scripts/revision_publish.py @@ -132,6 +132,9 @@ def run_push( target = str(check["repository"]) fork = str(check["fork_repository"]) try: + if args.fork_missing: + # No fork token was minted, so nothing below could read. + raise PublishError(refs.missing_fork(fork)) closed = closed_pull_request(target, int(check["pull_number"])) if closed is not None: raise Rejection(closed) @@ -139,7 +142,7 @@ def run_push( if unlisted is not None: result[recheck.AUTHOR_UNLISTED] = True raise Rejection(unlisted.reason) - refs.ensure_fork(target, str(check["fork_org"]), target.partition("/")[2]) + refs.require_fork(fork, target) refs.sync_fork(fork, str(check["default_branch"]), str(check["base_sha"])) published = already_moved(check) if published is not None: diff --git a/tests/test_fork_pool.py b/tests/test_fork_pool.py new file mode 100644 index 00000000..e5fa2ba1 --- /dev/null +++ b/tests/test_fork_pool.py @@ -0,0 +1,591 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: 2026 The Linux Foundation + +"""The forks job: proving the matrix, checking the token, readying forks.""" + +from __future__ import annotations + +import json +import sys +import tempfile +import unittest +from importlib import import_module +from pathlib import Path +from typing import Any +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) +github = import_module("bot_github") +policy = import_module("proposal_policy") +pool = import_module("fork_pool") + +ORG = "owner" +TARGET = f"{ORG}/repo" +FORK_ORG = "lfreleng-bot-forks" +FORK = f"{FORK_ORG}/repo" +CONFIG: dict[str, Any] = {"default": FORK_ORG, "organisations": {}} +SCOPED = "HTTP/2.0 200 OK\nX-Oauth-Scopes: public_repo\n\n{}" + + +def repo_object(**overrides: Any) -> dict[str, Any]: + """A repository API object describing a fork of the target.""" + data: dict[str, Any] = { + "full_name": FORK, + "fork": True, + "parent": {"full_name": TARGET}, + } + data.update(overrides) + return data + + +def absent() -> Exception: + """The error gh raises for a missing resource.""" + return github.GitHubError("gh: Not Found (HTTP 404)") + + +def past_deadline() -> list[float]: + """Clock readings that end a fork poll on its first miss.""" + return [0.0, pool.FORK_WAIT_SECONDS + 1.0] + + +def entry(**overrides: Any) -> dict[str, Any]: + """One select-job matrix entry for the target.""" + data: dict[str, Any] = { + "key": "repo-7", + "repository": TARGET, + "repo_name": "repo", + "fork_org": FORK_ORG, + "fork_repository": FORK, + } + data.update(overrides) + return data + + +def matrix(*entries: dict[str, Any]) -> str: + """The select job's matrix output holding ``entries``.""" + return json.dumps({"include": list(entries)}) + + +TARGET_ENTRY = pool.Target(TARGET, FORK_ORG, "repo") + + +def prepare(target: Any) -> str: + """Start one target and, when it is pending, wait for it as the command does.""" + state = pool.start(target) + if isinstance(state, pool.Pending): + return pool.finish(state, pool.time.monotonic() + pool.FORK_WAIT_SECONDS) + return state + + +class NoNetworkCase(unittest.TestCase): + """Base class failing any test that reaches a real subprocess.""" + + def setUp(self) -> None: + """Forbid ``gh``.""" + guard = patch.object( + github.subprocess, "run", side_effect=AssertionError("unexpected gh") + ) + guard.start() + self.addCleanup(guard.stop) + + +class TargetsTest(unittest.TestCase): + """``targets`` proves every matrix entry against the committed mapping.""" + + def test_entries_reduce_to_one_target_per_fork(self) -> None: + """An issue and a revision in one repository need one fork.""" + found = pool.targets( + matrix(entry(), entry(key="repo-9"), entry(repository="Owner/Repo")), + CONFIG, + ORG, + ) + self.assertEqual(found, [TARGET_ENTRY]) + self.assertEqual(found[0].fork, FORK) + + def test_empty_matrix_has_no_targets(self) -> None: + """Nothing selected, nothing to ready.""" + self.assertEqual(pool.targets(matrix(), CONFIG, ORG), []) + + def test_mapping_decides_the_fork_organisation(self) -> None: + """A dedicated pool in the mapping wins over the default.""" + config = {"default": FORK_ORG, "organisations": {ORG: "lfreleng-bot-forks-x"}} + found = pool.targets( + matrix( + entry( + fork_org="lfreleng-bot-forks-x", + fork_repository="lfreleng-bot-forks-x/repo", + ) + ), + config, + ORG, + ) + self.assertEqual(found[0].fork, "lfreleng-bot-forks-x/repo") + + def test_disagreeing_entries_are_refused(self) -> None: + """An entry naming another target, pool or fork never reaches a write.""" + for bad, message in ( + (entry(repository="other/repo"), "is not repo in owner"), + (entry(fork_org="lfreleng-bot-forks-x"), "another fork organisation"), + (entry(fork_repository=f"{FORK_ORG}/else"), "another fork repository"), + (entry(repo_name=""), "no repo_name"), + ): + with ( + self.subTest(bad=bad), + self.assertRaisesRegex(pool.PoolError, message), + ): + pool.targets(matrix(bad), CONFIG, ORG) + + def test_malformed_matrix_is_refused(self) -> None: + """Invalid JSON, no include list or a non-object entry is an error.""" + for raw in ("{", "[]", '{"include": {}}', '{"include": [1]}'): + with ( + self.subTest(raw=raw), + self.assertRaises(pool.PoolError), + ): + pool.targets(raw, CONFIG, ORG) + + def test_target_owner_cannot_be_its_own_pool(self) -> None: + """A run against a fork pool itself has nowhere to fork to.""" + with self.assertRaisesRegex(pool.PoolError, "itself"): + pool.targets(matrix(), CONFIG, FORK_ORG) + + +class TokenCheckTest(NoNetworkCase): + """The pool token must be classic and scoped to public_repo alone.""" + + def check(self, reply: str) -> None: + """Run the check against one ``gh api --include user`` reply.""" + with patch.object(github, "run_gh", return_value=reply) as run: + pool.check_token() + run.assert_called_once_with(["api", "--include", "user"]) + + def test_public_repo_alone_passes(self) -> None: + """The scope header is matched without regard to its case.""" + self.check(SCOPED) + self.check("HTTP/2.0 200 OK\nx-oauth-scopes: public_repo\n\n{}") + + def test_broader_scopes_are_refused(self) -> None: + """An operator's token, or one that can do more, never writes.""" + for scopes in ("repo", "public_repo, workflow", "public_repo, admin:org", ""): + reply = f"HTTP/2.0 200 OK\nX-Oauth-Scopes: {scopes}\n\n{{}}" + with ( + self.subTest(scopes=scopes), + self.assertRaisesRegex(pool.PoolError, "must carry public_repo alone"), + ): + self.check(reply) + + def test_token_without_scopes_is_refused(self) -> None: + """Fine-grained and App tokens report no scopes header.""" + with self.assertRaisesRegex(pool.PoolError, "reports no scopes"): + self.check("HTTP/2.0 200 OK\nContent-Type: application/json\n\n{}") + + def test_a_header_in_the_body_does_not_count(self) -> None: + """Only the header block before the first blank line is read.""" + with self.assertRaisesRegex(pool.PoolError, "reports no scopes"): + self.check('HTTP/2.0 200 OK\n\n{"x":"X-Oauth-Scopes: public_repo"}') + + def test_unreadable_token_is_refused(self) -> None: + """A rejected token fails before any fork is touched.""" + with ( + patch.object( + github, "run_gh", side_effect=github.GitHubError("Bad credentials") + ), + self.assertRaisesRegex(pool.PoolError, "could not read"), + ): + pool.check_token() + + +class PrepareTest(NoNetworkCase): + """``start`` finds, renames or requests the fork; ``finish`` waits for it.""" + + def test_existing_fork_is_used(self) -> None: + """A repository that is a fork of the target needs nothing.""" + with ( + patch.object(github, "api_object", return_value=repo_object()) as read, + patch.object(github, "api_list") as listing, + patch.object(github, "api_write") as write, + ): + self.assertEqual(prepare(TARGET_ENTRY), "present") + read.assert_called_once_with(f"repos/{FORK}") + listing.assert_not_called() + write.assert_not_called() + + def test_case_differences_in_the_parent_are_tolerated(self) -> None: + """GitHub reports owner names in their own case; the match folds it.""" + parent = {"full_name": "Owner/Repo"} + with patch.object( + github, "api_object", return_value=repo_object(parent=parent) + ): + self.assertEqual(prepare(TARGET_ENTRY), "present") + + def test_unrelated_repository_is_refused(self) -> None: + """A same-named repository that is not the target's fork is an error.""" + for data in ( + repo_object(fork=False, parent=None), + repo_object(parent={"full_name": "someone/else"}), + repo_object(parent=None), + ): + with ( + self.subTest(data=data), + patch.object(github, "api_object", return_value=data), + patch.object(github, "api_write") as write, + self.assertRaisesRegex(policy.PublishError, "not a fork of"), + ): + prepare(TARGET_ENTRY) + write.assert_not_called() + + def test_read_failure_is_operational(self) -> None: + """A 500 on the fork read never leads to a fork request.""" + with ( + patch.object( + github, "api_object", side_effect=github.GitHubError("x (HTTP 500)") + ), + patch.object(github, "api_write") as write, + self.assertRaisesRegex(policy.PublishError, "could not read fork"), + ): + prepare(TARGET_ENTRY) + write.assert_not_called() + + def test_missing_fork_is_created_then_awaited(self) -> None: + """A 404 with no listed fork creates one and polls until it appears.""" + with ( + patch.object( + github, + "api_object", + side_effect=[absent(), absent(), repo_object()], + ) as read, + patch.object(github, "api_list", return_value=[]) as listing, + patch.object(github, "api_write", return_value=repo_object()) as write, + patch.object(pool.time, "sleep") as sleep, + patch.object(pool.time, "monotonic", side_effect=[0.0, 1.0, 2.0]), + ): + self.assertEqual(prepare(TARGET_ENTRY), "created") + listing.assert_called_once_with(f"repos/{TARGET}/forks?sort=newest") + write.assert_called_once_with( + "POST", + f"repos/{TARGET}/forks", + {"organization": FORK_ORG, "default_branch_only": True}, + ) + self.assertEqual(read.call_count, 3) + sleep.assert_called_once_with(pool.FORK_POLL_SECONDS) + + def test_create_reply_under_an_old_name_is_renamed(self) -> None: + """The create reply, not the target's name, says where the fork is.""" + old = f"{FORK_ORG}/old-repo" + renamed = repo_object(full_name=FORK) + with ( + patch.object(github, "api_object", side_effect=[absent(), renamed]) as read, + patch.object(github, "api_list", return_value=[]), + patch.object( + github, + "api_write", + side_effect=[repo_object(full_name=old), renamed], + ) as write, + patch.object(pool.time, "sleep"), + patch.object(pool.time, "monotonic", return_value=0.0), + ): + self.assertEqual(prepare(TARGET_ENTRY), f"created as {old}, then renamed") + write.assert_called_with("PATCH", f"repos/{old}", {"name": "repo"}) + self.assertEqual(read.call_args_list[-1].args, (f"repos/{FORK}",)) + + def test_create_reply_outside_the_pool_is_refused(self) -> None: + """A create reply naming no fork in the pool is never trusted.""" + for reply in ({}, repo_object(full_name="someone/repo")): + with ( + self.subTest(reply=reply), + patch.object(github, "api_object", side_effect=absent()), + patch.object(github, "api_list", return_value=[]), + patch.object(github, "api_write", return_value=reply), + patch.object(pool.time, "sleep") as sleep, + patch.object(pool.time, "monotonic", side_effect=past_deadline()), + self.assertRaisesRegex(policy.PublishError, "named no fork"), + ): + prepare(TARGET_ENTRY) + sleep.assert_not_called() + + def test_fork_under_an_old_name_is_renamed(self) -> None: + """A fork kept from before a target rename is found and renamed.""" + old = f"{FORK_ORG}/old-repo" + listed = [ + {"full_name": "someone/repo", "owner": {"login": "someone"}}, + {"full_name": old, "owner": {"login": FORK_ORG.upper()}}, + ] + with ( + patch.object( + github, "api_object", side_effect=[absent(), repo_object()] + ) as read, + patch.object(github, "api_list", return_value=listed), + patch.object(github, "api_write", return_value={}) as write, + patch.object(pool.time, "sleep"), + patch.object(pool.time, "monotonic", return_value=0.0), + ): + self.assertEqual(prepare(TARGET_ENTRY), f"renamed from {old}") + write.assert_called_once_with("PATCH", f"repos/{old}", {"name": "repo"}) + self.assertEqual(read.call_args_list[-1].args, (f"repos/{FORK}",)) + + def test_rename_refusal_is_operational(self) -> None: + """A 422 because the target's name is taken fails this target.""" + listed = [{"full_name": f"{FORK_ORG}/old-repo", "owner": {"login": FORK_ORG}}] + with ( + patch.object(github, "api_object", side_effect=absent()), + patch.object(github, "api_list", return_value=listed), + patch.object( + github, + "api_write", + side_effect=github.GitHubError("gh: Validation Failed (HTTP 422)"), + ), + patch.object(pool.time, "sleep") as sleep, + self.assertRaisesRegex(policy.PublishError, "could not rename fork"), + ): + prepare(TARGET_ENTRY) + sleep.assert_not_called() + + def test_fork_list_failure_is_operational(self) -> None: + """A failed fork listing never leads to a fork request.""" + with ( + patch.object(github, "api_object", side_effect=absent()), + patch.object( + github, "api_list", side_effect=github.GitHubError("x (HTTP 500)") + ), + patch.object(github, "api_write") as write, + self.assertRaisesRegex(policy.PublishError, "could not list forks"), + ): + prepare(TARGET_ENTRY) + write.assert_not_called() + + def test_fork_request_failure_is_operational(self) -> None: + """A refused fork request is reported without polling.""" + with ( + patch.object(github, "api_object", side_effect=absent()), + patch.object(github, "api_list", return_value=[]), + patch.object( + github, + "api_write", + side_effect=github.GitHubError("gh: Forbidden (HTTP 403)"), + ), + patch.object(pool.time, "sleep") as sleep, + self.assertRaisesRegex(policy.PublishError, "could not fork"), + ): + prepare(TARGET_ENTRY) + sleep.assert_not_called() + + def test_poll_timeout_is_operational(self) -> None: + """A fork that never appears before the deadline is an error.""" + with ( + patch.object(github, "api_object", side_effect=absent()), + patch.object(github, "api_list", return_value=[]), + patch.object(github, "api_write", return_value=repo_object()), + patch.object(pool.time, "sleep"), + patch.object( + pool.time, + "monotonic", + side_effect=[0.0, 1.0, pool.FORK_WAIT_SECONDS + 1.0], + ), + self.assertRaisesRegex(policy.PublishError, "did not appear"), + ): + prepare(TARGET_ENTRY) + + def test_created_repository_must_still_be_a_fork(self) -> None: + """What appears after the request is checked like a found one.""" + with ( + patch.object( + github, "api_object", side_effect=[absent(), repo_object(fork=False)] + ), + patch.object(github, "api_list", return_value=[]), + patch.object(github, "api_write", return_value=repo_object()), + patch.object(pool.time, "sleep"), + patch.object(pool.time, "monotonic", return_value=0.0), + self.assertRaisesRegex(policy.PublishError, "not a fork of"), + ): + prepare(TARGET_ENTRY) + + +class MainTest(NoNetworkCase): + """The command: every target attempted, the token checked once, exit codes.""" + + def setUp(self) -> None: + """A config file on disk and a summary file to append to.""" + super().setUp() + holder = tempfile.TemporaryDirectory() + self.addCleanup(holder.cleanup) + root = Path(holder.name) + self.config = root / "fork-orgs.json" + self.config.write_text(json.dumps(CONFIG), encoding="utf-8") + self.summary = root / "summary.md" + + def run_main(self, env: dict[str, str]) -> int: + """Run ``prepare`` under ``env`` and return its exit status.""" + argv = [ + "prepare", + "--config", + str(self.config), + "--org", + ORG, + "--summary", + str(self.summary), + ] + with ( + patch.dict(pool.os.environ, env, clear=True), + self.assertRaises(SystemExit) as exited, + ): + pool.main(argv) + return int(exited.exception.code or 0) + + def test_no_token_warns_and_writes_nothing(self) -> None: + """Without the secret nothing is read or written; publish reports gaps.""" + with patch.object(github, "run_gh") as run: + self.assertEqual(self.run_main({"MATRIX": matrix(entry())}), 0) + run.assert_not_called() + self.assertFalse(self.summary.exists()) + + def test_ready_forks_pass_and_are_summarised(self) -> None: + """The token is checked once, then each fork is reported.""" + env = {"GH_TOKEN": "t", "MATRIX": matrix(entry(), entry(key="repo-9"))} + with ( + patch.object(github, "run_gh", return_value=SCOPED) as run, + patch.object(github, "api_object", return_value=repo_object()) as read, + ): + self.assertEqual(self.run_main(env), 0) + run.assert_called_once_with(["api", "--include", "user"]) + read.assert_called_once_with(f"repos/{FORK}") + self.assertIn(f"| `{FORK}` | present |", self.summary.read_text()) + + def test_one_failure_fails_the_job_after_every_target(self) -> None: + """A fork that cannot be made fails the job; the others are still tried.""" + other = entry( + key="other-1", + repository=f"{ORG}/other", + repo_name="other", + fork_repository=f"{FORK_ORG}/other", + ) + env = {"GH_TOKEN": "t", "MATRIX": matrix(entry(), other)} + ready = repo_object( + full_name=f"{FORK_ORG}/other", parent={"full_name": f"{ORG}/other"} + ) + with ( + patch.object(github, "run_gh", return_value=SCOPED), + patch.object( + github, "api_object", side_effect=[repo_object(fork=False), ready] + ) as read, + ): + self.assertEqual(self.run_main(env), 1) + self.assertEqual(read.call_count, 2) + summary = self.summary.read_text() + self.assertIn(f"| `{FORK}` | failed: ", summary) + self.assertIn(f"| `{FORK_ORG}/other` | present |", summary) + + def test_a_wrong_token_stops_before_any_fork(self) -> None: + """A token with broader scopes exits 1 before reading a fork.""" + env = {"GH_TOKEN": "t", "MATRIX": matrix(entry())} + broad = "HTTP/2.0 200 OK\nX-Oauth-Scopes: repo\n\n{}" + with ( + patch.object(github, "run_gh", return_value=broad), + patch.object(github, "api_object") as read, + ): + self.assertEqual(self.run_main(env), 1) + read.assert_not_called() + + def test_an_empty_selection_needs_no_token_check(self) -> None: + """Nothing selected means no API call at all.""" + with patch.object(github, "run_gh") as run: + self.assertEqual(self.run_main({"GH_TOKEN": "t", "MATRIX": matrix()}), 0) + run.assert_not_called() + + def test_every_fork_is_requested_before_any_wait(self) -> None: + """Forking is asynchronous, so the waits overlap instead of adding up. + + One deadline covers every new fork: a matrix of hundreds of + targets must not spend a poll interval on each in turn. + """ + other = entry( + key="other-1", + repository=f"{ORG}/other", + repo_name="other", + fork_repository=f"{FORK_ORG}/other", + ) + made = { + FORK: repo_object(), + f"{FORK_ORG}/other": repo_object( + full_name=f"{FORK_ORG}/other", parent={"full_name": f"{ORG}/other"} + ), + } + events: list[str] = [] + requested: set[str] = set() + + def read(endpoint: str) -> dict[str, Any]: + name = endpoint.removeprefix("repos/") + events.append(f"read {name}") + if name not in requested: + raise absent() + return made[name] + + def write(method: str, endpoint: str, payload: Any) -> dict[str, Any]: + target = endpoint.removeprefix("repos/").removesuffix("/forks") + name = f"{FORK_ORG}/{target.partition('/')[2]}" + requested.add(name) + events.append(f"{method} {name}") + return made[name] + + env = {"GH_TOKEN": "t", "MATRIX": matrix(entry(), other)} + with ( + patch.object(github, "run_gh", return_value=SCOPED), + patch.object(github, "api_object", side_effect=read), + patch.object(github, "api_list", return_value=[]), + patch.object(github, "api_write", side_effect=write), + patch.object(pool.time, "monotonic", return_value=0.0) as clock, + patch.object(pool.time, "sleep") as sleep, + ): + self.assertEqual(self.run_main(env), 0) + self.assertEqual( + events, + [ + f"read {FORK}", + f"POST {FORK}", + f"read {FORK_ORG}/other", + f"POST {FORK_ORG}/other", + f"read {FORK}", + f"read {FORK_ORG}/other", + ], + ) + sleep.assert_not_called() + # One deadline for the whole wait, not one per fork. + self.assertEqual(clock.call_count, 1) + summary = self.summary.read_text() + self.assertIn(f"| `{FORK}` | created |", summary) + self.assertIn(f"| `{FORK_ORG}/other` | created |", summary) + + def test_summary_rows_survive_a_job_cut_short(self) -> None: + """Each row is written as its outcome is final, not after the loop.""" + other = entry( + key="other-1", + repository=f"{ORG}/other", + repo_name="other", + fork_repository=f"{FORK_ORG}/other", + ) + env = {"GH_TOKEN": "t", "MATRIX": matrix(entry(), other)} + with ( + patch.object(github, "run_gh", return_value=SCOPED), + patch.object( + github, + "api_object", + side_effect=[repo_object(), KeyboardInterrupt()], + ), + patch.dict(pool.os.environ, env, clear=True), + self.assertRaises(KeyboardInterrupt), + ): + pool.main( + [ + "prepare", + "--config", + str(self.config), + "--org", + ORG, + "--summary", + str(self.summary), + ] + ) + self.assertIn(f"| `{FORK}` | present |", self.summary.read_text()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_fork_publish.py b/tests/test_fork_publish.py index ab0d0304..aa4f319c 100644 --- a/tests/test_fork_publish.py +++ b/tests/test_fork_publish.py @@ -1,7 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: 2026 The Linux Foundation -"""The fork the publisher writes into: finding, creating and syncing it.""" +"""The fork the publisher writes into: requiring and syncing it.""" from __future__ import annotations @@ -41,11 +41,6 @@ def absent() -> Exception: return github.GitHubError("gh: Not Found (HTTP 404)") -def past_deadline() -> list[float]: - """Clock readings that end a fork poll on its first miss.""" - return [0.0, refs.FORK_WAIT_SECONDS + 1.0] - - class NoNetworkCase(unittest.TestCase): """Base class failing any test that reaches a real subprocess.""" @@ -62,209 +57,52 @@ def setUp(self) -> None: self.root = Path(holder.name) -class EnsureForkTest(NoNetworkCase): - """``ensure_fork`` finds the fork, or creates it and waits for it.""" +class RequireForkTest(NoNetworkCase): + """``require_fork`` reads the fork the forks job made and never writes.""" - def test_existing_fork_is_used(self) -> None: - """A repository that is a fork of the target is the destination.""" + def test_existing_fork_passes_with_one_read(self) -> None: + """A fork of the target is accepted, and nothing is written.""" with ( patch.object(github, "api_object", return_value=repo_object()) as read, + patch.object(github, "api_list") as listing, patch.object(github, "api_write") as write, ): - self.assertEqual(refs.ensure_fork(TARGET, FORK_ORG, "repo"), FORK) + refs.require_fork(FORK, TARGET) read.assert_called_once_with(f"repos/{FORK}") + listing.assert_not_called() write.assert_not_called() - def test_case_differences_in_the_parent_are_tolerated(self) -> None: - """GitHub reports owner names in their own case; the match folds it.""" - parent = {"full_name": "Owner/Repo"} - with patch.object( - github, "api_object", return_value=repo_object(parent=parent) - ): - self.assertEqual(refs.ensure_fork(TARGET, FORK_ORG, "repo"), FORK) - - def test_unrelated_repository_is_refused(self) -> None: - """A same-named repository that is not the target's fork is an error.""" - for data in ( - repo_object(fork=False, parent=None), - repo_object(parent={"full_name": "someone/else"}), - repo_object(parent=None), - ): - with ( - self.subTest(data=data), - patch.object(github, "api_object", return_value=data), - patch.object(github, "api_write") as write, - self.assertRaisesRegex(policy.PublishError, "not a fork of"), - ): - refs.ensure_fork(TARGET, FORK_ORG, "repo") - write.assert_not_called() - - def test_read_failure_is_operational(self) -> None: - """A 500 on the fork read never leads to a fork request.""" - with ( - patch.object( - github, "api_object", side_effect=github.GitHubError("x (HTTP 500)") - ), - patch.object(github, "api_write") as write, - self.assertRaisesRegex(policy.PublishError, "could not read fork"), - ): - refs.ensure_fork(TARGET, FORK_ORG, "repo") - write.assert_not_called() - - def test_missing_fork_is_created_then_awaited(self) -> None: - """A 404 with no listed fork creates one and polls until it appears.""" - with ( - patch.object( - github, - "api_object", - side_effect=[absent(), absent(), repo_object()], - ) as read, - patch.object(github, "api_list", return_value=[]) as listing, - patch.object(github, "api_write", return_value=repo_object()) as write, - patch.object(refs.time, "sleep") as sleep, - patch.object(refs.time, "monotonic", side_effect=[0.0, 1.0, 2.0]), - ): - self.assertEqual(refs.ensure_fork(TARGET, FORK_ORG, "repo"), FORK) - listing.assert_called_once_with(f"repos/{TARGET}/forks?sort=newest") - write.assert_called_once_with( - "POST", - f"repos/{TARGET}/forks", - {"organization": FORK_ORG, "default_branch_only": True}, - ) - self.assertEqual(read.call_count, 3) - sleep.assert_called_once_with(refs.FORK_POLL_SECONDS) - - def test_create_reply_under_an_old_name_is_renamed(self) -> None: - """The create reply, not the target's name, says where the fork is.""" - old = f"{FORK_ORG}/old-repo" - renamed = repo_object(full_name=FORK) - with ( - patch.object(github, "api_object", side_effect=[absent(), renamed]) as read, - patch.object(github, "api_list", return_value=[]), - patch.object( - github, - "api_write", - side_effect=[repo_object(full_name=old), renamed], - ) as write, - patch.object(refs.time, "sleep"), - patch.object(refs.time, "monotonic", return_value=0.0), - ): - self.assertEqual(refs.ensure_fork(TARGET, FORK_ORG, "repo"), FORK) - write.assert_called_with("PATCH", f"repos/{old}", {"name": "repo"}) - self.assertEqual(read.call_args_list[-1].args, (f"repos/{FORK}",)) - - def test_create_reply_outside_the_pool_is_refused(self) -> None: - """A create reply naming no fork in the pool is never trusted.""" - for reply in ({}, repo_object(full_name="someone/repo")): - with ( - self.subTest(reply=reply), - patch.object(github, "api_object", side_effect=absent()), - patch.object(github, "api_list", return_value=[]), - patch.object(github, "api_write", return_value=reply), - patch.object(refs.time, "sleep") as sleep, - patch.object(refs.time, "monotonic", side_effect=past_deadline()), - self.assertRaisesRegex(policy.PublishError, "named no fork"), - ): - refs.ensure_fork(TARGET, FORK_ORG, "repo") - sleep.assert_not_called() - - def test_fork_under_an_old_name_is_renamed(self) -> None: - """A fork kept from before a target rename is found and renamed.""" - old = f"{FORK_ORG}/old-repo" - listed = [ - {"full_name": "someone/repo", "owner": {"login": "someone"}}, - {"full_name": old, "owner": {"login": FORK_ORG.upper()}}, - ] - with ( - patch.object( - github, "api_object", side_effect=[absent(), repo_object()] - ) as read, - patch.object(github, "api_list", return_value=listed), - patch.object(github, "api_write", return_value={}) as write, - patch.object(refs.time, "sleep"), - patch.object(refs.time, "monotonic", return_value=0.0), - ): - self.assertEqual(refs.ensure_fork(TARGET, FORK_ORG, "repo"), FORK) - write.assert_called_once_with("PATCH", f"repos/{old}", {"name": "repo"}) - self.assertEqual(read.call_args_list[-1].args, (f"repos/{FORK}",)) - - def test_rename_refusal_is_operational(self) -> None: - """A 422 because the target's name is taken fails the publish.""" - listed = [{"full_name": f"{FORK_ORG}/old-repo", "owner": {"login": FORK_ORG}}] + def test_missing_fork_names_the_forks_job(self) -> None: + """A 404 is neither created nor looked up by parent; it is reported.""" with ( patch.object(github, "api_object", side_effect=absent()), - patch.object(github, "api_list", return_value=listed), - patch.object( - github, - "api_write", - side_effect=github.GitHubError("gh: Validation Failed (HTTP 422)"), - ), - patch.object(refs.time, "sleep") as sleep, - self.assertRaisesRegex(policy.PublishError, "could not rename fork"), - ): - refs.ensure_fork(TARGET, FORK_ORG, "repo") - sleep.assert_not_called() - - def test_fork_list_failure_is_operational(self) -> None: - """A failed fork listing never leads to a fork request.""" - with ( - patch.object(github, "api_object", side_effect=absent()), - patch.object( - github, "api_list", side_effect=github.GitHubError("x (HTTP 500)") - ), + patch.object(github, "api_list") as listing, patch.object(github, "api_write") as write, - patch.object(refs.time, "sleep"), - patch.object(refs.time, "monotonic", side_effect=past_deadline()), - self.assertRaisesRegex(policy.PublishError, "could not list forks"), - ): - refs.ensure_fork(TARGET, FORK_ORG, "repo") - write.assert_not_called() - - def test_fork_request_failure_is_operational(self) -> None: - """A refused fork request is reported without polling.""" - with ( - patch.object(github, "api_object", side_effect=absent()), - patch.object(github, "api_list", return_value=[]), - patch.object( - github, - "api_write", - side_effect=github.GitHubError("gh: Forbidden (HTTP 403)"), + self.assertRaisesRegex( + policy.PublishError, f"fork {FORK} does not exist.*Prepare forks" ), - patch.object(refs.time, "sleep") as sleep, - self.assertRaisesRegex(policy.PublishError, "could not fork"), ): - refs.ensure_fork(TARGET, FORK_ORG, "repo") - sleep.assert_not_called() + refs.require_fork(FORK, TARGET) + listing.assert_not_called() + write.assert_not_called() - def test_poll_timeout_is_operational(self) -> None: - """A fork that never appears before the deadline is an error.""" + def test_unrelated_repository_is_refused(self) -> None: + """A same-named repository that is not the target's fork is an error.""" with ( - patch.object(github, "api_object", side_effect=absent()), - patch.object(github, "api_list", return_value=[]), - patch.object(github, "api_write", return_value=repo_object()), - patch.object(refs.time, "sleep"), - patch.object( - refs.time, - "monotonic", - side_effect=[0.0, 1.0, refs.FORK_WAIT_SECONDS + 1.0], - ), - self.assertRaisesRegex(policy.PublishError, "did not appear"), + patch.object(github, "api_object", return_value=repo_object(fork=False)), + self.assertRaisesRegex(policy.PublishError, "not a fork of"), ): - refs.ensure_fork(TARGET, FORK_ORG, "repo") + refs.require_fork(FORK, TARGET) - def test_created_repository_must_still_be_a_fork(self) -> None: - """What appears after the request is checked like a found one.""" + def test_read_failure_is_operational(self) -> None: + """A 500 on the fork read is a failure, not a missing fork.""" with ( patch.object( - github, "api_object", side_effect=[absent(), repo_object(fork=False)] + github, "api_object", side_effect=github.GitHubError("x (HTTP 500)") ), - patch.object(github, "api_list", return_value=[]), - patch.object(github, "api_write", return_value=repo_object()), - patch.object(refs.time, "sleep"), - patch.object(refs.time, "monotonic", return_value=0.0), - self.assertRaisesRegex(policy.PublishError, "not a fork of"), + self.assertRaisesRegex(policy.PublishError, "could not read fork"), ): - refs.ensure_fork(TARGET, FORK_ORG, "repo") + refs.require_fork(FORK, TARGET) class SyncForkTest(NoNetworkCase): diff --git a/tests/test_publish.py b/tests/test_publish.py index cc0853a3..a0149de0 100644 --- a/tests/test_publish.py +++ b/tests/test_publish.py @@ -199,7 +199,12 @@ def write_check(self, data: dict[str, Any]) -> Path: return path def push_args( - self, check: Path, *, mode: str = "pull-requests", dry_run: bool = False + self, + check: Path, + *, + mode: str = "pull-requests", + dry_run: bool = False, + fork_missing: bool = False, ) -> argparse.Namespace: """The namespace ``run_push`` receives.""" return argparse.Namespace( @@ -207,6 +212,7 @@ def push_args( workdir=self.root / "work", mode=mode, dry_run=dry_run, + fork_missing=fork_missing, run_attempt=1, author_session="", output=self.root / "result.json", @@ -582,8 +588,8 @@ class RunPushTest(NoNetworkCase): def setUp(self) -> None: """Make the fork ready without a network; tests override to fail it.""" super().setUp() - self.ensure_fork = patch.object( - publish, "ensure_fork", return_value=None + self.require_fork = patch.object( + publish, "require_fork", return_value=None ).start() self.sync_fork = patch.object(publish, "sync_fork", return_value=None).start() # The issue still stands; RecheckPushTest covers the re-read itself. @@ -600,7 +606,7 @@ def test_rejected_verdict_touches_nothing(self) -> None: patch.object(publish, "replay_commits") as replay, ): result = publish.run_push(self.push_args(path)) - self.ensure_fork.assert_not_called() + self.require_fork.assert_not_called() branch.assert_not_called() replay.assert_not_called() self.assertEqual(result["verdict"], "rejected") @@ -639,7 +645,7 @@ def test_dry_run_and_select_mode_never_write(self) -> None: dry = publish.run_push(self.push_args(path, dry_run=True)) select = publish.run_push(self.push_args(path, mode="select")) branch.assert_not_called() - self.ensure_fork.assert_not_called() + self.require_fork.assert_not_called() self.assertTrue(dry["dry_run"]) self.assertEqual(dry["verdict"], "proposed") self.assertIsNone(dry["branch_url"]) @@ -654,7 +660,7 @@ def test_branches_mode(self) -> None: patch.object(publish, "replay_commits", return_value=["f" * 40]) as replay, ): result = publish.run_push(self.push_args(path, mode="branches")) - self.ensure_fork.assert_called_once_with(REPOSITORY, FORK_ORG, "repo") + self.require_fork.assert_called_once_with(FORK, REPOSITORY) self.sync_fork.assert_called_once_with(FORK, "main", BASE) branch.assert_called_once_with(FORK, BRANCH, BASE) replay.assert_called_once() @@ -684,7 +690,9 @@ def test_pull_requests_mode_leaves_the_pr_to_open(self) -> None: def test_fork_not_ready_fails_without_rollback(self) -> None: """A fork that cannot be made or synced fails before any branch exists.""" path = self.write_check(check_json()) - self.ensure_fork.side_effect = policy.PublishError("x exists but is not a fork") + self.require_fork.side_effect = policy.PublishError( + "x exists but is not a fork" + ) with ( patch.object(publish, "create_branch") as branch, patch.object(publish, "delete_branch") as delete, @@ -697,6 +705,38 @@ def test_fork_not_ready_fails_without_rollback(self) -> None: self.assertEqual(written["verdict"], "publish-failed") self.assertIn("not a fork", written["reasons"][0]) + def test_missing_fork_fails_before_any_read_or_write(self) -> None: + """No fork token exists for a missing fork, so push touches nothing. + + The forks job creates forks; the publisher reports the gap and + names that job, before the issue re-read that needs a token. + """ + path = self.write_check(check_json()) + with ( + patch.object(publish, "create_branch") as branch, + self.assertRaisesRegex(policy.PublishError, "does not exist"), + ): + publish.run_push(self.push_args(path, fork_missing=True)) + self.recheck.assert_not_called() + self.sync_fork.assert_not_called() + branch.assert_not_called() + written = self.written_result() + self.assertEqual(written["verdict"], "publish-failed") + self.assertIn("Prepare forks", written["reasons"][0]) + + def test_a_missing_fork_is_not_reported_without_a_write(self) -> None: + """Dry runs, select mode and other verdicts need no fork at all.""" + path = self.write_check(check_json()) + abstain = self.write_check(check_json(verdict="abstain")) + for args in ( + self.push_args(path, dry_run=True, fork_missing=True), + self.push_args(path, mode="select", fork_missing=True), + self.push_args(abstain, fork_missing=True), + ): + with self.subTest(mode=args.mode, dry_run=args.dry_run): + result = publish.run_push(args) + self.assertNotEqual(result["verdict"], "publish-failed") + def test_replay_failure_rolls_back_the_branch(self) -> None: """A failure after branch creation deletes the fork branch and fails. @@ -1063,14 +1103,14 @@ class RecheckPushTest(NoNetworkCase): def setUp(self) -> None: """Watch the fork writes; each test sets the re-read's answer.""" super().setUp() - self.ensure_fork = patch.object(publish, "ensure_fork").start() + self.require_fork = patch.object(publish, "require_fork").start() self.sync_fork = patch.object(publish, "sync_fork").start() self.create = patch.object(publish, "create_branch").start() self.addCleanup(patch.stopall) def assert_no_write(self) -> None: """Neither the fork nor the branch was touched.""" - self.ensure_fork.assert_not_called() + self.require_fork.assert_not_called() self.sync_fork.assert_not_called() self.create.assert_not_called() @@ -1194,7 +1234,7 @@ def push_untouched( path = self.write_check(revision_check()) with ( patch.object(github, "api_object", side_effect=target_reads(pull, head)), - patch.object(refs, "ensure_fork") as fork, + patch.object(refs, "require_fork") as fork, patch.object(refs, "sync_fork") as sync, patch.object(refs, "branch_matches", return_value=None), patch.object(refs, "create_branch") as create, @@ -1249,7 +1289,7 @@ def test_a_swap_refused_for_a_moved_head_is_superseded(self) -> None: """The compare-and-swap's own refusal marks the round, as the pre-read does.""" path = self.write_check(revision_check()) with ( - patch.object(refs, "ensure_fork"), + patch.object(refs, "require_fork"), patch.object(refs, "sync_fork"), patch.object(refs, "branch_matches", return_value=None), patch.object( @@ -1303,7 +1343,7 @@ def test_the_branch_at_the_selected_head_is_swapped(self) -> None: path = self.write_check(revision_check()) with ( - patch.object(refs, "ensure_fork"), + patch.object(refs, "require_fork"), patch.object(refs, "sync_fork"), patch.object(refs, "branch_matches", return_value=None), patch.object(refs, "create_branch") as create, @@ -1325,7 +1365,7 @@ def test_a_failed_head_read_still_fails_the_job(self) -> None: bad = github.GitHubError("Bad Gateway (HTTP 502)", status=502) with ( patch.object(github, "api_object", side_effect=target_reads(head=bad)), - patch.object(refs, "ensure_fork"), + patch.object(refs, "require_fork"), patch.object(refs, "sync_fork"), patch.object(refs, "branch_matches", return_value=None), patch.object(publish.revision_publish, "move_branch") as move, @@ -1342,7 +1382,7 @@ def test_a_move_after_the_pre_read_stays_unknown(self) -> None: generic = github.GitHubError("gh: Something went wrong while executing") with ( patch.object(reads, "branch_head", return_value="b" * 40), - patch.object(refs, "ensure_fork"), + patch.object(refs, "require_fork"), patch.object(refs, "sync_fork"), patch.object(refs, "branch_matches", return_value=None), patch.object(refs, "create_branch"), @@ -1360,11 +1400,29 @@ def test_a_move_after_the_pre_read_stays_unknown(self) -> None: self.assertTrue(any("unknown" in r for r in written["reasons"])) self.assertFalse(any("unchanged" in r for r in written["reasons"])) + def test_missing_fork_fails_the_revision_before_any_read(self) -> None: + """Without a fork there is no fork token, so the push reads nothing.""" + path = self.write_check(revision_check()) + with ( + patch.object(github, "api_object") as read, + patch.object(refs, "sync_fork") as sync, + patch.object(publish.revision_publish, "move_branch") as move, + self.assertRaisesRegex(policy.PublishError, "does not exist"), + ): + publish.run_push(self.push_args(path, fork_missing=True)) + read.assert_not_called() + sync.assert_not_called() + move.assert_not_called() + written = self.written_result() + self.assertEqual(written["verdict"], "publish-failed") + self.assertIn("Prepare forks", written["reasons"][-1]) + self.assertIn("branch is unchanged", written["reasons"][-1]) + def test_revision_moves_the_branch_and_records_the_pull_request(self) -> None: """Sync, temporary branch, replay, compare-and-swap, cleanup; the PR is known.""" path = self.write_check(revision_check()) with ( - patch.object(refs, "ensure_fork") as fork, + patch.object(refs, "require_fork") as fork, patch.object(refs, "sync_fork") as sync, patch.object(refs, "branch_matches", return_value=None), patch.object( @@ -1396,7 +1454,7 @@ def test_retry_adopts_the_round_already_on_the_branch(self) -> None: path = self.write_check(revision_check()) chain = ["c" * 40, NEW_HEAD] with ( - patch.object(refs, "ensure_fork"), + patch.object(refs, "require_fork"), patch.object(refs, "sync_fork"), patch.object(refs, "branch_matches", return_value=chain) as matches, patch.object(publish.revision_publish, "move_branch") as move, @@ -1415,7 +1473,7 @@ def test_retry_adopts_the_round_already_on_the_branch(self) -> None: self.assertTrue(any("earlier attempt" in w for w in result["warnings"])) # A branch holding anything else goes to the swap, which decides. with ( - patch.object(refs, "ensure_fork"), + patch.object(refs, "require_fork"), patch.object(refs, "sync_fork"), patch.object(refs, "branch_matches", return_value=None), patch.object( @@ -1430,7 +1488,7 @@ def test_moved_head_is_a_rejection_not_a_failure(self) -> None: """A head that changed since selection is refused, nothing forced.""" path = self.write_check(revision_check()) with ( - patch.object(refs, "ensure_fork"), + patch.object(refs, "require_fork"), patch.object(refs, "sync_fork"), patch.object(refs, "branch_matches", return_value=None), patch.object( @@ -1491,7 +1549,7 @@ def test_push_does_nothing_and_names_the_pull_request(self) -> None: """No sync, no move: the branch is untouched; respond gets the pull request.""" path = self.write_check(revision_check(verdict="handoff", commits=[])) with ( - patch.object(refs, "ensure_fork") as fork, + patch.object(refs, "require_fork") as fork, patch.object(publish.revision_publish, "move_branch") as move, patch.object(review, "pull_head") as head, ): @@ -1775,7 +1833,7 @@ def test_check_warnings_survive_every_early_return(self) -> None: for check, mode, dry_run in cases: with ( self.subTest(verdict=check["verdict"], mode=mode, dry_run=dry_run), - patch.object(refs, "ensure_fork"), + patch.object(refs, "require_fork"), patch.object(publish.revision_publish, "move_branch"), ): path = self.write_check(check) @@ -1788,7 +1846,7 @@ def test_branches_mode_publishes_no_revision(self) -> None: """A branch-only run never moves a live pull request's head.""" path = self.write_check(revision_check()) with ( - patch.object(refs, "ensure_fork") as fork, + patch.object(refs, "require_fork") as fork, patch.object(publish.revision_publish, "move_branch") as move, ): result = publish.run_push(self.push_args(path, mode="branches")) @@ -1807,7 +1865,7 @@ def move(_clone: Path, check: dict[str, Any]) -> list[str]: raise policy.PublishError("replay broke") with ( - patch.object(refs, "ensure_fork"), + patch.object(refs, "require_fork"), patch.object(refs, "sync_fork"), patch.object(refs, "branch_matches", return_value=None), patch.object(publish.revision_publish, "move_branch", side_effect=move), @@ -1824,7 +1882,7 @@ def test_an_unknown_swap_outcome_is_not_called_unchanged(self) -> None: self.target_at_selection() path = self.write_check(revision_check()) with ( - patch.object(refs, "ensure_fork"), + patch.object(refs, "require_fork"), patch.object(refs, "sync_fork"), patch.object(refs, "branch_matches", return_value=None), patch.object( @@ -1852,7 +1910,7 @@ def move(_clone: Path, check: dict[str, Any]) -> list[str]: raise policy.Rejection("head moved") with ( - patch.object(refs, "ensure_fork"), + patch.object(refs, "require_fork"), patch.object(refs, "sync_fork"), patch.object(refs, "branch_matches", return_value=None), patch.object(publish.revision_publish, "move_branch", side_effect=move), diff --git a/tests/test_workflow.py b/tests/test_workflow.py index b24a8a19..450d0486 100644 --- a/tests/test_workflow.py +++ b/tests/test_workflow.py @@ -361,12 +361,12 @@ def test_allow_list_summary_prints_once_from_select(self) -> None: self.assertEqual(value, "false") def test_every_trusted_job_loads_the_allow_list(self) -> None: - """Select, publish, report and antagonistic load the allow-list first. + """Select, forks, publish, report and antagonistic load the allow-list first. CONNECTION_ALLOW_LIST does not cross job boundaries, and harden-runner in block mode with an empty list enforces nothing. """ - for job in ("select", "publish", "report", "antagonistic"): + for job in ("select", "forks", "publish", "report", "antagonistic"): with self.subTest(job=job): loaders = self.actions(job, BLOCK_ACTION) self.assertEqual(len(loaders), 1) @@ -399,7 +399,7 @@ def test_every_loader_passes_the_supplemental_inputs(self) -> None: loaders = [ (job, step) for job in self.jobs for step in self.actions(job, BLOCK_ACTION) ] - self.assertEqual(len(loaders), 4) + self.assertEqual(len(loaders), 5) for job, step in loaders: with_ = cast(dict[str, Any], step["with"]) self.assertEqual(set(with_) - {"allow_list_summary"}, set(expected)) @@ -1319,19 +1319,17 @@ def test_a_revision_retitles_before_the_push(self) -> None: ) def test_a_handoff_reaches_push_without_a_token(self) -> None: - """Both fork mints need a proposal, so a handoff's push step holds no token. + """The fork mint needs a proposal, so a handoff's push step holds no token. Any GitHub read a handoff needs, the head check above all, therefore belongs in ``respond``, which holds the pull request token; the push step must stay offline for a handoff. """ - for identity in ("fork-token", "fork-create-token"): - condition = unwrap(str(self.step("publish", identity)["if"])) - self.assertIn("steps.check.outputs.verdict == 'proposed'", condition) + condition = unwrap(str(self.step("publish", "fork-token")["if"])) + self.assertIn("steps.check.outputs.verdict == 'proposed'", condition) push = self.step("publish", "push") self.assertEqual( - unwrap(str(push["env"]["GH_TOKEN"])), - "steps.fork-token.outputs.token || steps.fork-create-token.outputs.token", + unwrap(str(push["env"]["GH_TOKEN"])), "steps.fork-token.outputs.token" ) self.assertNotIn("github.token", str(push["env"]["GH_TOKEN"])) respond = self.step("publish", "respond") @@ -1522,7 +1520,7 @@ class PublishJobContracts(ReusableWorkflowCase): def test_publish_runs_after_author_with_read_grants(self) -> None: """Every author entry gets a verdict; the job itself can write nothing.""" publish = self.jobs["publish"] - self.assertEqual(publish["needs"], ["select", "author"]) + self.assertEqual(publish["needs"], ["select", "author", "forks"]) condition = unwrap(str(publish["if"])) self.assertIn("!cancelled()", condition) self.assertIn("needs.select.result == 'success'", condition) @@ -1563,7 +1561,7 @@ def test_evidence_is_verified_before_the_proposal_is_fetched(self) -> None: self.assertLess(steps.index(verified), steps.index(fetch)) def test_offline_check_and_scoped_token_mints(self) -> None: - """The check has no token; each fork mint grants workflows always.""" + """The check has no token; the fork mint names one fork, workflows always.""" check = self.step("publish", "check") script = flatten(check["run"]) self.assertIn("publish.py check", script) @@ -1572,36 +1570,24 @@ def test_offline_check_and_scoped_token_mints(self) -> None: # No step may gate on the proposal's workflow edits any longer. self.assertNotIn("needs_workflows", script) - for identity, exists in ( - ("fork-token", "true"), - ("fork-create-token", "false"), - ): - with self.subTest(mint=identity): - mint = self.step("publish", identity) - self.assertTrue(is_action(mint, APP_TOKEN)) - condition = unwrap(str(mint["if"])) - self.assertIn("!inputs.dry_run", condition) - self.assertIn("steps.check.outputs.verdict == 'proposed'", condition) - self.assertIn("inputs.github_app_client_id != ''", condition) - self.assertIn( - f"steps.fork-state.outputs.exists == '{exists}'", condition - ) - with_ = cast(dict[str, Any], mint["with"]) - self.assert_expression(with_["owner"], "matrix.fork_org") - self.assertEqual(with_["permission-contents"], "write") - self.assertEqual(with_["permission-metadata"], "read") - self.assertNotIn("permission-pull-requests", with_) - self.assertNotIn("permission-issues", with_) - # Syncing the fork can fast-forward over upstream - # workflow commits, so the grant cannot depend on the - # proposal's own diff. - self.assertEqual(with_["permission-workflows"], "write") - write = cast(dict[str, Any], self.step("publish", "fork-token")["with"]) - self.assert_expression(write["repositories"], "matrix.repo_name") - # The fork does not exist yet, so no repository can be named. - create = cast(dict[str, Any], self.step("publish", "fork-create-token")["with"]) - self.assertNotIn("repositories", create) - self.assertEqual(create["permission-administration"], "write") + mint = self.step("publish", "fork-token") + self.assertTrue(is_action(mint, APP_TOKEN)) + condition = unwrap(str(mint["if"])) + self.assertIn("!inputs.dry_run", condition) + self.assertIn("steps.check.outputs.verdict == 'proposed'", condition) + self.assertIn("inputs.github_app_client_id != ''", condition) + # The forks job made the fork; with none, nothing is minted. + self.assertIn("steps.fork-state.outputs.exists == 'true'", condition) + with_ = cast(dict[str, Any], mint["with"]) + self.assert_expression(with_["owner"], "matrix.fork_org") + self.assert_expression(with_["repositories"], "matrix.repo_name") + self.assertEqual(with_["permission-contents"], "write") + self.assertEqual(with_["permission-metadata"], "read") + self.assertNotIn("permission-pull-requests", with_) + self.assertNotIn("permission-issues", with_) + # Syncing the fork can fast-forward over upstream workflow + # commits, so the grant cannot depend on the proposal's own diff. + self.assertEqual(with_["permission-workflows"], "write") pr = self.step("publish", "pr-token") self.assertTrue(is_action(pr, APP_TOKEN)) @@ -1778,8 +1764,7 @@ def test_writes_never_fall_back_to_the_native_token(self) -> None: """Branch, pull request and comment writes use App tokens alone.""" push = self.step("publish", "push") self.assert_expression( - push["env"]["GH_TOKEN"], - "steps.fork-token.outputs.token || steps.fork-create-token.outputs.token", + push["env"]["GH_TOKEN"], "steps.fork-token.outputs.token" ) self.assertIn("publish.py push", flatten(push["run"])) opened = self.step("publish", "open") @@ -1926,7 +1911,7 @@ def test_every_minted_token_is_checked_for_identity(self) -> None: fork = self.step("publish", "Pre-flight: fork token identity") self.assertEqual( squash(fork["env"]["MINTED_SLUG"]), - "${{ steps.fork-token.outputs.app-slug || steps.fork-create-token.outputs.app-slug }}", + "${{ steps.fork-token.outputs.app-slug }}", ) self.assertLess( self.position("publish", "Pre-flight: fork token identity"), @@ -2049,7 +2034,7 @@ def test_check_audits_online_with_the_native_token(self) -> None: class MintProvenanceContracts(ReusableWorkflowCase): """Every App token names a known owner and carries the least it needs.""" - FORK_MINTS = ("fork-token", "fork-create-token") + FORK_MINTS = ("fork-token",) TARGET_MINTS = ( ("select", "app-token"), ("publish", "pr-token"), @@ -2106,7 +2091,6 @@ def test_no_mint_gains_a_permission(self) -> None: "permission-checks": "read", }, "fork-token": fork, - "fork-create-token": {**fork, "permission-administration": "write"}, "pr-token": { "permission-pull-requests": "write", "permission-metadata": "read", @@ -2127,16 +2111,6 @@ def test_no_mint_requests_actions(self) -> None: self.assertNotIn("permission-actions", with_) self.assertNotIn("INPUT_PERMISSION-ACTIONS", env) - def test_administration_belongs_to_the_creation_mint_alone(self) -> None: - """Only the mint that forks a missing repository may administer.""" - for job, step in self.mints(): - with_ = cast(dict[str, Any], step["with"]) - with self.subTest(job=job, mint=step["id"]): - if step["id"] == "fork-create-token": - self.assertEqual(with_["permission-administration"], "write") - else: - self.assertNotIn("permission-administration", with_) - def test_target_mints_cannot_write_code(self) -> None: """No token for the target organisation can push, run or administer.""" for job, identity in self.TARGET_MINTS: @@ -2182,6 +2156,120 @@ def test_fork_organisation_is_proven_before_any_fork_mint(self) -> None: ) +POOL_TOKEN = "secrets.fork_pool_token" + + +class ForkPreparationContracts(ReusableWorkflowCase): + """Forks are made outside the App, so no mint may administer (#202). + + Creating or renaming a fork needs Administration: write, which an + App holds on every installation at once, the target organisation + included. A machine account's token does it in a job of its own. + """ + + def test_forks_job_runs_beside_the_author_on_live_writing_runs(self) -> None: + """After select, before publish, never in a dry run or select mode.""" + job = self.jobs["forks"] + self.assertEqual(job["name"], "Prepare forks") + self.assertEqual(job["needs"], "select") + self.assert_expression( + job["if"], + "needs.select.outputs.run_agent == 'true' &&" + " !inputs.dry_run && inputs.mode != 'select'", + ) + self.assertEqual(job["permissions"], {"contents": "read"}) + self.assertEqual(self.actions("forks", APP_TOKEN), []) + self.assertEqual(self.jobs["publish"]["needs"], ["select", "author", "forks"]) + + def test_forks_job_is_hardened_like_the_other_trusted_jobs(self) -> None: + """The allow-list loads first and harden-runner blocks against it.""" + steps = self.steps("forks") + self.assertTrue(is_action(steps[0], BLOCK_ACTION)) + self.assertTrue(is_action(steps[1], HARDEN_RUNNER)) + loader = cast(dict[str, Any], steps[0]["with"]) + self.assert_expression(loader["config"], "inputs.harden_runner_allowlist") + self.assertEqual(loader["allow_list_summary"], "false") + self.assert_expression( + steps[1]["with"]["allowed-endpoints"], "env.CONNECTION_ALLOW_LIST" + ) + + def test_forks_job_runs_trusted_assets_alone(self) -> None: + """It checks out the pinned assets, never a target, and reads the matrix.""" + guard = flatten(self.step("forks", "Require trusted provenance")["run"]) + self.assertIn('[[ "$ASSETS_SHA" =~ ^[0-9a-f]{40}$ ]]', guard) + checkout = self.action("forks", CHECKOUT) + with_ = cast(dict[str, Any], checkout["with"]) + self.assert_expression(with_["repository"], "inputs.assets_repository") + self.assert_expression(with_["ref"], "needs.select.outputs.assets_sha") + self.assertEqual(with_["path"], "monkey-assets") + prepare = self.step("forks", "prepare") + script = flatten(prepare["run"]) + self.assertIn("monkey-assets/scripts/fork_pool.py prepare", script) + self.assertIn("--config monkey-assets/config/fork-orgs.json", script) + env = cast(dict[str, Any], prepare["env"]) + self.assert_expression(env["MATRIX"], "needs.select.outputs.matrix") + self.assert_expression(env["ORG"], "inputs.org") + self.assertLess( + self.position("forks", "Require trusted provenance"), + self.position("forks", "prepare"), + ) + + def test_pool_token_reaches_one_step_of_one_job(self) -> None: + """The fork pool token is optional and the prepare step's alone.""" + secrets = cast( + dict[str, dict[str, Any]], self.triggers["workflow_call"]["secrets"] + ) + self.assertIs(secrets["fork_pool_token"]["required"], False) + holders = [ + (job, step.get("id")) + for job in self.jobs + for step in self.jobs[job].get("steps", []) + if "fork_pool_token" in dumped(step) + ] + self.assertEqual(holders, [("forks", "prepare")]) + for job, body in self.jobs.items(): + outside = {k: v for k, v in body.items() if k != "steps"} + with self.subTest(job=job): + self.assertNotIn("fork_pool_token", dumped(outside)) + prepare = self.step("forks", "prepare") + self.assert_expression(prepare["env"]["GH_TOKEN"], POOL_TOKEN) + self.assertEqual( + Counter(SECRET_REFERENCE.findall(dumped(self.jobs["forks"]))), + Counter({POOL_TOKEN: 1}), + ) + + def test_no_mint_requests_administration(self) -> None: + """The App never administers: no mint asks for it at any level.""" + mints = [ + (job, step) + for job in self.jobs + if "steps" in self.jobs[job] + for step in self.actions(job, APP_TOKEN) + ] + self.assertTrue(mints) + for job, step in mints: + with self.subTest(job=job, mint=step["id"]): + self.assertNotIn("permission-administration", step["with"]) + self.assertNotIn( + "INPUT_PERMISSION-ADMINISTRATION", step.get("env") or {} + ) + + def test_publish_requires_the_fork_and_never_creates_it(self) -> None: + """Push holds the fork write token alone and learns when it is missing.""" + ids = [step.get("id") for step in self.steps("publish")] + self.assertNotIn("fork-create-token", ids) + push = self.step("publish", "push") + env = cast(dict[str, Any], push["env"]) + self.assert_expression(env["GH_TOKEN"], "steps.fork-token.outputs.token") + self.assert_expression(env["FORK_EXISTS"], "steps.fork-state.outputs.exists") + script = flatten(push["run"]) + self.assertIn('if [ "$FORK_EXISTS" = false ]; then', script) + self.assertIn("extra+=(--fork-missing)", script) + self.assertLess( + self.position("publish", "fork-state"), self.position("publish", "push") + ) + + class SelectAndReportContracts(ReusableWorkflowCase): """Trusted selection outputs, org-wide read mint, result gathering.""" @@ -3702,6 +3790,7 @@ def test_declared_inputs_and_secrets(self) -> None: "github_app_private_key", "copilot_review_token", "antagonistic_dispatch_token", + "fork_pool_token", }, ) for name, secret in secrets.items(): @@ -4049,6 +4138,7 @@ def test_caller_forwards_credentials_and_pins_assets(self) -> None: "github_app_private_key", "copilot_review_token", "antagonistic_dispatch_token", + "fork_pool_token", }, ) self.assert_expression(secrets["copilot_token"], "secrets.COPILOT_CLI_TOKEN") @@ -4056,6 +4146,11 @@ def test_caller_forwards_credentials_and_pins_assets(self) -> None: secrets["github_app_private_key"], "secrets.BOT_APP_PRIVATE_KEY" ) + def test_caller_forwards_the_fork_pool_token(self) -> None: + """The machine account's token arrives under its repository secret name.""" + secrets = cast(dict[str, Any], self.jobs["code-monkey"]["secrets"]) + self.assert_expression(secrets["fork_pool_token"], "secrets.FORK_POOL_TOKEN") + def test_options_job_loads_the_allow_list(self) -> None: """The options job blocks egress against the forwarded allow-list. diff --git a/tests/test_write_recovery.py b/tests/test_write_recovery.py index a0052fe1..f61c9838 100644 --- a/tests/test_write_recovery.py +++ b/tests/test_write_recovery.py @@ -249,6 +249,7 @@ def push(self, check: dict[str, Any] | None = None) -> dict[str, Any]: workdir=self.root / "work", mode="pull-requests", dry_run=False, + fork_missing=False, run_attempt=1, author_session="", output=self.root / "result.json",