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
5 changes: 5 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ jobs:
run: NODE_PATH="${RUNNER_TEMP}/crate-analysis/node_modules" node scripts/release/test-source-version.mjs
- name: Plan the actual source version without write credentials
id: plan
env:
# Hosted runners share addresses whose anonymous API quota is often
# exhausted. This job's token is read-only (workflow contents: read).
GH_READ_TOKEN: ${{ github.token }}
run: |
NODE_PATH="${RUNNER_TEMP}/crate-analysis/node_modules" \
node scripts/release/source-version.mjs > "${RUNNER_TEMP}/source-plan.json"
Expand All @@ -75,6 +79,7 @@ jobs:
if: steps.plan.outputs.version != ''
env:
SOURCE_VERSION: ${{ steps.plan.outputs.version }}
GH_READ_TOKEN: ${{ github.token }}
run: tools/package-release.sh build/release "${SOURCE_VERSION}"
- name: Retain the complete verified release payload
if: steps.plan.outputs.version != ''
Expand Down
10 changes: 7 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,13 @@
Trusted Publishing in the main-only `crates-io-release` environment, without
required reviewers or wait timers. One-time environment/registration setup
remains an owner operation, tracked in `github-settings`.
- Source packaging runs twice in a credential-free read-only job, with independent
extracted-package verification. No registry token, OIDC capability or GitHub write
credential may reach Cargo/build scripts. The write-enabled semantic-release job
- Source packaging runs twice in a read-only job without write credentials, with
independent extracted-package verification. Only its planning and preparation
steps get the read-only job token in their environment, for public release
catalog reads;
`package-release.sh` passes it only to `crate_prepare.py`, which strips it before
Cargo. No registry token, OIDC capability or GitHub write credential may reach
Cargo/build scripts. The write-enabled semantic-release job
only checks and publishes the complete prebuilt inventory. It must refuse any
difference in its independently analyzed source version or revision.
Governance enables immutable releases before activation; the source job does
Expand Down
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,14 @@ future candidates use `reviewed-automatic-publication`. No post-release policy P
is needed to copy a checksum back into source.

The read-only source job plans the next repository version, runs the aggregate,
packages the public crate graph twice and builds the extracted archives. It emits
packages the public crate graph twice and builds the extracted archives. Only its
planning and preparation steps get the job's read-only `GITHUB_TOKEN`
(`contents: read`) in their environment, for public release catalog reads, because
hosted runners share addresses whose anonymous GitHub API quota is often
exhausted. The pinned checkout and setup actions also receive it through their
default `token` input. In preparation, `tools/package-release.sh` unsets it at
once and hands it only to `crate_prepare.py`, which strips it again before Cargo
packages or verifies the crate graph. It emits
`crate-release.json` with actual source revision, source tag, inventory, registry
metadata, archive SHA-256 and a content checksum excluding only VCS metadata.
Changed package content with a reused Cargo version fails. Historical 0.1.0 and
Expand Down
65 changes: 64 additions & 1 deletion tools/check-crate-release-policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
PUBLISH_WORKFLOW = WORKFLOWS / "publish-crate.yml"
BOOTSTRAP_CHECK = ROOT / "tools" / "check-crate-publication.py"
SOURCE_WORKFLOW = WORKFLOWS / "release.yml"
EXPECTED_SOURCE_WORKFLOW_SHA256 = "f897401133c5d69d73edbafe020cdf80cedcabbe31f76233a9e1a9f52a19ae94"
PACKAGE_SCRIPT = ROOT / "tools" / "package-release.sh"
EXPECTED_SOURCE_WORKFLOW_SHA256 = "818d6584dc464997c8fb1021243159ceac2096a8d73d186462930fc7fc904d29"
EXPECTED_PUBLICATION_WORKFLOW_SHA256 = "b0491b93c39cb1b58e73afff2ac49a9aea8854a53c1de2df04a66ca639ffe58a"
EXPECTED_WORKFLOWS = {
"dependency-review.yml", "pr-title.yml", "release.yml", "validate.yml",
Expand All @@ -33,6 +34,18 @@
"environment": "crates-io-release",
}

# Shared hosted-runner addresses exhaust GitHub's anonymous API quota, so the
# source job's release catalog reads carry its read-only token, and only there.
SOURCE_READ_TOKEN_STEPS = (
"Plan the actual source version without write credentials",
"Prepare every immutable source and crate asset",
)
SOURCE_READ_TOKEN = "\n GH_READ_TOKEN: ${{ github.token }}\n"
# The preparation step runs package-release.sh, which must hand the token only
# to crate preparation (which strips it before Cargo), not to its other tools.
PACKAGE_SCRIPT_TOKEN_SCOPE = "\ndeclare +x catalog_read_token=${GH_READ_TOKEN-}\nunset GH_READ_TOKEN\n"
PACKAGE_SCRIPT_TOKEN_USE = "\nGH_READ_TOKEN=${catalog_read_token} python3 tools/crate_prepare.py prepare "

FORBIDDEN_WORKFLOW_FRAGMENTS = (
"CARGO_REGISTRY_BOOTSTRAP_TOKEN",
"CARGO_REGISTRY_TOKEN",
Expand All @@ -47,6 +60,54 @@ def load_json(path: Path) -> object:
return json.loads(path.read_text(encoding="utf-8"))


def workflow_permissions(text: str) -> list[str] | None:
"""Entries of the one top-level permissions block; YAML blank lines don't end it."""
# splitlines() also splits on CR, NEL, U+2028 and U+2029, which YAML parsers
# may treat as line breaks, so a comment cannot hide a further scope.
lines = text.splitlines()
heads = [index for index, line in enumerate(lines) if line.startswith("permissions:")]
if len(heads) != 1 or lines[heads[0]] != "permissions:":
return None
entries = []
for line in lines[heads[0] + 1:]:
if line and not line[0].isspace() and not line.startswith("#"):
break
if line.strip() and not line.strip().startswith("#"):
entries.append(line.strip())
return entries


def check_source_read_token(text: str, script: str) -> None:
start, end = text.find("\n package:\n"), text.find("\n attest:\n")
if start < 0 or end < start:
raise SystemExit("source package job is missing")
job = text[start:end]
if workflow_permissions(text) != ["contents: read"] or "permissions" in job:
raise SystemExit("source package job must keep the read-only workflow token")
steps = job.split("\n - ")[1:]
carrying = [
step.partition("\n")[0].removeprefix("name: ")
for step in steps
if "\n env:\n" in step and SOURCE_READ_TOKEN in step
]
# Count the credential as well as the name, so no alias, anchor (including
# one defined before the job), secret or whole-context dump carries it to
# another step. Expressions are case-insensitive and allow whitespace.
expressions = "".join(text[:end].lower().split())
if (carrying != list(SOURCE_READ_TOKEN_STEPS) or job.count("GH_READ_TOKEN") != len(carrying)
or expressions.count("github.token") != len(carrying) or "secrets" in job.lower()
or "tojson(github" in expressions or "github[" in expressions):
raise SystemExit("source catalog reads must use the read-only token in exactly the planning and preparation steps")
# Scope the token before the script's first command; only the shebang,
# set -euo pipefail and comments may precede it. Without the scope lines,
# the partition leaves the whole script before them, so it fails too.
before = script.partition(PACKAGE_SCRIPT_TOKEN_SCOPE)[0]
commands = [line for line in before.splitlines() if line.strip() and not line.lstrip().startswith("#")]
if (commands != ["set -euo pipefail"] or PACKAGE_SCRIPT_TOKEN_USE not in script
or script.count("GH_READ_TOKEN") != 3 or script.count("catalog_read_token") != 2):
raise SystemExit("package-release.sh must pass the read token only to crate preparation")


def main() -> None:
publishing = load_json(PUBLISHING_POLICY)
release = load_json(RELEASE_POLICY)
Expand Down Expand Up @@ -110,6 +171,8 @@ def main() -> None:
if {path.name for path in workflow_paths} != EXPECTED_WORKFLOWS:
raise SystemExit("reviewed workflow inventory changed")

check_source_read_token(SOURCE_WORKFLOW.read_text(encoding="utf-8"),
PACKAGE_SCRIPT.read_text(encoding="utf-8"))
for workflow in workflow_paths:
text = workflow.read_text(encoding="utf-8")
for fragment in FORBIDDEN_WORKFLOW_FRAGMENTS:
Expand Down
10 changes: 9 additions & 1 deletion tools/package-release.sh
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
#!/usr/bin/env bash
set -euo pipefail

# Only crate preparation reads the release catalog with the read-only job token,
# and it strips the token again before Cargo runs. No other command below may
# inherit it (this limits accidental exposure; it is not a barrier against
# hostile code running as this user). declare +x also drops a plain inherited
# export of the holder's own name, so never export the holder.
declare +x catalog_read_token=${GH_READ_TOKEN-}
unset GH_READ_TOKEN

repository=$(git rev-parse --show-toplevel)
cd "${repository}"

Expand Down Expand Up @@ -130,7 +138,7 @@ prepare_options=()
if [[ ${version} == *-validation || ${CRATE_RELEASE_DRY_RUN:-0} == 1 ]]; then
prepare_options+=(--dry-run)
fi
python3 tools/crate_prepare.py prepare "${prepare_options[@]}" \
GH_READ_TOKEN=${catalog_read_token} python3 tools/crate_prepare.py prepare "${prepare_options[@]}" \
--source-tag "v${version}" --output "$(realpath "${output}")"

(
Expand Down
20 changes: 20 additions & 0 deletions tools/test_crate_release.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"""Negative tests for the portable exact-archive publication boundary."""
from __future__ import annotations

import ast
import copy
from contextlib import ExitStack
import gzip
Expand Down Expand Up @@ -611,6 +612,25 @@ def test_actions_source_ref_cannot_be_overridden_and_read_token_not_in_build(sel
with patch.dict(os.environ, {'GH_READ_TOKEN': 'read-only-secret'}, clear=True):
self.assertNotIn('GH_READ_TOKEN', P.clean_environment())

def test_preparation_subprocesses_other_than_git_drop_the_read_token(self):
# The source job hands prepare() GH_READ_TOKEN for catalog reads; only
# clean_environment() keeps it from Cargo, build scripts and the verifier.
source = Path(P.__file__).read_text()
self.assertNotRegex(source, r'\bos\.(system|popen|exec|spawn|posix_spawn)|\bpty\.'
r'|from subprocess import|import subprocess as')
calls = [node for node in ast.walk(ast.parse(source)) if isinstance(node, ast.Call)
and isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name)
and node.func.value.id == 'subprocess']
self.assertEqual(len(calls), 4)
for call in calls:
command = call.args[0] if call.args else None
if (isinstance(command, ast.List) and isinstance(command.elts[0], ast.Constant)
and command.elts[0].value == 'git'):
continue
env = [keyword.value for keyword in call.keywords if keyword.arg == 'env']
self.assertTrue(env and isinstance(env[0], ast.Call) and isinstance(env[0].func, ast.Name)
and env[0].func.id == 'clean_environment', ast.unparse(call))

def test_required_checks_exact_revision_name_app_and_latest_success(self):
check = {'name': 'Example validation', 'head_sha': REVISION, 'app': {'slug': 'github-actions'},
'id': 1, 'status': 'completed', 'conclusion': 'success'}
Expand Down
113 changes: 113 additions & 0 deletions tools/test_crate_release_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ def setUp(self) -> None:
"policy/rust-crate-publishing.json",
"policy/rust-crate-release.json",
"tools/check-crate-release-policy.py",
"tools/package-release.sh",
):
source = SOURCE_ROOT / relative
target = self.root / relative
Expand Down Expand Up @@ -133,6 +134,118 @@ def test_rejects_oidc_permission_in_existing_workflow(self) -> None:
stream.write("\n# id-token: write\n")
self.assert_rejected("disabled registry capability")

def test_source_catalog_reads_use_only_the_read_only_job_token(self) -> None:
path = self.root / ".github" / "workflows" / "release.yml"
original = path.read_text(encoding="utf-8")
token = " GH_READ_TOKEN: ${{ github.token }}\n"
plan = original.index(" id: plan\n")
prepare = original.index(" SOURCE_VERSION: ${{ steps.plan.outputs.version }}\n")
placement = "source catalog reads must use the read-only token"
permission = "source package job must keep the read-only workflow token"

def validate_env(entry: str) -> str:
return original.replace(" run: tools/validate.sh\n",
" env:\n " + entry + "\n run: tools/validate.sh\n", 1)

for case, changed, expected in (
("planning step without token",
original[:plan] + original[plan:].replace(token, "", 1), placement),
("preparation step without token",
original[:prepare] + original[prepare:].replace(token, "", 1), placement),
("token widened to the package job",
original.replace(" env:\n CARGO_HOME:",
" env:\n GH_READ_TOKEN: ${{ github.token }}\n CARGO_HOME:", 1),
placement),
("token given to the aggregate validation step",
original.replace(" run: tools/validate.sh\n", " env:\n" + token + " run: tools/validate.sh\n", 1),
placement),
("token renamed for the aggregate validation step",
original.replace(" run: tools/validate.sh\n",
" env:\n GH_TOKEN: ${{ github.token }}\n run: tools/validate.sh\n", 1),
placement),
("token aliased through secrets",
original.replace(" run: cargo fetch --locked\n",
" env:\n FETCH: ${{ secrets.GITHUB_TOKEN }}\n run: cargo fetch --locked\n", 1),
placement),
("token anchored for reuse",
original.replace(token, token + " LEAK: &leak ${{ github.token }}\n", 1).replace(
" run: tools/validate.sh\n", " env:\n LEAK: *leak\n run: tools/validate.sh\n", 1),
placement),
("token anchored before the package job",
original.replace(" group: protocol-semantic-release\n",
" group: protocol-semantic-release\n leak: &leak ${{ github.token }}\n", 1).replace(
" run: tools/validate.sh\n", " env:\n LEAK: *leak\n run: tools/validate.sh\n", 1),
placement),
("token in another letter case",
validate_env("LEAK: ${{ github.TOKEN }}"), placement),
("secret by index",
validate_env("LEAK: ${{ secrets['GITHUB_TOKEN'] }}"), placement),
("whole github context",
validate_env("LEAK: ${{ toJSON(github) }}"), placement),
("github context by index",
validate_env("LEAK: ${{ github [ 'token' ] }}"), placement),
("package job write permission",
original.replace(" timeout-minutes: 40\n", " timeout-minutes: 40\n permissions:\n contents: write\n", 1),
permission),
("workflow write permission",
original.replace("permissions:\n contents: read\n", "permissions:\n contents: write\n", 1), permission),
("workflow scopes after a blank line",
original.replace("permissions:\n contents: read\n\n",
"permissions:\n contents: read\n\n id-token: write\n actions: write\n\n", 1),
permission),
("workflow read-all shorthand",
original.replace("permissions:\n contents: read\n", "permissions: read-all\n", 1), permission),
("workflow scope hidden by a comment line separator",
original.replace("permissions:\n contents: read\n",
"permissions:\n contents: read\n # note\u2028 actions: write\n", 1), permission),
("package job permissions key with a space",
original.replace(" timeout-minutes: 40\n", " timeout-minutes: 40\n permissions : write-all\n", 1),
permission),
("package job quoted permissions key",
original.replace(" timeout-minutes: 40\n", ' timeout-minutes: 40\n "permissions": write-all\n', 1),
permission),
):
with self.subTest(case=case):
self.assertNotEqual(changed, original)
path.write_text(changed, encoding="utf-8")
self.assert_rejected(expected)

def test_release_script_passes_read_token_only_to_crate_preparation(self) -> None:
path = self.root / "tools" / "package-release.sh"
original = path.read_text(encoding="utf-8")
scope = "declare +x catalog_read_token=${GH_READ_TOKEN-}\nunset GH_READ_TOKEN\n"
use = "GH_READ_TOKEN=${catalog_read_token} python3 tools/crate_prepare.py prepare "
cd = 'cd "${repository}"\n'
for case, changed in (
("token left exported", original.replace("unset GH_READ_TOKEN\n", "", 1)),
("holder exported", original.replace("declare +x catalog_read_token", "export catalog_read_token", 1)),
("scope after the first command",
original.replace(scope, "", 1).replace(cd, cd + scope, 1)),
("token withheld from crate preparation",
original.replace(use, "python3 tools/crate_prepare.py prepare ", 1)),
("token passed to cargo package",
original.replace(" cargo package --locked --offline --allow-dirty",
" GH_READ_TOKEN=${catalog_read_token} cargo package --locked --offline --allow-dirty", 1)),
("token passed to the contract bundle",
original.replace("python3 tools/contract_release_bundle.py",
"GH_READ_TOKEN=${catalog_read_token} python3 tools/contract_release_bundle.py", 1)),
("token re-exported", original.replace(use, "export GH_READ_TOKEN=${catalog_read_token}\n" + use, 1)),
("holder exported on a later line",
original.replace("unset GH_READ_TOKEN\n", "unset GH_READ_TOKEN\nexport catalog_read_token\n", 1)),
("token passed to cargo package through indirect expansion",
original.replace(" cargo package --locked --offline --allow-dirty",
" holder=catalog_read; holder+=_token\n"
" GH_READ_TOKEN=${!holder} cargo package --locked --offline --allow-dirty", 1)),
("token moved from crate preparation to cargo package",
original.replace(use, "python3 tools/crate_prepare.py prepare ", 1).replace(
" cargo package --locked --offline --allow-dirty",
" GH_READ_TOKEN=${catalog_read_token} cargo package --locked --offline --allow-dirty", 1)),
):
with self.subTest(case=case):
self.assertNotEqual(changed, original)
path.write_text(changed, encoding="utf-8")
self.assert_rejected("package-release.sh must pass the read token only to crate preparation")

def test_rejects_registry_capabilities_in_dependency_review(self) -> None:
path = self.root / ".github" / "workflows" / "dependency-review.yml"
original = path.read_text(encoding="utf-8")
Expand Down