diff --git a/README.md b/README.md index ecbe7ce..895c3ce 100644 --- a/README.md +++ b/README.md @@ -164,8 +164,12 @@ the bot fork organisations and no other (section 10.6). The account needs admin on every repository in those organisations, as an owner or through a base permission of admin: renaming a fork to follow a renamed target needs admin on the fork, and the forks already in -the pools are not the account's own. Without the token, existing -forks keep working and a target with no fork fails its publish. +the pools are not the account's own. Create the token with an +expiry no more than 90 days ahead: the forks job refuses one that +never expires or expires later, and warns on every run from 14 days +before the expiry, when the owner rotates the secret. Without the +token, 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 diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 9b2d74c..655aa62 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -2051,22 +2051,38 @@ job makes no write to that fork. 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). +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` first has `pool_token.py` read the token's +`X-OAuth-Scopes` and refuse 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. + +No classic token stops at chosen organisations: it can write to +every repository the account can, the forks that head the open pull +requests among them, and GitHub signs commits made through the API. +Human approval, last-push approval and stale-review dismissal still +stand between such a commit and a merge, but a leaked token stays +useful until it expires, and a classic token may never expire. So +`pool_token.py` also reads the `GitHub-Authentication-Token-Expiration` +header of the same reply, which GitHub omits for a token that never +expires. No header, one it cannot parse, or an expiry more than 90 +days ahead fails the job before any write, naming the date it read: +the owner rotates the token at least every 90 days. An expiry 14 +days away or less passes with a `::warning` naming the date on every +run, and the rotation falls due before the job stops. The token's +owner creates its successor with an expiry within 90 days and +replaces `FORK_POOL_TOKEN` when the warning appears. ## 11. Dispatch and Concurrency @@ -2196,7 +2212,7 @@ conflicts while producer artifacts survive. | 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 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) | +| 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 or expires within 14 days, and fails naming the scopes or the expiry 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 | @@ -2274,6 +2290,7 @@ 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/pool_token.py its token's scopes and expiry (§10.6) 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/scripts/fork_pool.py b/scripts/fork_pool.py index b4f9d5a..d47a1f2 100644 --- a/scripts/fork_pool.py +++ b/scripts/fork_pool.py @@ -8,9 +8,9 @@ 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. +with the ``public_repo`` scope and nothing more. The token check in +``pool_token.py`` refuses any other kind, and a token that never +expires or expires more than 90 days ahead, before any write. ``fork_pool.py prepare --config FILE --org ORG --matrix-env NAME`` reads the select job's matrix from the environment variable ``NAME`` @@ -34,20 +34,13 @@ import bot_github as github import branch_refs as refs import fork_orgs as forks +from pool_token import PoolError, check_token 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.""" @@ -110,57 +103,6 @@ def targets(matrix: str, config: dict[str, Any], org: str) -> list[Target]: return list(found.values()) -def token_identity() -> tuple[frozenset[str] | None, str | None]: - """The classic token's scopes and the login of the account it serves. - - GitHub reports a classic token's scopes in the X-OAuth-Scopes - header of any API reply; fine-grained and App tokens carry none, - and the scopes are None for them. The login comes from the body. - """ - lines = github.run_gh(["api", "--include", "user"]).splitlines() - end = next((i for i, line in enumerate(lines) if not line.strip()), len(lines)) - scopes: frozenset[str] | None = None - for line in lines[:end]: - name, sep, value = line.partition(":") - if sep and name.strip().lower() == SCOPES_HEADER: - scopes = frozenset(s.strip() for s in value.split(",") if s.strip()) - break - try: - user: Any = json.loads("\n".join(lines[end + 1 :])) - except (ValueError, RecursionError): - user = None - login = ( - cast("dict[str, Any]", user).get("login") if isinstance(user, dict) else None - ) - return scopes, login if isinstance(login, str) and login else None - - -def check_token() -> str: - """Refuse any token but a classic one scoped to public_repo alone. - - Return the login of the pool account the token belongs to, which - names that account in a failure it alone can fix. - """ - try: - scopes, login = token_identity() - 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" - ) - if login is None: - raise PoolError("the fork pool token's account reports no login") - return login - - def check_rename_rights(found: str, fork_org: str, account: str) -> None: """Fail unless the pool account may rename ``found``: that needs admin. diff --git a/scripts/pool_token.py b/scripts/pool_token.py new file mode 100644 index 0000000..89f6ab5 --- /dev/null +++ b/scripts/pool_token.py @@ -0,0 +1,137 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: 2026 The Linux Foundation + +"""The fork pool token check the forks job makes before any write. + +``fork_pool.py`` creates and renames forks through a classic token of +a machine account in the bot fork organisations (DESIGN.md section +10.6). ``check_token`` refuses any token but a classic one with the +``public_repo`` scope alone, so an operator's own token, or one with +broader scopes, never reaches a write. It also refuses a token that +never expires or expires more than 90 days ahead, and warns when the +expiry is 14 days away or less. +""" + +from __future__ import annotations + +import json +from datetime import UTC, datetime, timedelta +from typing import Any, NamedTuple, cast + +import bot_github as github + +# 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" +# GitHub names a classic token's expiry here, as ``2027-01-18 10:39:33 +# UTC``, and omits the header for a token that never expires. +EXPIRY_HEADER = "github-authentication-token-expiration" +EXPIRY_FORMAT = "%Y-%m-%d %H:%M:%S %z" +# A leaked token writes until it lapses, so it must lapse within this +# window, and the job warns while this much of it remains. +MAX_TOKEN_LIFETIME = timedelta(days=90) +ROTATION_WARNING = timedelta(days=14) + + +class PoolError(Exception): + """The matrix, the mapping or the token rules out preparing forks.""" + + +class TokenIdentity(NamedTuple): + """What ``gh api --include user`` reports about the pool token.""" + + scopes: frozenset[str] | None + expiry: str | None + login: str | None + + +def token_identity() -> TokenIdentity: + """The classic token's scopes and expiry, and its account's login. + + GitHub reports a classic token's scopes in the X-OAuth-Scopes + header of any API reply; fine-grained and App tokens carry none, + and the scopes are None for them. The expiry header is None for a + token that never expires. The login comes from the body. + """ + lines = github.run_gh(["api", "--include", "user"]).splitlines() + end = next((i for i, line in enumerate(lines) if not line.strip()), len(lines)) + headers: dict[str, str] = {} + for line in lines[:end]: + name, sep, value = line.partition(":") + if sep: + headers.setdefault(name.strip().lower(), value.strip()) + scopes_text = headers.get(SCOPES_HEADER) + scopes = ( + None + if scopes_text is None + else frozenset(s.strip() for s in scopes_text.split(",") if s.strip()) + ) + try: + user: Any = json.loads("\n".join(lines[end + 1 :])) + except (ValueError, RecursionError): + user = None + login = ( + cast("dict[str, Any]", user).get("login") if isinstance(user, dict) else None + ) + return TokenIdentity( + scopes, + headers.get(EXPIRY_HEADER), + login if isinstance(login, str) and login else None, + ) + + +def check_expiry(expiry: str | None) -> None: + """Refuse a token that never expires or outlives the rotation window. + + A token within ``ROTATION_WARNING`` of its expiry passes with a + warning, on every run, so the rotation is due before the job stops. + """ + if expiry is None: + raise PoolError("the fork pool token never expires; create it with an expiry") + text = expiry.removesuffix(" UTC") + " +0000" if expiry.endswith(" UTC") else expiry + try: + when = datetime.strptime(text, EXPIRY_FORMAT) + except ValueError as exc: + raise PoolError( + f"the fork pool token's expiry {expiry!r} cannot be read" + ) from exc + left = when - datetime.now(UTC) + if left > MAX_TOKEN_LIFETIME: + raise PoolError( + f"the fork pool token expires {expiry}, more than " + f"{MAX_TOKEN_LIFETIME.days} days ahead; create it with an expiry " + f"within {MAX_TOKEN_LIFETIME.days} days" + ) + if left <= ROTATION_WARNING: + print( + "::warning title=Fork pool token expires soon::the fork pool " + f"token expires {expiry}; rotate FORK_POOL_TOKEN before then" + ) + + +def check_token() -> str: + """Refuse any token but a classic, expiring one scoped to public_repo alone. + + Return the login of the pool account the token belongs to, which + names that account in a failure it alone can fix. + """ + try: + scopes, expiry, login = token_identity() + 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" + ) + check_expiry(expiry) + if login is None: + raise PoolError("the fork pool token's account reports no login") + return login diff --git a/tests/test_fork_pool.py b/tests/test_fork_pool.py index a40746b..059e6cb 100644 --- a/tests/test_fork_pool.py +++ b/tests/test_fork_pool.py @@ -5,10 +5,13 @@ from __future__ import annotations +import io import json import sys import tempfile import unittest +from contextlib import redirect_stdout +from datetime import UTC, datetime, timedelta from importlib import import_module from pathlib import Path from typing import Any @@ -25,7 +28,28 @@ FORK = f"{FORK_ORG}/repo" CONFIG: dict[str, Any] = {"default": FORK_ORG, "organisations": {}} ACCOUNT = "pool-bot" -SCOPED = f'HTTP/2.0 200 OK\nX-Oauth-Scopes: public_repo\n\n{{"login": "{ACCOUNT}"}}' + + +def expiring(days: float) -> str: + """The expiry header of a token that lapses ``days`` from now.""" + when = datetime.now(UTC) + timedelta(days=days) + return f"GitHub-Authentication-Token-Expiration: {when:%Y-%m-%d %H:%M:%S} UTC" + + +def reply( + scopes: str = "public_repo", + expiry: str | None = None, + body: str = f'{{"login": "{ACCOUNT}"}}', +) -> str: + """A ``gh api --include user`` reply; a 30-day expiry unless given.""" + expiry = expiring(30) if expiry is None else expiry + headers = ["HTTP/2.0 200 OK", f"X-Oauth-Scopes: {scopes}"] + if expiry: + headers.append(expiry) + return "\n".join([*headers, "", body]) + + +SCOPED = reply() OLD = f"{FORK_ORG}/old-repo" @@ -171,22 +195,23 @@ def test_public_repo_alone_passes(self) -> None: def test_account_without_login_is_refused(self) -> None: """A failure the account must fix names it, so its login is required.""" for body in ("{}", "[]", "not json", '{"login": ""}'): - reply = f"HTTP/2.0 200 OK\nX-Oauth-Scopes: public_repo\n\n{body}" with ( self.subTest(body=body), self.assertRaisesRegex(pool.PoolError, "reports no login"), ): - self.check(reply) + self.check(reply(body=body)) def test_broader_scopes_are_refused(self) -> None: - """An operator's token, or one that can do more, never writes.""" + """An operator's token, or one that can do more, never writes. + + A well-formed expiry does not excuse a scope beyond public_repo. + """ 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) + self.check(reply(scopes=scopes, body="{}")) def test_token_without_scopes_is_refused(self) -> None: """Fine-grained and App tokens report no scopes header.""" @@ -198,6 +223,46 @@ def test_a_header_in_the_body_does_not_count(self) -> None: 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_token_that_never_expires_is_refused(self) -> None: + """A classic token may be made without expiry; this one may not.""" + with self.assertRaisesRegex( + pool.PoolError, "never expires; create it with an expiry" + ): + self.check(reply(expiry="")) + + def test_unparsable_expiry_is_refused(self) -> None: + """An expiry the job cannot read fails, as a missing scope header does.""" + for value in ("soon", "2027-13-40 10:39:33 UTC", "2027-01-18"): + header = f"GitHub-Authentication-Token-Expiration: {value}" + with ( + self.subTest(value=value), + self.assertRaisesRegex(pool.PoolError, "expiry .* cannot be read"), + ): + self.check(reply(expiry=header)) + + def test_expiry_beyond_ninety_days_is_refused(self) -> None: + """A token must be rotated at least every 90 days.""" + header = expiring(91) + date = header.partition(": ")[2] + with self.assertRaisesRegex(pool.PoolError, f"expires {date}.*90 days"): + self.check(reply(expiry=header)) + + def test_expiry_within_fourteen_days_warns_and_passes(self) -> None: + """A rotation falling due is announced on every run, without failing.""" + header = expiring(13) + output = io.StringIO() + with redirect_stdout(output): + self.assertEqual(self.check(reply(expiry=header)), ACCOUNT) + self.assertIn("::warning", output.getvalue()) + self.assertIn(header.partition(": ")[2], output.getvalue()) + + def test_expiry_in_between_passes_silently(self) -> None: + """A token with weeks to run neither warns nor fails.""" + output = io.StringIO() + with redirect_stdout(output): + self.assertEqual(self.check(reply(expiry=expiring(60))), ACCOUNT) + self.assertEqual(output.getvalue(), "") + def test_unreadable_token_is_refused(self) -> None: """A rejected token fails before any fork is touched.""" with ( @@ -532,7 +597,7 @@ def test_one_failure_fails_the_job_after_every_target(self) -> None: 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{}" + broad = reply(scopes="repo", body="{}") with ( patch.object(github, "run_gh", return_value=broad), patch.object(github, "api_object") as read, @@ -540,6 +605,22 @@ def test_a_wrong_token_stops_before_any_fork(self) -> None: self.assertEqual(self.run_main(env), 1) read.assert_not_called() + def test_a_bad_expiry_stops_before_any_fork(self) -> None: + """No expiry, an unreadable one or a distant one exits 1 before reading.""" + env = {"GH_TOKEN": "t", "MATRIX": matrix(entry())} + for expiry in ( + "", + "GitHub-Authentication-Token-Expiration: soon", + expiring(91), + ): + with ( + self.subTest(expiry=expiry), + patch.object(github, "run_gh", return_value=reply(expiry=expiry)), + 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: