Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
51 changes: 34 additions & 17 deletions docs/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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 |
Expand Down Expand Up @@ -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
Expand Down
66 changes: 4 additions & 62 deletions scripts/fork_pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -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``
Expand All @@ -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."""

Expand Down Expand Up @@ -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.

Expand Down
137 changes: 137 additions & 0 deletions scripts/pool_token.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading