diff --git a/.github/workflows/call-images-build-ci.yml b/.github/workflows/call-images-build-ci.yml index e375c6af30..a445630d43 100644 --- a/.github/workflows/call-images-build-ci.yml +++ b/.github/workflows/call-images-build-ci.yml @@ -78,6 +78,8 @@ jobs: permissions: contents: read packages: write + env: + FORK_TARGET_BUILD: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.head.repo.full_name != github.repository }} steps: - name: ⬇️ Checkout trusted workflow repo (helpers) @@ -158,7 +160,8 @@ jobs: INFINITO_DISTROS: ${{ join(fromJson(needs.pools.outputs.matrix), ' ') }} IMAGE_ARCH: ${{ matrix.architecture }} IMAGE_DIGEST_DIR: build/image-digests - USE_NIX_TOKEN: ${{ !(github.event_name == 'pull_request_target' && github.event.pull_request.head.repo.full_name != github.repository) }} + USE_NIX_TOKEN: ${{ env.FORK_TARGET_BUILD != 'true' }} + EXPORT_BUILD_CACHE: ${{ env.FORK_TARGET_BUILD != 'true' }} NIX_GITHUB_TOKEN: ${{ github.token }} MAX_ATTEMPTS: "7" RETRY_DELAY_SECONDS: "20" diff --git a/.github/workflows/call-images-mirror-missing.yml b/.github/workflows/call-images-mirror-missing.yml index 9d95329996..7f70bdec8a 100644 --- a/.github/workflows/call-images-mirror-missing.yml +++ b/.github/workflows/call-images-mirror-missing.yml @@ -91,6 +91,8 @@ jobs: steps: - name: ⬇️ Checkout uses: actions/checkout@v7.0.0 + with: + persist-credentials: false - name: 🔍 Resolve GHCR namespace and repository id: vars @@ -99,6 +101,10 @@ jobs: GHCR_NAMESPACE_INPUT: ${{ inputs.ghcr_namespace || '' }} run: bash scripts/meta/resolve/ghcr/namespace_and_repository.sh + - name: 🔗 Check symlinks out as plain files (optional) + if: ${{ inputs.source_repository != '' && inputs.source_ref != '' }} + run: git config --global core.symlinks false + - name: ⬇️ Checkout source repo for scan (optional) if: ${{ inputs.source_repository != '' && inputs.source_ref != '' }} uses: actions/checkout@v7.0.0 @@ -110,6 +116,12 @@ jobs: persist-credentials: false allow-unsafe-pr-checkout: ${{ inputs.allow_unsafe_checkout }} + - name: 🔗 Refuse symlinks in the scanned source (optional) + if: ${{ inputs.source_repository != '' && inputs.source_ref != '' }} + env: + SOURCE_PATH: ${{ inputs.source_path }} + run: bash scripts/github/gate/no_symlinks.sh "${SOURCE_PATH}" + - name: 🔧 Setup Python uses: actions/setup-python@v6 with: diff --git a/.github/workflows/entry-pr-change-orchestrate.yml b/.github/workflows/entry-pr-change-orchestrate.yml index 0a3c46f036..4f2921e911 100644 --- a/.github/workflows/entry-pr-change-orchestrate.yml +++ b/.github/workflows/entry-pr-change-orchestrate.yml @@ -140,8 +140,27 @@ jobs: PR_MERGE_SHA: ${{ github.event.pull_request.merge_commit_sha || '' }} run: ./scripts/meta/resolve/pr/merge_ref.sh - build-ci-images-fork: + fork-trust-gate: + name: 🛡️ Gate fork trust needs: prepare-fork-merge-ref + runs-on: ubuntu-26.04 + steps: + - name: ⬇️ Checkout + uses: actions/checkout@v7.0.0 + with: + persist-credentials: false + + - name: 🛡️ Require the maintainer Trusted label + shell: bash + env: + TRUSTED: ${{ needs.prepare-fork-merge-ref.outputs.trusted }} + PR_NUMBER: ${{ github.event.pull_request.number }} + run: bash scripts/github/gate/trusted_label.sh + + build-ci-images-fork: + needs: + - prepare-fork-merge-ref + - fork-trust-gate permissions: contents: read packages: write @@ -155,7 +174,9 @@ jobs: allow_unsafe_checkout: true images-mirror-missing-fork: - needs: prepare-fork-merge-ref + needs: + - prepare-fork-merge-ref + - fork-trust-gate permissions: contents: read packages: write diff --git a/docs/contributing/artefact/git/pipeline.md b/docs/contributing/artefact/git/pipeline.md index e69ee1385d..1bbe1b25a9 100644 --- a/docs/contributing/artefact/git/pipeline.md +++ b/docs/contributing/artefact/git/pipeline.md @@ -32,7 +32,7 @@ The orchestrator runs the following stages in order: ### 1. Fork Prerequisites ⏳ -For fork PRs, CI waits for privileged images built by the `pull_request_target` event before proceeding. For an untrusted fork that build runs from the safe base merge ref **without organization secrets** (only the per-job `GITHUB_TOKEN`); a maintainer-applied `🛡️ Trusted` label switches the build source to the PR head, unlocks the mirror credentials, and skips the wait — see [Trusted fork PRs](#trusted-fork-prs-). +For fork PRs, CI waits for privileged images built by the `pull_request_target` event before proceeding. That build and the mirror producer run only for a fork PR that carries the maintainer-applied `🛡️ Trusted` label; for an untrusted fork the `🛡️ Gate fork trust` job fails instead, and the waiting `pull_request` run fails fast with it. The label also switches the build source to the PR head and skips the wait — see [Trusted fork PRs](#trusted-fork-prs-). ### 2. Security 🛡️ @@ -62,7 +62,7 @@ The `code-quality-gate` requires linting, code tests, and security checks to all [call-images-mirror-missing.yml](../../../../.github/workflows/call-images-mirror-missing.yml) mirrors any missing upstream images in parallel with the DNS tests so later deploy jobs pull from GHCR instead of Docker Hub, MCR, or other external registries. This shields CI from upstream rate limits, geo-blocking, and transient registry outages. -Fork PRs cannot publish mirror packages directly, so their runs wait for the `pull_request_target` mirror producer before continuing. The producer mirrors with the Docker Hub credentials only for trusted PRs ([🛡️ Trusted](#trusted-fork-prs-)); untrusted forks mirror anonymously (no organization secrets). See [mirror.md](../image/mirror.md) for the mirroring architecture and naming convention. +Fork PRs cannot publish mirror packages directly, so their runs wait for the `pull_request_target` mirror producer before continuing. The producer runs only for trusted PRs ([🛡️ Trusted](#trusted-fork-prs-)) and is the only fork-facing job that receives the Docker Hub credentials. It checks the fork tree out with `core.symlinks=false` and refuses any symlink left in it, so the scan reads the tree's own files and nothing outside it. See [mirror.md](../image/mirror.md) for the mirroring architecture and naming convention. GHCR publication uses the workflow `GITHUB_TOKEN`; optional Docker Hub secrets are used only to reduce source-side Docker Hub rate limits while mirroring. See [authentication.md](../../tools/ghcr/authentication.md). @@ -139,7 +139,7 @@ See [configuration.md](../../tools/github/actions/configuration.md) for all repo Fork PRs run under the `pull_request` event without write permissions. Privileged steps (image builds, package writes) run via `pull_request_target`. The fork CI waits for those privileged images before proceeding. See [pull-request.md](pull-request.md) for the contributor-facing fork workflow. -By default — for an **untrusted** fork PR — the privileged `pull_request_target` build checks out the **base merge ref** (`refs/pull//merge`) from the base repository: the PR's changes merged onto base, with all workflow and build-orchestration scripts coming from base, never from the fork. Because `actions/checkout` otherwise refuses to fetch a PR ref under `pull_request_target`, the source checkout sets `allow-unsafe-pr-checkout: true`. The untrusted build runs **without organization secrets** — `secrets: inherit` is not passed and it authenticates to GHCR with the per-job `GITHUB_TOKEN` only, so a malicious fork cannot read repository/organization secrets. (The `pull_request_target` token still carries `packages: write`, so the `🛡️ Trusted` label remains the real trust boundary for anything beyond image publication.) +For an **untrusted** fork PR the privileged `pull_request_target` jobs stop at the `🛡️ Gate fork trust` job: it fails, so neither the image build nor the mirror producer runs fork content next to the `packages: write` token, and the fork's `pull_request` run fails its prerequisite wait as soon as that run ends. The merge-ref expressions in `build-ci-images-fork` stay as a fallback only. Because `actions/checkout` otherwise refuses to fetch a PR ref under `pull_request_target`, the source checkouts set `allow-unsafe-pr-checkout: true`; the lint `tests/lint/repository/test_workflow_fork_checkout_gated.py` fails any `pull_request_target` job with such a checkout that does not need the gate. ### Trusted fork PRs 🔓 @@ -147,12 +147,13 @@ When a maintainer applies the `🛡️ Trusted` label, the fork PR is treated as - The orchestrator's `wait-fork-prereq-run` job **skips the wait** for the privileged fork images. - The privileged `pull_request_target` build switches its **build source** from the base merge ref to the **raw PR head** (`head.repo.full_name` @ `head.sha`). -- The trusted build additionally receives the Docker Hub mirror credentials (passed only when the label is present); untrusted builds mirror anonymously. +- The trusted mirror producer receives the Docker Hub mirror credentials; untrusted fork PRs get no privileged job at all. +- A fork-sourced build imports the shared `buildcache-` registry cache but never exports to it, so only base-sourced builds write the cache every trusted build reads. - The built image **keeps the merge-SHA tag** (`ci-`) so the `pull_request` orchestrator finds it unchanged — no consumer workflow has to know about the label. Security gates: -- The `🛡️ Trusted` label flips the build source to the PR head and unlocks the Docker Hub credentials; without it the safe base merge ref is built with no organization secrets. Restrict who may set the label via repository label permissions / branch protection so only maintainers can grant it. +- The `🛡️ Trusted` label is the only way a fork PR reaches the privileged build and mirror. Restrict who may set the label via repository label permissions / branch protection so only maintainers can grant it. The label stays on the PR across later pushes, so review every new head before CI uses it, or remove the label first. - Build-orchestration scripts (`scripts/image/push.sh` and the helper checkout) always come from the base repo at `github.sha`; only the Docker build **context** (`_src`) is the fork head. `persist-credentials: false` keeps the token out of the source checkout, and `USE_NIX_TOKEN` stays disabled for fork-sourced builds. - Fork `pull_request` runs always receive a read-only token (GitHub-enforced); the label never grants write tokens or secrets to the untrusted event. diff --git a/scripts/github/gate/no_symlinks.sh b/scripts/github/gate/no_symlinks.sh new file mode 100755 index 0000000000..738e0aa091 --- /dev/null +++ b/scripts/github/gate/no_symlinks.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# +# Usage: no_symlinks.sh +# a directory checked out from an untrusted ref; the script fails +# when it holds a symlink, which would let a later read leave it. + +set -euo pipefail + +tree="${1:?Usage: no_symlinks.sh }" + +mapfile -t links < <(find "${tree}" -type l -print) + +if ((${#links[@]} > 0)); then + echo "Refusing ${tree}: ${#links[@]} symlink(s) survived core.symlinks=false." >&2 + printf ' - %q\n' "${links[@]:0:20}" >&2 + exit 1 +fi +echo "No symlinks under ${tree}." diff --git a/scripts/github/gate/trusted_label.sh b/scripts/github/gate/trusted_label.sh new file mode 100755 index 0000000000..642025c24b --- /dev/null +++ b/scripts/github/gate/trusted_label.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# +# Inputs via env: +# TRUSTED "true" when the fork PR carries the maintainer '🛡️ Trusted' label. +# PR_NUMBER the pull request number, named in the refusal. + +set -euo pipefail + +: "${TRUSTED:?}" +: "${PR_NUMBER:?}" + +if [[ "${TRUSTED}" != "true" ]]; then + echo "Fork PR #${PR_NUMBER} is not labelled '🛡️ Trusted'. The privileged image build and mirror run fork content with a packages:write token, so they start only after a maintainer reviewed the head and applied the label." >&2 + exit 1 +fi +echo "Fork PR #${PR_NUMBER} carries '🛡️ Trusted'; the privileged image build and mirror may run." diff --git a/scripts/image/push.sh b/scripts/image/push.sh index 4bb1299b7d..f2e54aa88e 100755 --- a/scripts/image/push.sh +++ b/scripts/image/push.sh @@ -17,6 +17,7 @@ export INFINITO_PARENT_IMAGE : "${IMAGE_DIGEST_DIR:?Missing IMAGE_DIGEST_DIR}" : "${GITHUB_REPOSITORY:?Missing GITHUB_REPOSITORY}" : "${USE_NIX_TOKEN:?Missing USE_NIX_TOKEN}" +: "${EXPORT_BUILD_CACHE:?Missing EXPORT_BUILD_CACHE}" : "${INFINITO_PARENT_IMAGE:?Missing INFINITO_PARENT_IMAGE; source scripts/meta/env/load.sh}" : "${INFINITO_SRC_DIR:?Missing INFINITO_SRC_DIR; source scripts/meta/env/load.sh}" : "${INFINITO_VENV_DIR:?Missing INFINITO_VENV_DIR; source scripts/meta/env/load.sh}" @@ -39,6 +40,13 @@ else echo "pull_request_target on fork detected: skipping NIX_CONFIG token build-arg." fi +cache_to_arg=() +if [[ "${EXPORT_BUILD_CACHE}" == "true" ]]; then + cache_to_arg=(--cache-to "type=registry,mode=max,ref=${cache_ref}") +else + echo "Fork-sourced build: importing ${cache_ref} without exporting to it." +fi + while true; do echo "=== Build & push attempt ${attempt}/${max_attempts} ===" @@ -56,7 +64,7 @@ while true; do --build-arg "INFINITO_DOCKER_CLI_INSTALL_SCRIPT=${INFINITO_DOCKER_CLI_INSTALL_SCRIPT:?source scripts/meta/env/load.sh}" \ "${nix_arg[@]}" \ --cache-from "type=registry,ref=${cache_ref}" \ - --cache-to "type=registry,mode=max,ref=${cache_ref}" \ + "${cache_to_arg[@]}" \ "${BUILD_CONTEXT_DIR}"; then echo "Build & push succeeded on attempt ${attempt}/${max_attempts}." break diff --git a/tests/lint/repository/test_workflow_fork_checkout_gated.py b/tests/lint/repository/test_workflow_fork_checkout_gated.py new file mode 100644 index 0000000000..4b386cb56e --- /dev/null +++ b/tests/lint/repository/test_workflow_fork_checkout_gated.py @@ -0,0 +1,72 @@ +from __future__ import annotations + +import re +import unittest + +from utils.cache.yaml import load_yaml_any + +from . import PROJECT_ROOT + +_WORKFLOWS_DIR = PROJECT_ROOT / ".github" / "workflows" +_GATE_JOB = "fork-trust-gate" +_UNSAFE_CALL_INPUT = "allow_unsafe_checkout" +_UNSAFE_STEP_INPUT = "allow-unsafe-pr-checkout" +_GATE_BYPASS = re.compile(r"\b(?:always|cancelled|failure)\(\s*\)") + + +def _listens_to_pull_request_target(document) -> bool: + triggers = document.get("on") or document.get(True) or {} + if isinstance(triggers, str): + return triggers == "pull_request_target" + return "pull_request_target" in triggers + + +def _enabled(value) -> bool: + return value not in (None, False, "false") + + +def _checks_out_pull_request_code(job: dict) -> bool: + if _enabled((job.get("with") or {}).get(_UNSAFE_CALL_INPUT)): + return True + return any( + _enabled((step.get("with") or {}).get(_UNSAFE_STEP_INPUT)) + for step in job.get("steps") or [] + if isinstance(step, dict) + ) + + +def _needs(job: dict) -> list[str]: + needs = job.get("needs") or [] + return [needs] if isinstance(needs, str) else list(needs) + + +class TestWorkflowForkCheckoutGated(unittest.TestCase): + def test_pull_request_checkouts_under_pull_request_target_need_the_gate( + self, + ) -> None: + offenders: list[str] = [] + for path in sorted(_WORKFLOWS_DIR.glob("*.y*ml")): + document = load_yaml_any(str(path), default_if_missing={}) or {} + if not _listens_to_pull_request_target(document): + continue + for job_id, job in (document.get("jobs") or {}).items(): + if not isinstance(job, dict) or not _checks_out_pull_request_code(job): + continue + if _GATE_JOB not in _needs(job): + offenders.append(f"{path.name}: {job_id}: does not need it") + elif _GATE_BYPASS.search(str(job.get("if", ""))): + offenders.append(f"{path.name}: {job_id}: runs past a failed gate") + + if offenders: + self.fail( + f"{len(offenders)} pull_request_target job(s) check out pull " + f"request code without depending on a green '{_GATE_JOB}'. Such " + "a job runs fork content next to a write-scoped token, so it " + "must wait for the gate that refuses fork PRs lacking the " + "maintainer '🛡️ Trusted' label, and its if: must not use " + "always(), cancelled() or failure().\n" + "\n".join(offenders) + ) + + +if __name__ == "__main__": + unittest.main()