From 7630a0de3c4fe0d2606b27c68bd98aa9a180b47d Mon Sep 17 00:00:00 2001 From: Colin Walters Date: Wed, 30 Sep 2026 16:07:26 -0400 Subject: [PATCH] ci: Check the lock files from the default branch's code ci's stale-lock and shape checks run from the pull request's own tree, so a pull request can change the compiler, lib/ or ci.yml until a lock file that doesn't match its source passes (#26). trusted-check runs the same checks on pull_request_target, so its file and every script it runs are the default branch's, with contents: read and no secrets. The pull request's tree is only data: the default branch's wfc, built from its checkout alone, writes its blobs as committed with the new `wfc extract-tree` (git archive would apply its .gitattributes), refusing symlinks and submodules, and nothing there is executed or built. That wfc then runs `wfc check` on it: the lock files must match their sources and have the compiled shape. Evaluating the pull request's nickel can still read any file the job can, which holds no secrets; confining that step is #57. A pull request that changes the compiler itself passes only on the event of a maintainer applying the `compiler-change` label, by a human maintainer other than its author, and a push after the label fails again until it is reapplied. GitHub runs pull_request_target only from the default branch, so this can't run until merged; its steps were replayed on a devspace instead. It holds once trusted-check is a required check in the branch ruleset, which takes an administrator. docs/requirements.md has the trust model as R14. Fixes #26. Generated-by: AI --- .github/uncompiled-workflows | 1 + .github/workflows/trusted-check.yml | 129 +++++++++++ Cargo.lock | 324 +++++++++++++++++++++++++++- Cargo.toml | 2 + README.md | 11 +- docs/requirements.md | 83 +++++-- src/extract.rs | 90 ++++++++ src/lib.rs | 1 + src/main.rs | 20 +- tests/extract.rs | 105 +++++++++ 10 files changed, 747 insertions(+), 19 deletions(-) create mode 100644 .github/workflows/trusted-check.yml create mode 100644 src/extract.rs create mode 100644 tests/extract.rs diff --git a/.github/uncompiled-workflows b/.github/uncompiled-workflows index 3b55290..3a75e7a 100644 --- a/.github/uncompiled-workflows +++ b/.github/uncompiled-workflows @@ -2,3 +2,4 @@ # checked by `wfc check`. Each runs with none of the compiler's # guarantees, so each needs its reason here. ci.yml # this repository's own checks; runs no untrusted code with credentials (contents: read, no secrets), and calls the compiled workflows +trusted-check.yml # the check of the lock files from the base branch (#26); reads the pull request only as data, with contents: read diff --git a/.github/workflows/trusted-check.yml b/.github/workflows/trusted-check.yml new file mode 100644 index 0000000..15a97e1 --- /dev/null +++ b/.github/workflows/trusted-check.yml @@ -0,0 +1,129 @@ +# The stale-lock and shape checks, run from code the pull request can't +# change (#26). ci.yml runs them too, but from the pull request's own +# tree, where a change to the compiler, lib/ or ci.yml can make them pass +# whatever the lock files say. +# +# This runs on pull_request_target, so the workflow and every script it +# runs are the default branch's: GitHub takes the workflow from there +# whatever the pull request's base, and checks out that branch's head. The +# pull request's tree is only data: the default branch's wfc, built from +# its checkout alone, writes its blobs into head/ exactly as committed (no +# .gitattributes applied), and then checks head/. Nothing of the pull +# request is executed or built, but evaluating its nickel can read any +# file this job can (#57). +# +# A pull request that changes the compiler relative to the default branch +# (lib/, runtime/, src/, the crate's manifests and build configuration, +# actions.lock.json, .gitattributes, the uncompiled-workflows list, or a +# workflow that isn't a lock file) passes only on the event of a maintainer, other than its +# author, applying the `compiler-change` label after reviewing it. Any +# other event checks it again and fails, so a push after the label needs +# it applied anew. docs/requirements.md (R14) has the trust model. +name: trusted-check + +on: + pull_request_target: + types: [opened, synchronize, reopened, labeled, unlabeled] + +permissions: + contents: read + +concurrency: + group: trusted-check-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + trusted-check: + runs-on: ubuntu-latest + timeout-minutes: 20 + env: + # Paths whose change is a change of the compiler, reviewed by hand. + COMPILER_PATHS: lib runtime src build.rs Cargo.toml Cargo.lock rust-toolchain.toml rust-toolchain .cargo actions.lock.json .gitattributes .github/uncompiled-workflows + LABEL: compiler-change + # Who may vouch for a change of the compiler. + APPROVER_ROLES: admin maintain + steps: + - name: Check out the default branch + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + path: base + fetch-depth: 0 + persist-credentials: false + + # By number, from this repository, so a fork's needs no access of + # its own. + - name: Fetch the pull request's head + env: + PR: ${{ github.event.pull_request.number }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + SERVER: ${{ github.server_url }} + REPO: ${{ github.repository }} + run: | + set -euo pipefail + git -C base fetch -q --no-tags "$SERVER/$REPO" "+refs/pull/$PR/head:refs/remotes/pr/head" + test "$(git -C base rev-parse refs/remotes/pr/head)" = "$HEAD_SHA" + + - name: Build wfc from the default branch + working-directory: base + run: cargo build --release --locked + + - name: Extract its tree as data + env: + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + run: base/target/release/wfc extract-tree base "$HEAD_SHA" head + + - name: Changes to the compiler need a maintainer's fresh label + env: + ACTION: ${{ github.event.action }} + EVENT_LABEL: ${{ github.event.label.name }} + SENDER: ${{ github.event.sender.login }} + AUTHOR: ${{ github.event.pull_request.user.login }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + REPO: ${{ github.repository }} + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + # Against the default branch's tip, which is what runs here, so + # that changes on a stacked pull request's base branch count too. + # Two trees, not the merge-base: a pull request on an older base + # would otherwise check its lock files with that base's compiler. + read -ra paths <<<"$COMPILER_PATHS" + # Captured first, so a failing diff (a missing commit, say) + # fails the step rather than looking like no change. + diff=$(git -C base diff --name-only HEAD "$HEAD_SHA" -- "${paths[@]}" \ + ':(glob).github/workflows/*' ':(exclude,glob).github/workflows/*.lock.yml') + mapfile -t changed <<<"$diff" + [ -n "$diff" ] || changed=() + if [ "${#changed[@]}" -eq 0 ]; then + echo "The compiler is unchanged from the default branch." + exit 0 + fi + echo "This pull request changes the compiler:" + printf ' %s\n' "${changed[@]}" + # Only the labeling itself counts: a label applied before the + # last push doesn't vouch for what was pushed after it. + if [ "$ACTION" != labeled ] || [ "$EVENT_LABEL" != "$LABEL" ]; then + echo "::error::the compiler changed; a maintainer other than its author must review it and then (re)apply the $LABEL label, after the last push" + exit 1 + fi + # Bots can't vouch for a review: cgwalters-bot has admin here. + if [ "$SENDER" = cgwalters-bot ] || [[ "$SENDER" == *"[bot]" ]]; then + echo "::error::$SENDER is a bot; a human maintainer must review the compiler change" + exit 1 + fi + if [ "$SENDER" = "$AUTHOR" ]; then + echo "::error::$SENDER labeled their own pull request; another maintainer must review the compiler change" + exit 1 + fi + role=$(gh api "repos/$REPO/collaborators/$SENDER/permission" --jq .role_name) + read -ra roles <<<"$APPROVER_ROLES" + if [[ " ${roles[*]} " != *" $role "* ]]; then + echo "::error::$SENDER has the $role role; the $LABEL label counts only from ${APPROVER_ROLES// / or }" + exit 1 + fi + echo "$SENDER ($role) labeled it $LABEL at this head." + + # The pull request's uncompiled-workflows list: past the gate, it is + # the default branch's own or a change a maintainer approved. + - name: Lock files match their sources and have the compiled shape, by the default branch's wfc + run: base/target/release/wfc check --root head diff --git a/Cargo.lock b/Cargo.lock index 8703a8d..fef560e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -23,6 +23,12 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "250f629c0161ad8107cf89319e990051fae62832fd343083bea452d93e2205fd" +[[package]] +name = "ambient-authority" +version = "0.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9d4ee0d472d1cd2e28c97dfa124b3d8d992e10eb0a035f33f5d12e3a177ba3b" + [[package]] name = "anstream" version = "1.0.0" @@ -175,6 +181,62 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "cap-primitives" +version = "4.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b5f74729fd2f44701d1a8eb47e906cdb3ccd9ec0f02baad85a744b791940b18" +dependencies = [ + "ambient-authority", + "fs-set-times", + "io-extras", + "io-lifetimes 3.0.1", + "ipnet", + "maybe-owned", + "rustix", + "rustix-linux-procfs", + "windows-sys 0.61.2", + "winx", +] + +[[package]] +name = "cap-std" +version = "4.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1ec78e242cfa2cfe276807ac2ecc00315a6c97786977414bcd1c3963b6c91b8" +dependencies = [ + "cap-primitives", + "io-extras", + "io-lifetimes 3.0.1", + "rustix", +] + +[[package]] +name = "cap-std-ext" +version = "5.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c6c5ac70c4465b47c3a322330f87c2df31e42ac527497d94dc1f1d1cb8989f9" +dependencies = [ + "cap-primitives", + "cap-tempfile", + "libc", + "rustix", +] + +[[package]] +name = "cap-tempfile" +version = "4.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "038b3f6a5d4b5641b1bb99d638eb7a22013de84f81c528d8930de06d7383fbd5" +dependencies = [ + "cap-std", + "rand", + "rustix", + "rustix-linux-procfs", + "uuid", + "windows-sys 0.61.2", +] + [[package]] name = "cc" version = "1.5.1" @@ -409,6 +471,41 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" +[[package]] +name = "fs-set-times" +version = "0.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a" +dependencies = [ + "io-lifetimes 2.0.4", + "rustix", + "windows-sys 0.52.0", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + [[package]] name = "generic-array" version = "0.14.7" @@ -430,6 +527,18 @@ dependencies = [ "wasi", ] +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + [[package]] name = "getrandom" version = "0.4.3" @@ -438,7 +547,7 @@ checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", "libc", - "r-efi", + "r-efi 6.0.0", ] [[package]] @@ -541,6 +650,34 @@ dependencies = [ "rustversion", ] +[[package]] +name = "io-extras" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f" +dependencies = [ + "io-lifetimes 3.0.1", + "windows-sys 0.52.0", +] + +[[package]] +name = "io-lifetimes" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06432fb54d3be7964ecd3649233cddf80db2832f47fec34c01f65b3d9d774983" + +[[package]] +name = "io-lifetimes" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f0fb0570afe1fed943c5c3d4102d5358592d8625fda6a0007fdbe65a92fba96" + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + [[package]] name = "is_terminal_polyfill" version = "1.70.2" @@ -562,6 +699,17 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + [[package]] name = "json_scanner" version = "0.1.0" @@ -739,6 +887,12 @@ dependencies = [ "serde", ] +[[package]] +name = "maybe-owned" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4" + [[package]] name = "md-5" version = "0.11.0" @@ -940,6 +1094,21 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315" +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + [[package]] name = "precomputed-hash" version = "0.1.1" @@ -988,12 +1157,47 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + [[package]] name = "r-efi" version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + [[package]] name = "redox_syscall" version = "0.5.18" @@ -1059,6 +1263,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustix-linux-procfs" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fc84bf7e9aa16c4f2c758f27412dc9841341e16aa682d9c7ac308fe3ee12056" +dependencies = [ + "once_cell", + "rustix", +] + [[package]] name = "rustls" version = "0.23.45" @@ -1261,6 +1475,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + [[package]] name = "smallvec" version = "1.16.2" @@ -1500,6 +1720,17 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "uuid" +version = "1.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "wasm-bindgen", +] + [[package]] name = "version_check" version = "0.9.5" @@ -1531,6 +1762,60 @@ version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.6", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + [[package]] name = "webpki-roots" version = "1.0.9" @@ -1656,11 +1941,28 @@ dependencies = [ "memchr", ] +[[package]] +name = "winx" +version = "0.36.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d" +dependencies = [ + "bitflags", + "windows-sys 0.52.0", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + [[package]] name = "workflow-compiler" version = "0.1.0" dependencies = [ "anyhow", + "cap-std-ext", "clap", "nickel-lang-core", "regex", @@ -1677,6 +1979,26 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" +[[package]] +name = "zerocopy" +version = "0.8.59" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6df92bf3d9227be3d53173901ddbffac2babc27ae50f397776ffd6dc33f800cb" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.59" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac4f328cf2f05d084e496c3e9c3f33ed0a183656a16e1fcec4d464d8373aec82" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "zeroize" version = "1.9.0" diff --git a/Cargo.toml b/Cargo.toml index 63c2b8a..7bf7fff 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,8 @@ path = "src/main.rs" [dependencies] anyhow = "1" +# extract-tree writes a pull request's tree through a directory fd. +cap-std-ext = "5" clap = { version = "4", features = ["derive"] } # Outside nickel's 1.0 stability promise, so pinned exactly; bump it # deliberately and regenerate the lock files. 0.19.0 is the core of diff --git a/README.md b/README.md index c6eda08..6529520 100644 --- a/README.md +++ b/README.md @@ -219,10 +219,16 @@ cargo test # wfc's own tests, and `check` of this repository must have a source and the compiled shape (`src/shape.rs`: the generated enter and seal steps, byte for byte, and nothing between them that leaves the wrapper), and anything else must be listed, with its reason, -in `.github/uncompiled-workflows`. +in `.github/uncompiled-workflows`. `trusted-check.yml` runs the same +checks on every pull request with the base branch's code, the pull +request's tree only as data, and needs a maintainer's `compiler-change` +label on pull requests that change the compiler itself (R14). `compile` also fetches new actions' metadata from GitHub; `check` never -uses the network. +uses the network. `trusted-check` compiles a pull request's sources (R14 +in [docs/requirements.md](docs/requirements.md)), and nickel resolves +their imports against any path the job can read; confining that step is +[#57](https://github.com/cgwalters-forge/workflow-compiler/issues/57). `nickel-lang-core` is outside nickel's 1.0 stability promise, so `Cargo.toml` pins it exactly; a bump can change the lock files, so it @@ -272,7 +278,6 @@ the task compiler that will produce this compiler's input): - [#19](https://github.com/cgwalters-forge/workflow-compiler/issues/19) `runner_steps` that execute a pull request's checkout (P1) - [#20](https://github.com/cgwalters-forge/workflow-compiler/issues/20) caches saved from sandbox output and restored in `runner_steps` (P1) - [#25](https://github.com/cgwalters-forge/workflow-compiler/issues/25) expressions from issues, comments and pull requests in privileged `run:` steps (P1) -- [#26](https://github.com/cgwalters-forge/workflow-compiler/issues/26) the stale-lock check runs the pull request's own compiler (P1) - [#27](https://github.com/cgwalters-forge/workflow-compiler/issues/27) local sockets and localhost services reachable from the sandbox (P1) - [#14](https://github.com/cgwalters-forge/workflow-compiler/issues/14) prompts from a trusted ref for PR-triggered agents (P2) - [#2](https://github.com/cgwalters-forge/workflow-compiler/issues/2) post-steps of `runner_steps` actions (P2) diff --git a/docs/requirements.md b/docs/requirements.md index f891f0b..cdadf1f 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -104,12 +104,12 @@ else. The lock file in `.github/workflows/` is a deterministic function of the reviewed source and of this repository's contracts and runtime scripts, which the lock file embeds; the stale-lock check fails `ci` on any difference. So reviewing the source is reviewing the job, and the source's -schema has no way to say "run this later step as runner". The check itself -runs from the pull request's own `ci.yml`, compiler (`src/`), `lib/` and -`runtime/`, so those files are inside -the boundary too: a pull request that changes them can make a stale lock -file pass, and they need the same review as the lock files -([#26](https://github.com/cgwalters-forge/workflow-compiler/issues/26)). +schema has no way to say "run this later step as runner". `ci` runs the +check from the pull request's own tree, where a change to `ci.yml`, +the compiler's `src/` or `lib/` could make a stale lock file pass; so the same +checks also run from the base branch's code, in `trusted-check`, with the +pull request only as data, and a change to the compiler itself needs a +maintainer's fresh label (R14). The **uid boundary** is between the runner user and the sandbox user (`runner-sandbox`). It is the one that holds at run time against hostile @@ -216,9 +216,8 @@ and jobs and workflows have only the keys gha.ncl's contracts let through, so a key GitHub adds later is refused until the compiler knows it. Any other file in `.github/workflows/` must be listed, with its reason, in `.github/uncompiled-workflows` (here, `ci.yml`), and every lock file needs -a source. This proves the repository's own tree; that the tree `ci` runs -the check from is trustworthy is -[#26](https://github.com/cgwalters-forge/workflow-compiler/issues/26). +a source. `trusted-check` runs this from the base branch's code too +(R14). **Proof:** the reject tests in `tests/reject/` (`shell-override`, `working-directory`, `job-container`, `job-defaults`, and the others), @@ -492,10 +491,9 @@ there, the pull request's code may only be checked out and run inside the sandbox ([#19](https://github.com/cgwalters-forge/workflow-compiler/issues/19)), and event text may only reach privileged steps as data (R12). -**The repository requires `ci`**, including the stale-lock check, before -anything merges, and its maintainers review changes to `ci.yml`, -the compiler (`src/`), `lib/` and `runtime/` like lock files -([#26](https://github.com/cgwalters-forge/workflow-compiler/issues/26)). +**The repository requires `ci` and `trusted-check`** before anything +merges (R14), and its maintainers review changes to the compiler like +lock files, which the `compiler-change` label records. **The privileged phase doesn't run code from an untrusted checkout.** `runner_steps` run as runner with sudo: a `run: make deps` there, on a @@ -579,6 +577,63 @@ holds only for one that does. **Status:** not enforced ([#20](https://github.com/cgwalters-forge/workflow-compiler/issues/20)). +### R14. The lock files are checked by code the pull request can't change + +`ci` checks a pull request with the pull request's own `ci.yml`, +compiler (`src/`), `lib/` and `runtime/`, which the pull request can change +so that a lock file that doesn't match its source, or doesn't have the +compiled shape, passes. So `trusted-check` runs the same checks with the +default branch's code. It is a `pull_request_target` workflow, so its +file and everything it runs come from the default branch (GitHub always +takes that workflow from the default branch, whatever the pull request's +base), with only `contents: read` and no secrets. The pull request's tree +is data: the default branch's `wfc`, built from its checkout alone, +writes each of its blobs as committed (`wfc extract-tree`), ignoring its +`.gitattributes` (which `git archive` would apply, dropping or rewriting +files), and refuses symlinks, submodules and `..` paths; nothing there is +executed or built. That `wfc` then compiles the pull request's sources, +compares the lock files and checks their shape (R1), including what the +compiler's lints refuse in publish and sandboxed steps. + +It still compiles with the pull request's `lib/` and checks against its +`runtime/`, `actions.lock.json` and uncompiled-workflows list: those are +the compiler, and a pull request may change them. So any change to them, +to `src/`, the crate's manifests and build configuration (`build.rs`, +`.cargo/`, the toolchain file), `.gitattributes` or a workflow that +isn't a lock file, compared with the default branch (so a stacked pull request's base +branch doesn't hide one), passes only on the event of a maintainer +applying the `compiler-change` label: a human other than the pull +request's author (`cgwalters-bot`, which has admin here, and any `[bot]` +account are refused), with the admin or maintain role, which the check +looks up. Every other event checks again and fails, so a push after the label +needs it applied anew; that includes labeling with another label, since +a passing check on an unrelated event would stand for the head it ran +on. + +**Status:** holds once these ruleset settings are in place, which only an +administrator can make: `trusted-check` a required status check, pinned +to the GitHub Actions app, with branches required to be up to date before +merging, so what passed is what merges. Evaluating the pull request's +nickel is still running its code, bounded by the job's timeout, in an +interpreter whose only I/O is reading files: an `import` can name any +file the job's user can read, and what it reads can show in the job's +public log. The job has no secrets and checks out without persisting +credentials, and confining the step to the extracted tree is +[#57](https://github.com/cgwalters-forge/workflow-compiler/issues/57). + +**Proof:** since GitHub runs `pull_request_target` workflows only from +the default branch, the workflow can't run before it is merged. Its steps +were replayed on a devspace against test branches, as the event would run +them: an honest change to a source passes; a hand-edited lock file fails +at the compare; a change to the compiler fails at the label gate on a +push, on another label, and when its author or a bot labels it, and +passes on a maintainer's `compiler-change` labeling; a head with no +history in common with the default branch fails at the gate rather than +passing as unchanged. +`tests/extract.rs` checks that `export-ignore`, +`export-subst` and `ident` don't change what is extracted, and that a +symlink is refused. Once merged, the same pull requests are the test. + ## Non-goals **A kernel boundary.** The sandbox is a different uid on the same kernel, @@ -665,7 +720,7 @@ the roadmap in the [README](../README.md#status-and-roadmap): - [#21](https://github.com/cgwalters-forge/workflow-compiler/issues/21): nothing checks the repository settings (R10); - [#22](https://github.com/cgwalters-forge/workflow-compiler/issues/22): unrestricted network egress ([Non-goals](#non-goals)); - [#25](https://github.com/cgwalters-forge/workflow-compiler/issues/25): expressions from events in privileged `run:` steps (R12) (fixed); -- [#26](https://github.com/cgwalters-forge/workflow-compiler/issues/26): the stale-lock check runs the pull request's own compiler (review boundary, R10); +- [#26](https://github.com/cgwalters-forge/workflow-compiler/issues/26): the stale-lock check runs the pull request's own compiler (review boundary, R10) (fixed, R14); - [#27](https://github.com/cgwalters-forge/workflow-compiler/issues/27): local sockets and localhost services (R2, R3); - [#28](https://github.com/cgwalters-forge/workflow-compiler/issues/28): the ephemeral-runner assumption (R5, R10); - [#29](https://github.com/cgwalters-forge/workflow-compiler/issues/29): explicit token permissions (R10); diff --git a/src/extract.rs b/src/extract.rs new file mode 100644 index 0000000..6d28e8f --- /dev/null +++ b/src/extract.rs @@ -0,0 +1,90 @@ +//! Writing the tree of a commit into a directory as plain files, for +//! trusted-check to read as data: every blob exactly as committed. +//! `git archive` isn't used, since it applies the tree's own +//! .gitattributes (export-ignore drops files, export-subst and ident +//! rewrite them). Only regular files are written; a symlink or submodule +//! in the tree, or a path with `.` or `..` components, is refused, and +//! every file is written through a directory fd for `dest`. + +use std::ffi::OsStr; +use std::io::Write as _; +use std::os::unix::ffi::OsStrExt as _; +use std::path::Path; +use std::process::Command; + +use anyhow::{Context, Result, bail}; +use cap_std_ext::cap_std::ambient_authority; +use cap_std_ext::cap_std::fs::{Dir, OpenOptions, OpenOptionsExt as _}; + +fn git(git_dir: &Path, args: &[&str]) -> Result> { + let out = Command::new("git") + .arg("-C") + .arg(git_dir) + .args(args) + .output() + .context("running git")?; + if !out.status.success() { + bail!( + "git {}: {}", + args.join(" "), + String::from_utf8_lossy(&out.stderr).trim() + ); + } + Ok(out.stdout) +} + +/// Writes the tree of `commit` in the repository at `git_dir` under +/// `dest`, which must not exist. Returns the number of files written. +pub fn extract_tree(git_dir: &Path, commit: &str, dest: &Path) -> Result { + let listing = git(git_dir, &["ls-tree", "-r", "-z", "--full-tree", commit])?; + std::fs::create_dir(dest).with_context(|| format!("creating {}", dest.display()))?; + let dir = Dir::open_ambient_dir(dest, ambient_authority()) + .with_context(|| format!("opening {}", dest.display()))?; + let mut count = 0; + for entry in listing.split(|&b| b == 0).filter(|e| !e.is_empty()) { + let tab = entry + .iter() + .position(|&b| b == b'\t') + .context("parsing git ls-tree")?; + let meta = std::str::from_utf8(&entry[..tab]).context("parsing git ls-tree")?; + let rel = Path::new(OsStr::from_bytes(&entry[tab + 1..])); + let [mode, kind, oid] = meta.split(' ').collect::>()[..] else { + bail!("parsing git ls-tree: {meta}"); + }; + let mode = match (mode, kind) { + ("100644", "blob") => 0o644, + ("100755", "blob") => 0o755, + ("120000", _) => bail!("{} is a symlink; refusing to read the tree", rel.display()), + ("160000", _) => bail!( + "{} is a submodule; refusing to read the tree", + rel.display() + ), + _ => bail!( + "{} is a mode {mode} entry; refusing to read the tree", + rel.display() + ), + }; + // Bytewise: Path::components would skip a `.` inside the path. + if rel + .as_os_str() + .as_bytes() + .split(|&b| b == b'/') + .any(|c| matches!(c, b"" | b"." | b"..")) + { + bail!("refusing the path {:?}", rel); + } + if let Some(parent) = rel.parent().filter(|p| !p.as_os_str().is_empty()) { + dir.create_dir_all(parent) + .with_context(|| format!("creating {}", parent.display()))?; + } + let blob = git(git_dir, &["cat-file", "blob", oid])?; + dir.open_with( + rel, + OpenOptions::new().write(true).create_new(true).mode(mode), + ) + .and_then(|mut f| f.write_all(&blob)) + .with_context(|| format!("writing {}", rel.display()))?; + count += 1; + } + Ok(count) +} diff --git a/src/lib.rs b/src/lib.rs index 9668585..107cd33 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,6 +4,7 @@ //! `.github/workflows/`. pub mod actions; +pub mod extract; pub mod nickel; pub mod repo; pub mod shape; diff --git a/src/main.rs b/src/main.rs index 44a3da9..95d8ec8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,7 +5,7 @@ use std::process::ExitCode; use anyhow::Result; use clap::{Args, Parser, Subcommand}; -use workflow_compiler::{Mode, run}; +use workflow_compiler::{Mode, extract, run}; #[derive(Parser)] #[command( @@ -29,6 +29,15 @@ enum Command { /// .github/workflows/ is neither a lock file with the compiled shape /// nor listed in .github/uncompiled-workflows. Check(Repo), + /// Write the tree of COMMIT into DEST, which must not exist, as plain + /// files: every blob exactly as committed, ignoring .gitattributes. + /// Symlinks, submodules and `.` or `..` paths are refused. + ExtractTree { + /// A directory in the repository. + git_dir: PathBuf, + commit: String, + dest: PathBuf, + }, } #[derive(Args)] @@ -42,6 +51,15 @@ fn main_inner() -> Result { let (repo, mode) = match Cli::parse().command { Command::Compile(repo) => (repo, Mode::Compile), Command::Check(repo) => (repo, Mode::Check), + Command::ExtractTree { + git_dir, + commit, + dest, + } => { + let n = extract::extract_tree(&git_dir, &commit, &dest)?; + eprintln!("extracted {n} files of {commit}"); + return Ok(true); + } }; let problems = run(&repo.root, mode)?; for p in &problems { diff --git a/tests/extract.rs b/tests/extract.rs new file mode 100644 index 0000000..06a8f4f --- /dev/null +++ b/tests/extract.rs @@ -0,0 +1,105 @@ +//! Tests for `wfc extract-tree`: every blob as committed, nothing else. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +use workflow_compiler::extract::extract_tree; + +fn git(dir: &Path, args: &[&str]) { + let status = Command::new("git") + .arg("-C") + .arg(dir) + .args(args) + .status() + .unwrap(); + assert!(status.success(), "git {args:?}"); +} + +/// A repository in a new temporary directory with `files` committed, +/// after `extra` changed its work tree and index; and where to extract it. +fn repo( + files: &[(&str, &str)], + extra: impl FnOnce(&Path), +) -> (tempfile::TempDir, PathBuf, PathBuf) { + let dir = tempfile::tempdir().unwrap(); + let r = dir.path().join("r"); + std::fs::create_dir(&r).unwrap(); + git(&r, &["init", "-q"]); + for (rel, text) in files { + let path = r.join(rel); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + } + git(&r, &["add", "-A"]); + extra(&r); + git( + &r, + &[ + "-c", + "user.name=t", + "-c", + "user.email=t@t", + "commit", + "-q", + "-m", + "t", + ], + ); + let dest = dir.path().join("out"); + (dir, r, dest) +} + +#[test] +fn writes_every_blob_as_committed_ignoring_gitattributes() { + let (_dir, r, dest) = repo( + &[ + ( + ".gitattributes", + "hidden.yml export-ignore\nsubst.txt export-subst\nident.txt ident\n", + ), + (".github/workflows/hidden.yml", "on: push\n"), + ("subst.txt", "$Format:%H$\n"), + ("ident.txt", "$Id$\n"), + ], + |_| {}, + ); + assert_eq!(extract_tree(&r, "HEAD", &dest).unwrap(), 4); + for (rel, want) in [ + (".github/workflows/hidden.yml", "on: push\n"), + ("subst.txt", "$Format:%H$\n"), + ("ident.txt", "$Id$\n"), + ] { + assert_eq!( + std::fs::read_to_string(dest.join(rel)).unwrap(), + want, + "{rel}" + ); + } +} + +#[test] +fn refuses_symlinks_and_submodules() { + let (_dir, r, dest) = repo(&[("a.txt", "a")], |r| { + std::os::unix::fs::symlink(".git", r.join("runtime")).unwrap(); + git(r, &["add", "runtime"]); + }); + let e = extract_tree(&r, "HEAD", &dest).unwrap_err(); + assert!(format!("{e:#}").contains("runtime is a symlink"), "{e:#}"); + + let sub = format!("160000,{},vendor/sub", "1".repeat(40)); + let (_dir, r, dest) = repo(&[("a.txt", "a")], |r| { + git(r, &["update-index", "--add", "--cacheinfo", &sub]); + }); + let e = extract_tree(&r, "HEAD", &dest).unwrap_err(); + assert!( + format!("{e:#}").contains("vendor/sub is a submodule"), + "{e:#}" + ); +} + +#[test] +fn refuses_an_existing_destination() { + let (_dir, r, dest) = repo(&[("a.txt", "a")], |_| {}); + std::fs::create_dir(&dest).unwrap(); + assert!(extract_tree(&r, "HEAD", &dest).is_err()); +}