diff --git a/.github/uncompiled-workflows b/.github/uncompiled-workflows new file mode 100644 index 0000000..3b55290 --- /dev/null +++ b/.github/uncompiled-workflows @@ -0,0 +1,4 @@ +# Workflows in .github/workflows/ that aren't compiled from workflows/, +# 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 diff --git a/.github/workflows/actions-test.lock.yml b/.github/workflows/actions-test.lock.yml index f712e53..50723c5 100644 --- a/.github/workflows/actions-test.lock.yml +++ b/.github/workflows/actions-test.lock.yml @@ -1091,6 +1091,7 @@ jobs: const runner = process.env.SUDO_USER; if (!runner || runner === "root") throw new Error("must be started with sudo by the runner user"); const user = CONFIG.user; + if (user === runner || user === "root") throw new Error(`the sandbox user can't be ${user}: it must be another user than the runner and root`); // A runner that ran a job before would hand this one the previous job's // sandbox and workspace: refuse it. (The user itself may come with the @@ -1103,6 +1104,10 @@ jobs: } const sandbox = passwd(user); const runnerHome = passwd(runner).home; + // Also by uid: another name for root or the runner is still them. + if (sandbox.uid === 0 || sandbox.uid === passwd(runner).uid) { + throw new Error(`the sandbox user ${user} has uid ${sandbox.uid}, root's or the runner's`); + } fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o755 }); // The sandbox works on its own copy of what the job hands it (the files git diff --git a/.github/workflows/agent-review.lock.yml b/.github/workflows/agent-review.lock.yml index 11fe4e8..76d5cab 100644 --- a/.github/workflows/agent-review.lock.yml +++ b/.github/workflows/agent-review.lock.yml @@ -1742,6 +1742,7 @@ jobs: const runner = process.env.SUDO_USER; if (!runner || runner === "root") throw new Error("must be started with sudo by the runner user"); const user = CONFIG.user; + if (user === runner || user === "root") throw new Error(`the sandbox user can't be ${user}: it must be another user than the runner and root`); // A runner that ran a job before would hand this one the previous job's // sandbox and workspace: refuse it. (The user itself may come with the @@ -1754,6 +1755,10 @@ jobs: } const sandbox = passwd(user); const runnerHome = passwd(runner).home; + // Also by uid: another name for root or the runner is still them. + if (sandbox.uid === 0 || sandbox.uid === passwd(runner).uid) { + throw new Error(`the sandbox user ${user} has uid ${sandbox.uid}, root's or the runner's`); + } fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o755 }); // The sandbox works on its own copy of what the job hands it (the files git diff --git a/.github/workflows/sandbox-test.lock.yml b/.github/workflows/sandbox-test.lock.yml index 099184f..18f6d7b 100644 --- a/.github/workflows/sandbox-test.lock.yml +++ b/.github/workflows/sandbox-test.lock.yml @@ -1482,6 +1482,7 @@ jobs: const runner = process.env.SUDO_USER; if (!runner || runner === "root") throw new Error("must be started with sudo by the runner user"); const user = CONFIG.user; + if (user === runner || user === "root") throw new Error(`the sandbox user can't be ${user}: it must be another user than the runner and root`); // A runner that ran a job before would hand this one the previous job's // sandbox and workspace: refuse it. (The user itself may come with the @@ -1494,6 +1495,10 @@ jobs: } const sandbox = passwd(user); const runnerHome = passwd(runner).home; + // Also by uid: another name for root or the runner is still them. + if (sandbox.uid === 0 || sandbox.uid === passwd(runner).uid) { + throw new Error(`the sandbox user ${user} has uid ${sandbox.uid}, root's or the runner's`); + } fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o755 }); // The sandbox works on its own copy of what the job hands it (the files git diff --git a/Cargo.lock b/Cargo.lock index f68f59b..8703a8d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -352,6 +352,22 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + [[package]] name = "find-msvc-tools" version = "0.1.14" @@ -414,6 +430,17 @@ dependencies = [ "wasi", ] +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + [[package]] name = "hashbrown" version = "0.15.5" @@ -596,6 +623,12 @@ version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + [[package]] name = "lock_api" version = "0.4.14" @@ -955,6 +988,12 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + [[package]] name = "redox_syscall" version = "0.5.18" @@ -1001,12 +1040,25 @@ checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" dependencies = [ "cc", "cfg-if", - "getrandom", + "getrandom 0.2.17", "libc", "untrusted", "windows-sys 0.52.0", ] +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + [[package]] name = "rustls" version = "0.23.45" @@ -1276,6 +1328,19 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + [[package]] name = "term" version = "1.2.1" @@ -1602,6 +1667,7 @@ dependencies = [ "serde", "serde_json", "sha2", + "tempfile", "ureq", ] diff --git a/Cargo.toml b/Cargo.toml index 9cbd557..63c2b8a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,6 +24,9 @@ sha2 = "0.11" # Fetches the action.yml of actions to lock; `check` never uses it. ureq = "3" +[dev-dependencies] +tempfile = "3" + # nickel's evaluator is slow unoptimized, and `cargo test` and # `cargo run -- compile` evaluate every source. [profile.dev.package."*"] diff --git a/README.md b/README.md index f8bf0d8..c6eda08 100644 --- a/README.md +++ b/README.md @@ -210,10 +210,17 @@ The compiler is `wfc`, a Rust program that embeds nickel ```sh cargo run -- compile # write .github/workflows/*.lock.yml -cargo run -- check # fail on a stale lock file or an accepted reject test +cargo run -- check # fail on a stale lock file, an accepted reject test, + # or a workflow that isn't compiled (see below) cargo test # wfc's own tests, and `check` of this repository ``` +`check` also checks every workflow in `.github/workflows/`: a lock file +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`. + `compile` also fetches new actions' metadata from GitHub; `check` never uses the network. @@ -261,7 +268,6 @@ the task compiler that will produce this compiler's input): - [#36](https://github.com/cgwalters-forge/workflow-compiler/issues/36) `agent_run` with real inference through praxis run tokens (P1) - [#4](https://github.com/cgwalters-forge/workflow-compiler/issues/4) agent-run as a compiler macro or a composite action (P1) - [#5](https://github.com/cgwalters-forge/workflow-compiler/issues/5) use `cgwalters-forge/actions/secure-host-setup` (P1) -- [#13](https://github.com/cgwalters-forge/workflow-compiler/issues/13) the stale-lock check doesn't prove every workflow is compiled (P1) - [#8](https://github.com/cgwalters-forge/workflow-compiler/issues/8) using the compiler from other repositories (P1) - [#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) diff --git a/docs/requirements.md b/docs/requirements.md index 69f8da8..f891f0b 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -198,16 +198,47 @@ a step's `shell:` or `working-directory`, a job's `container:`, `defaults` or `services`, workflow- or job-level `env:`, and a `uses:` in `steps` that the shim can't run. -**Status:** holds, with the gap below. +**Status:** holds. Besides matching each lock file to its source, `wfc +check` checks the output itself (`src/shape.rs`), so a +source that builds its own record instead of going through `gha.compile` +fails too. It requires exactly what the compiler emits rather than +refusing what it knows to be dangerous: every job has exactly one enter +step, byte for byte what `runtime/` makes it, with the configuration the +compiler writes (a sandbox user that is neither the runner nor root, the +workspace, a valid hand-off, the sudo lock whenever steps follow the +seal), after the generated secure-host step; every step up to the one +generated seal step runs through the step wrapper, has only the keys such +a step has and references no secret or token; every step after the seal +requires it to have succeeded and is held to what gha.ncl's `PublishStep` +refuses (unknown keys, unpinned actions, sandboxed steps' outputs in +`run`, `working-directory`, `with` or `env`, untrusted text in scripts); +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). **Proof:** the reject tests in `tests/reject/` (`shell-override`, -`working-directory`, `job-container`, `job-defaults`, and the others), which -`wfc check` requires to fail with their expected message, -`job-services`, `job-env` and `workflow-env` among them. Gap: -`wfc check` proves each lock file matches its source, not that every -workflow in `.github/workflows/` is a lock file or that a source went -through `gha.compile` unmodified -([#13](https://github.com/cgwalters-forge/workflow-compiler/issues/13)). +`working-directory`, `job-container`, `job-defaults`, and the others), +which `wfc check` requires to fail with their expected +message, `job-services`, `job-env` and `workflow-env` among them; and +`tests/shape.rs`, where a hand-built workflow of the +compiled shape passes and each way out is found: an action, a plain shell, +`working-directory` or an unknown key mid-sandbox, a `--stage` that runs +more or carries `env`, `NODE_OPTIONS` for the wrapper, a second seal id, +publish steps that skip or escape the seal condition, a job or workflow +`env`, job `container`, `services`, `defaults`, `uses` or an unknown key, +a secret or the token in a sandboxed step, a publish step that is +unpinned, has an unknown key, uses sandboxed steps' outputs or expands +event text, a changed, skippable or missing enter, secure-host or seal +step, a seal before entering, and a CONFIG with the runner or root as +sandbox user, another workspace, a hand-off out of it, no sudo lock before +publish steps or an extra key; and, for the tree, an unlisted or `.YML` +workflow, an orphan lock file, and a listed workflow without its reason or +that doesn't exist. `tests/reject/sandbox-user-*.ncl` refuse the runner +and root as `sandbox.user`. ### R2. A sandboxed step runs as another user, in a session of its own diff --git a/lib/gha.ncl b/lib/gha.ncl index a6048aa..7fb0daf 100644 --- a/lib/gha.ncl +++ b/lib/gha.ncl @@ -66,7 +66,7 @@ in # as runner under node before anything is validated, so names that change # how a program starts or where it finds others are refused here, along # with the ones runner-sandbox-run refuses anyway. -let DENIED_ENV_RE = "^(ACTIONS_|RUNNER_|GITHUB_(TOKEN|ENV|PATH|OUTPUT|STATE|STEP_SUMMARY)$|LD_|NODE_|(BASH_ENV|ENV|PATH|HOME|USER|LOGNAME|SHELL)$)" in +let DENIED_ENV_RE = "^(ACTIONS_|RUNNER_|GITHUB_(TOKEN|ENV|PATH|OUTPUT|STATE|STEP_SUMMARY)$|LD_|NODE_|OPENSSL_(CONF|MODULES)$|(BASH_ENV|ENV|PATH|HOME|USER|LOGNAME|SHELL)$)" in let SafeEnvNames = validator (fun env => std.array.all (fun n => !(std.string.is_match DENIED_ENV_RE n)) (std.record.fields env)) (fun env => @@ -305,7 +305,11 @@ let PublishStep = fun publish_ids => std.contract.Sequence [ ] in let Sandbox = { - user | String | validator (fun s => std.string.is_match USER_RE s) (fun s => "invalid user name `%{s}`") | default = "runner-sandbox", + # Never the runner (whose tokens the sandbox must not reach) nor root. + user | String + | validator (fun s => std.string.is_match USER_RE s) (fun s => "invalid user name `%{s}`") + | validator (fun s => !(std.array.elem s ["root", "runner"])) (fun s => "sandbox.user can't be `%{s}`: the sandbox must be another user than the runner and root") + | default = "runner-sandbox", # Take root away from the runner user too, once the sandbox is entered; # its only sudo rule left is the wrapper. lock_runner_sudo | Bool | default = true, diff --git a/runtime/install.cjs b/runtime/install.cjs index 02ec0ca..3ae183a 100644 --- a/runtime/install.cjs +++ b/runtime/install.cjs @@ -46,6 +46,7 @@ if (run("sh", ["-c", "command -v run0"], { check: false }).status !== 0) { const runner = process.env.SUDO_USER; if (!runner || runner === "root") throw new Error("must be started with sudo by the runner user"); const user = CONFIG.user; +if (user === runner || user === "root") throw new Error(`the sandbox user can't be ${user}: it must be another user than the runner and root`); // A runner that ran a job before would hand this one the previous job's // sandbox and workspace: refuse it. (The user itself may come with the @@ -58,6 +59,10 @@ if (run("getent", ["passwd", user], { check: false }).status !== 0) { } const sandbox = passwd(user); const runnerHome = passwd(runner).home; +// Also by uid: another name for root or the runner is still them. +if (sandbox.uid === 0 || sandbox.uid === passwd(runner).uid) { + throw new Error(`the sandbox user ${user} has uid ${sandbox.uid}, root's or the runner's`); +} fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o755 }); // The sandbox works on its own copy of what the job hands it (the files git diff --git a/src/lib.rs b/src/lib.rs index 946f6ef..9668585 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,6 +6,7 @@ pub mod actions; pub mod nickel; pub mod repo; +pub mod shape; use std::collections::{BTreeMap, btree_map}; use std::path::Path; @@ -26,6 +27,8 @@ pub const REJECT_DIR: &str = "tests/reject"; /// actions from tests/actions/, for one) check its output without making /// a workflow of it. pub const ACCEPT_DIR: &str = "tests/accept"; +/// Workflows in [`LOCKS_DIR`] that aren't compiled, each with its reason. +pub const UNCOMPILED: &str = ".github/uncompiled-workflows"; /// How to regenerate what `compile` writes, from the repository root. pub const REGENERATE: &str = "cargo run -- compile"; /// The prefix of a reject test's expected message. @@ -149,6 +152,7 @@ fn check(root: &Repo) -> Result> { } } } + problems.extend(shape::check_tree(root)?); let rejects = root.list(REJECT_DIR, ".ncl")?; for source in &rejects { let text = root.read(source)?.unwrap_or_default(); diff --git a/src/main.rs b/src/main.rs index 59ddfa0..44a3da9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -24,8 +24,10 @@ enum Command { /// in actions.lock.json. Compile(Repo), /// Fail if a lock file or expected output is stale or hand-edited, if - /// actions.lock.json doesn't match the action.yml files it holds, or - /// if a source in tests/reject/ compiles. + /// actions.lock.json doesn't match the action.yml files it holds, if + /// a source in tests/reject/ compiles, or if a workflow in + /// .github/workflows/ is neither a lock file with the compiled shape + /// nor listed in .github/uncompiled-workflows. Check(Repo), } diff --git a/src/repo.rs b/src/repo.rs index 331b35e..696a1cf 100644 --- a/src/repo.rs +++ b/src/repo.rs @@ -37,6 +37,16 @@ impl Repo { } } + /// Whether `rel` is a regular file, not following symlinks; false if + /// it doesn't exist. + pub fn is_file(&self, rel: &str) -> Result { + match std::fs::symlink_metadata(self.path(rel)) { + Ok(meta) => Ok(meta.is_file()), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false), + Err(e) => Err(e).with_context(|| format!("reading {rel}")), + } + } + /// The names in the directory `rel` that end in `suffix`, as paths /// relative to the root, sorted; none if it doesn't exist. pub fn list(&self, rel: &str, suffix: &str) -> Result> { diff --git a/src/shape.rs b/src/shape.rs new file mode 100644 index 0000000..346cc47 --- /dev/null +++ b/src/shape.rs @@ -0,0 +1,743 @@ +//! Checks the shape of a compiled workflow, independently of its source: +//! that it holds exactly what `gha.compile` emits. Each job has the +//! generated steps, byte for byte what this repository's runtime scripts +//! make them, and everything between entering the sandbox and sealing it +//! runs through the step wrapper. Keys are allowlisted, mirroring +//! gha.ncl's closed contracts, so anything GitHub adds later is refused +//! until the compiler knows it. The stale-lock check proves a lock file +//! matches its source; this proves the source went through +//! `gha.compile`, rather than building a record of its own that merely +//! looks like a workflow (#13). + +use std::collections::BTreeMap; +use std::path::Path; +use std::sync::LazyLock; + +use anyhow::{Context, Result}; +use regex::Regex; +use serde_json::{Map, Value}; + +use crate::repo::Repo; +use crate::{LOCKS_DIR, SOURCES_DIR, UNCOMPILED, nickel}; + +/// The texts of the runtime scripts the generated steps embed, by file +/// name. +pub type Runtime = BTreeMap; + +const RUNTIME_DIR: &str = "runtime"; +const EXEC: &str = "/usr/local/bin/runner-sandbox-exec"; +const SEAL_ID: &str = "runner-sandbox-seal"; +const SEAL_CONDITION: &str = "steps.runner-sandbox-seal.outcome == 'success'"; +/// The enter step's embedded scripts, by variable. +const ENTER_ENV: &[(&str, &str)] = &[ + ("RUNNER_SANDBOX_EXEC_JS", "exec.cjs"), + ("RUNNER_SANDBOX_RUN_JS", "run.cjs"), + ("RUNNER_SANDBOX_HANDOFF_JS", "handoff.cjs"), + ("RUNNER_SANDBOX_FILECMD_JS", "filecmd.cjs"), + ("RUNNER_SANDBOX_LAUNCH_JS", "launch.cjs"), +]; +/// The keys gha.ncl's Workflow and Job contracts let through to the output. +const WORKFLOW_KEYS: &[&str] = &[ + "name", + "run-name", + "on", + "permissions", + "concurrency", + "jobs", +]; +const JOB_KEYS: &[&str] = &[ + "name", + "runs-on", + "timeout-minutes", + "if", + "needs", + "permissions", + "steps", +]; +/// The keys of a sandboxed step, by kind; a stage step has no env, which +/// would apply to the bash that runs it as runner. +const WRAPPER_STEP_KEYS: &[&str] = &[ + "name", + "id", + "if", + "continue-on-error", + "timeout-minutes", + "shell", + "run", + "env", +]; +const STAGE_STEP_KEYS: &[&str] = &[ + "name", + "id", + "if", + "continue-on-error", + "timeout-minutes", + "shell", + "run", +]; +const PUBLISH_STEP_KEYS: &[&str] = &[ + "name", + "id", + "if", + "run", + "shell", + "uses", + "with", + "env", + "working-directory", + "continue-on-error", + "timeout-minutes", +]; +const CONFIG_KEYS: &[&str] = &["user", "lockRunnerSudo", "handoff", "workspace"]; +/// Never the sandbox user. +const NOT_SANDBOX_USERS: &[&str] = &["root", "runner"]; +const HANDOFF_MODES: &[&str] = &["tracked", "all", "none"]; + +fn re(pattern: &str) -> Regex { + Regex::new(pattern).expect("valid regex") +} + +/// The wrapper forms a sandboxed step's shell may take. +static SANDBOX_SHELLS: LazyLock<[Regex; 3]> = LazyLock::new(|| { + let exec = regex::escape(EXEC); + [ + re(&format!(r"^{exec} \{{0\}}$")), + re(&format!(r"^{exec} --action \{{0\}}$")), + re(&format!( + r"^{exec} --action-path [A-Za-z0-9_.-]+/[A-Za-z0-9_./-]+@[0-9a-f]{{40}} \{{0\}}$" + )), + ] +}); +static STAGE_RUN: LazyLock = LazyLock::new(|| { + re(&format!( + r"^{} --stage [A-Za-z0-9_-]+ ([A-Za-z0-9._-]+(/[A-Za-z0-9._-]+)*)$", + regex::escape(EXEC) + )) +}); +static ACTION_PATH: LazyLock = LazyLock::new(|| re(r"--action-path (\S+)@")); +/// `.` and `..` path components, which gha.ncl's path contracts refuse. +static DOT_COMPONENT: LazyLock = LazyLock::new(|| re(r"(^|/)\.\.?(/|$)")); +static PINNED: LazyLock = + LazyLock::new(|| re(r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_./-]+@[0-9a-f]{40}$")); +// Expressions, as gha.ncl's lints read them: CREDENTIALS_RE +// (NoCredentials), STEP_OUTPUTS_RE and WHOLE_STEPS_RE +// (NoSandboxOutputs), UNTRUSTED_TEXT_RE and SAFE_EVENT_RE +// (NoUntrustedTextInScript). `\b` is ASCII's, as in their JavaScript +// originals. +static CREDENTIALS: LazyLock = LazyLock::new(|| { + re(r"(?i)(?-u:\b)secrets(?-u:\b)|(?-u:\b)github\s*(\[|[,)}]|\.\s*token(?-u:\b)|\.\s*\*)") +}); +static STEP_OUTPUTS: LazyLock = + LazyLock::new(|| re(r"(?i)(?-u:\b)steps\s*\.\s*([A-Za-z0-9_-]+)\s*\.\s*outputs(?-u:\b)")); +static WHOLE_STEPS: LazyLock = LazyLock::new(|| { + re(r"(?i)(?-u:\b)steps(?-u:\b)\s*(\[|[,)}]|$|\.\s*\*|\.\s*[A-Za-z0-9_-]+\s*(\[|\.\s*\*))") +}); +static UNTRUSTED_TEXT: LazyLock = LazyLock::new(|| { + re( + r"(?i)(?-u:\b)github\s*(\.\s*(event|head_ref)(?-u:\b)|\.\s*\*|\[|[,)}]|$)|(?-u:\b)inputs(?-u:\b)|(?-u:\b)needs\s*(\.\s*[A-Za-z0-9_*-]+\s*(\.\s*outputs(?-u:\b)|\[)|\[|\.\s*\*|[,)}]|$)", + ) +}); +// ASCII case folding only (`-u`): this one exempts text, and Unicode's +// would also fold `ſ` and the Kelvin sign into its names. +static SAFE_EVENT: LazyLock = LazyLock::new(|| { + re( + r"(?i-u)\bgithub\s*\.\s*event\s*\.\s*(number|(issue|pull_request|comment|review|review_comment|discussion|discussion_comment|release|milestone|workflow_run|check_run|check_suite|deployment|repository|sender)\s*\.\s*(number|id))\b", + ) +}); +static WHOLE_ENV: LazyLock = LazyLock::new(|| re(r"(?i)(?-u:\b)env\s*(\[|\.\s*\*|[,)}]|$)")); +/// As DENIED_ENV_RE in lib/gha.ncl: names that would change how the +/// runner side of the wrapper starts. The wrapper's own are allowed. +static DENIED_ENV: LazyLock = LazyLock::new(|| { + re( + r"^(ACTIONS_|RUNNER_|GITHUB_(TOKEN|ENV|PATH|OUTPUT|STATE|STEP_SUMMARY)$|LD_|NODE_|OPENSSL_(CONF|MODULES)$|(BASH_ENV|ENV|PATH|HOME|USER|LOGNAME|SHELL)$)", + ) +}); +static WRAPPER_ENV: LazyLock = + LazyLock::new(|| re(r"^RUNNER_SANDBOX_(ENV|ENV_NAMES|VAR_[0-9]+)$")); +/// As USER_RE in lib/gha.ncl. +static USER: LazyLock = LazyLock::new(|| re(r"^[a-z_][a-z0-9_-]{0,30}$")); +static WORKSPACE_PATH: LazyLock = LazyLock::new(|| re(r"^[^/]+(/[^/]+)*$")); +static QUOTED: LazyLock = LazyLock::new(|| re(r"'([^']|'')*'")); +static AFTER_SEAL_WRAPPED: LazyLock = LazyLock::new(|| { + re(&format!( + r"(?s)^\((.*)\) && {}$", + regex::escape(SEAL_CONDITION) + )) +}); +static AFTER_SEAL_OUTCOME: LazyLock = LazyLock::new(|| { + re(&format!( + r"^!cancelled\(\) && steps\.[A-Za-z0-9_-]+\.outcome == 'success' && {}$", + regex::escape(SEAL_CONDITION) + )) +}); +static UNCOMPILED_LINE: LazyLock = LazyLock::new(|| re(r"^\s*(\S+)\s+#\s*(\S.*)$")); + +fn enter_shell() -> String { + let names: Vec<&str> = ENTER_ENV.iter().map(|(k, _)| *k).collect(); + format!("sudo --preserve-env={} node {{0}}", names.join(",")) +} + +/// The `${{ ... }}` expressions in `v`, each up to the end of `v`. +fn expressions(v: &str) -> impl Iterator { + v.split("${{").skip(1) +} + +/// Every string in `v`, however deep. +fn strings(v: &Value) -> Vec<&str> { + match v { + Value::String(s) => vec![s], + Value::Array(a) => a.iter().flat_map(strings).collect(), + Value::Object(o) => o.values().flat_map(strings).collect(), + _ => vec![], + } +} + +fn untrusted(e: &str) -> bool { + UNTRUSTED_TEXT.is_match(&SAFE_EVENT.replace_all(e, "0")) +} + +fn json(v: Option<&Value>) -> String { + v.map_or_else(|| "undefined".into(), Value::to_string) +} + +/// The keys of `obj` not in `allowed`. +fn keys_outside<'a>(obj: &'a Map, allowed: &[&str]) -> Vec<&'a str> { + obj.keys() + .map(String::as_str) + .filter(|k| !allowed.contains(k)) + .collect() +} + +/// Whether `v` is a map with exactly `keys`. +fn has_keys(v: &Value, keys: &[&str]) -> bool { + v.as_object() + .is_some_and(|o| o.len() == keys.len() && keys.iter().all(|k| o.contains_key(*k))) +} + +fn str_of<'a>(v: &'a Value, key: &str) -> Option<&'a str> { + v.get(key).and_then(Value::as_str) +} + +/// Problems with `config`, the enter step's configuration. +fn config_problems(config: &Value, has_publish: bool) -> Vec { + let mut problems = Vec::new(); + if !has_keys(config, CONFIG_KEYS) { + let keys: Vec = config + .as_object() + .map(|o| o.keys().cloned().collect()) + .unwrap_or_default(); + problems.push(format!("has CONFIG keys {}", Value::from(keys))); + } + let user = str_of(config, "user"); + if !user.is_some_and(|u| USER.is_match(u) && !NOT_SANDBOX_USERS.contains(&u)) { + problems.push(format!("has the sandbox user {}", json(config.get("user")))); + } + if str_of(config, "workspace") != Some("${{ github.workspace }}") { + problems.push(format!( + "hands off {}, not the workspace", + json(config.get("workspace")) + )); + } + // As PublishNeedsLock in gha.ncl: runner code after the sandbox only + // with runner's root taken away. + let lock = config.get("lockRunnerSudo"); + if lock != Some(&Value::Bool(true)) && (lock != Some(&Value::Bool(false)) || has_publish) { + problems.push(format!( + "has lockRunnerSudo {}{}", + json(lock), + if has_publish { + " with steps after the seal" + } else { + "" + } + )); + } + let handoff = config.get("handoff"); + let handoff_ok = handoff.is_some_and(|h| { + has_keys(h, &["workspace", "include"]) + && str_of(h, "workspace").is_some_and(|m| HANDOFF_MODES.contains(&m)) + && h["include"].as_array().is_some_and(|include| { + include.iter().all(|p| { + p.as_str().is_some_and(|p| { + WORKSPACE_PATH.is_match(p) + && !DOT_COMPONENT.is_match(p) + && !p.contains("${{") + }) + }) + }) + }); + if !handoff_ok { + problems.push(format!("has the hand-off {}", json(handoff))); + } + problems +} + +/// The CONFIG of `run` if it is `const CONFIG = ;\n` +/// followed by install.cjs. +fn install_config(runtime: &Runtime, run: Option<&Value>) -> Option { + let install = runtime.get("install.cjs")?; + let config = run? + .as_str()? + .strip_suffix(install.as_str())? + .strip_prefix("const CONFIG = ")? + .strip_suffix(";\n")?; + serde_json::from_str::(config) + .ok() + .filter(Value::is_object) +} + +fn is_enter(runtime: &Runtime, s: &Value) -> bool { + has_keys(s, &["name", "shell", "env", "run"]) + && str_of(s, "name") == Some("Enter the sandbox (generated)") + && str_of(s, "shell") == Some(enter_shell().as_str()) + && install_config(runtime, s.get("run")).is_some() + && has_keys( + &s["env"], + &ENTER_ENV.iter().map(|(k, _)| *k).collect::>(), + ) + && ENTER_ENV.iter().all(|(k, f)| { + runtime + .get(*f) + .is_some_and(|text| str_of(&s["env"], k) == Some(text)) + }) +} + +fn is_secure_host(runtime: &Runtime, s: &Value) -> bool { + has_keys(s, &["name", "shell", "run"]) + && str_of(s, "name") == Some("Secure the host (generated)") + && str_of(s, "shell") == Some("sudo node {0}") + && runtime + .get("secure-host.cjs") + .is_some_and(|text| str_of(s, "run") == Some(text)) +} + +fn is_seal(s: &Value) -> bool { + has_keys(s, &["name", "id", "if", "shell", "run"]) + && str_of(s, "name") == Some("Seal the sandbox (generated)") + && str_of(s, "id") == Some(SEAL_ID) + && str_of(s, "if") == Some("always()") + && str_of(s, "shell") == Some("bash") + && str_of(s, "run") == Some(format!("{EXEC} --seal").as_str()) +} + +/// Whether `cond` has balanced parentheses outside string literals. +fn balanced(cond: &str) -> bool { + let mut depth = 0i64; + for c in QUOTED.replace_all(cond, "''").chars() { + depth += match c { + '(' => 1, + ')' => -1, + _ => 0, + }; + if depth < 0 { + return false; + } + } + depth == 0 +} + +/// Whether a publish step's condition requires the seal to have succeeded. +fn after_seal(cond: Option<&Value>) -> bool { + let Some(cond) = cond.and_then(Value::as_str) else { + return false; + }; + if cond.contains("${{") || cond.contains("}}") { + return false; + } + if let Some(caps) = AFTER_SEAL_WRAPPED.captures(cond) { + return balanced(&caps[1]); + } + AFTER_SEAL_OUTCOME.is_match(cond) +} + +/// Problems with `step`, a step between entering the sandbox and the seal. +fn sandbox_step_problems(step: &Map) -> Vec { + let mut problems = Vec::new(); + let get = |k: &str| step.get(k).and_then(Value::as_str); + let shell = get("shell").unwrap_or(""); + let stage = (shell == "bash") + .then(|| STAGE_RUN.captures(get("run").unwrap_or(""))) + .flatten(); + let extra = keys_outside( + step, + if stage.is_some() { + STAGE_STEP_KEYS + } else { + WRAPPER_STEP_KEYS + }, + ); + if !extra.is_empty() { + problems.push(format!( + "has {}, which a {} step never has", + extra.join(", "), + if stage.is_some() { + "stage" + } else { + "sandboxed" + } + )); + } + if get("id") == Some(SEAL_ID) { + problems.push(format!("has the seal's id {SEAL_ID}")); + } + if stage.is_none() && !SANDBOX_SHELLS.iter().any(|re| re.is_match(shell)) { + problems.push(format!( + "runs with shell {}, not the sandbox wrapper", + step.get("shell").unwrap_or(&Value::Null) + )); + } + let stage_path = stage + .as_ref() + .map_or("", |c| c.get(1).map_or("", |m| m.as_str())); + let action_path = ACTION_PATH + .captures(shell) + .map_or("", |c| c.get(1).map_or("", |m| m.as_str())); + if [stage_path, action_path] + .iter() + .any(|p| DOT_COMPONENT.is_match(p)) + { + problems.push("names a path with `.` or `..`".into()); + } + if step + .values() + .flat_map(strings) + .any(|v| expressions(v).any(|e| CREDENTIALS.is_match(e))) + { + problems.push("references secrets or the job's token, which a sandboxed step can't".into()); + } + if let Some(env) = step.get("env").and_then(Value::as_object) { + for name in env.keys() { + if !WRAPPER_ENV.is_match(name) && DENIED_ENV.is_match(name) { + problems.push(format!("sets {name} for the wrapper's runner side")); + } + } + } + problems +} + +/// Problems with `step`, a step after the seal, as gha.ncl's PublishStep +/// has them (`ids`: the ids of the publish steps, whose outputs are +/// runner's, lowercased). +fn publish_step_problems(step: &Map, ids: &[String]) -> Vec { + let mut problems = Vec::new(); + let extra = keys_outside(step, PUBLISH_STEP_KEYS); + if !extra.is_empty() { + problems.push(format!( + "has {}, which a publish step never has", + extra.join(", ") + )); + } + if step.contains_key("run") == step.contains_key("uses") { + problems.push("needs exactly one of run or uses".into()); + } + if let Some(uses) = step.get("uses") + && !uses.as_str().is_some_and(|u| PINNED.is_match(u)) + { + problems.push(format!("uses {uses}, which isn't pinned by commit")); + } + let null = Value::Null; + let field = |k: &str| step.get(k).unwrap_or(&null); + let data: Vec<&str> = [field("run"), field("working-directory")] + .into_iter() + .filter_map(Value::as_str) + .chain(strings(field("with"))) + .chain(strings(field("env"))) + .collect(); + let sandbox_outputs = |e: &str| { + WHOLE_STEPS.is_match(e) + || STEP_OUTPUTS + .captures_iter(e) + .any(|c| !ids.contains(&c[1].to_lowercase())) + }; + if data.iter().any(|v| expressions(v).any(sandbox_outputs)) { + problems.push("uses sandboxed steps' outputs, strings the sandbox chose".into()); + } + // Scripts: the run, and every with (github-script's script and the + // like), including env values re-expanded into them. + let tainted: Vec = field("env") + .as_object() + .into_iter() + .flatten() + .filter(|(_, v)| v.as_str().is_some_and(|v| expressions(v).any(untrusted))) + .map(|(k, _)| { + re(&format!( + r"(?i)(?-u:\b)env\s*\.\s*{}(?-u:\b)", + regex::escape(k) + )) + }) + .collect(); + let expands_env = |e: &str| { + !tainted.is_empty() && (WHOLE_ENV.is_match(e) || tainted.iter().any(|t| t.is_match(e))) + }; + let scripts: Vec<&str> = field("run") + .as_str() + .into_iter() + .chain(strings(field("with"))) + .collect(); + if scripts + .iter() + .any(|v| expressions(v).any(|e| untrusted(e) || expands_env(e))) + { + problems.push("expands text others control into a script run as runner".into()); + } + problems +} + +/// The problems with `workflow`, a parsed lock file, given the runtime +/// scripts its generated steps must embed. +pub fn check_workflow(workflow: &Value, runtime: &Runtime) -> Vec { + let mut problems = Vec::new(); + let Some(top) = workflow.as_object() else { + return vec!["the workflow isn't a map".into()]; + }; + let extra = keys_outside(top, WORKFLOW_KEYS); + if !extra.is_empty() { + problems.push(format!( + "the workflow sets {}, which a compiled one never has", + extra.join(", ") + )); + } + if top.get("permissions").is_some_and(|p| !p.is_object()) { + problems.push("the workflow's permissions aren't a map".into()); + } + let Some(jobs) = top.get("jobs").and_then(Value::as_object) else { + problems.push("the workflow has no jobs map".into()); + return problems; + }; + for (name, job) in jobs { + let Some(job) = job.as_object() else { + problems.push(format!("job {name} isn't a map")); + continue; + }; + let extra = keys_outside(job, JOB_KEYS); + if !extra.is_empty() { + problems.push(format!( + "job {name} sets {}, which a compiled job never has", + extra.join(", ") + )); + } + if job.get("permissions").is_some_and(|p| !p.is_object()) { + problems.push(format!("job {name}'s permissions aren't a map")); + } + let steps: &[Value] = job + .get("steps") + .and_then(Value::as_array) + .map_or(&[], Vec::as_slice); + let at = |i: usize, s: &Value| match str_of(s, "name") { + Some(n) if !n.is_empty() => format!("job {name}, step {} ({n})", i + 1), + _ => format!("job {name}, step {}", i + 1), + }; + let enters: Vec = (0..steps.len()) + .filter(|&i| is_enter(runtime, &steps[i])) + .collect(); + let seals: Vec = (0..steps.len()) + .filter(|&i| str_of(&steps[i], "id") == Some(SEAL_ID)) + .collect(); + let &[enter] = enters.as_slice() else { + problems.push(format!( + "job {name} has {} generated steps entering the sandbox, not 1 (or it differs from what the compiler generates)", + enters.len() + )); + continue; + }; + if enter == 0 || !is_secure_host(runtime, &steps[enter - 1]) { + problems.push(format!( + "job {name}: the step before entering the sandbox isn't the generated secure-host step" + )); + } + let seal = match seals.as_slice() { + &[seal] if seal > enter && is_seal(&steps[seal]) => seal, + _ => { + problems.push(format!( + "job {name} doesn't have exactly one generated seal step after entering the sandbox" + )); + continue; + } + }; + let config = install_config(runtime, steps[enter].get("run")).expect("checked by is_enter"); + for p in config_problems(&config, seal < steps.len() - 1) { + problems.push(format!("job {name}: the enter step {p}")); + } + for (i, step) in steps.iter().enumerate().take(seal).skip(enter + 1) { + let Some(fields) = step.as_object() else { + problems.push(format!("{} isn't a map", at(i, step))); + continue; + }; + for p in sandbox_step_problems(fields) { + problems.push(format!("{} {p}", at(i, step))); + } + } + let publish_ids: Vec = steps[seal + 1..] + .iter() + .filter_map(|s| str_of(s, "id")) + .map(str::to_lowercase) + .collect(); + for (i, step) in steps.iter().enumerate().skip(seal + 1) { + let Some(fields) = step.as_object() else { + problems.push(format!("{} isn't a map", at(i, step))); + continue; + }; + if !after_seal(fields.get("if")) { + problems.push(format!( + "{} runs as runner after the sandbox without requiring the seal to have succeeded", + at(i, step) + )); + } + for p in publish_step_problems(fields, &publish_ids) { + problems.push(format!("{} {p}", at(i, step))); + } + } + } + problems +} + +/// The names `text` (the uncompiled-workflows list) holds, and its lines +/// without a reason. +fn read_uncompiled(text: &str) -> (Vec, Vec) { + let mut names = Vec::new(); + let mut unexplained = Vec::new(); + for line in text.lines() { + let trimmed = line.trim(); + if trimmed.is_empty() || trimmed.starts_with('#') { + continue; + } + match UNCOMPILED_LINE.captures(line) { + Some(c) => names.push(c[1].to_owned()), + None => unexplained.push(trimmed.to_owned()), + } + } + (names, unexplained) +} + +/// The names of the entries in the directory `rel`, sorted; none if it +/// doesn't exist. +fn files_in(root: &Repo, rel: &str) -> Result> { + let prefix = format!("{rel}/"); + Ok(root + .list(rel, "")? + .into_iter() + .map(|p| p.strip_prefix(&prefix).unwrap_or(&p).to_owned()) + .collect()) +} + +/// The runtime scripts of the repository at `root`. +pub fn read_runtime(root: &Repo) -> Result { + let mut runtime = Runtime::new(); + for name in files_in(root, RUNTIME_DIR)? { + let rel = format!("{RUNTIME_DIR}/{name}"); + // Only files are scripts; a directory or symlink there is skipped. + if root.is_file(&rel)? + && let Some(text) = root.read(&rel)? + { + runtime.insert(name, text); + } + } + Ok(runtime) +} + +/// Checks that every file in `root`'s [`LOCKS_DIR`] is a lock file with a +/// source in [`SOURCES_DIR`] and the compiled shape, or listed in +/// [`UNCOMPILED`], one name per line with its reason after `#`: each runs +/// with none of the compiler's guarantees, so each is a reviewed +/// exception. Returns the problems. +pub fn check_tree(root: &Repo) -> Result> { + let mut found = Vec::new(); + let list_name = Path::new(UNCOMPILED) + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or(UNCOMPILED); + let list = root.read(UNCOMPILED)?.unwrap_or_default(); + let (listed, unexplained) = read_uncompiled(&list); + for line in unexplained { + found.push(format!( + "{list_name}: {} has no \"# reason\"", + Value::from(line) + )); + } + let runtime = read_runtime(root)?; + let files = files_in(root, LOCKS_DIR)?; + for file in &files { + let rel = format!("{LOCKS_DIR}/{file}"); + let Some(stem) = file.strip_suffix(".lock.yml") else { + if !listed.contains(file) { + found.push(format!( + "{rel} isn't compiled; compile it from {SOURCES_DIR}/, or list it in {list_name} with the reason" + )); + } + continue; + }; + if root.read(&format!("{SOURCES_DIR}/{stem}.ncl"))?.is_none() { + found.push(format!("{rel} has no source in {SOURCES_DIR}/")); + continue; + } + let text = root + .read(&rel)? + .with_context(|| format!("{rel} disappeared"))?; + // YAML only: nickel parses it as data, with no imports to follow. + match nickel::yaml_to_json(&rel, &text) { + Err(e) => found.push(format!("{rel} can't be parsed: {e:#}")), + Ok(workflow) => { + for p in check_workflow(&workflow, &runtime) { + found.push(format!("{rel}: {p}")); + } + } + } + } + for name in listed { + if !files.contains(&name) { + found.push(format!("{list_name} lists {name}, which doesn't exist")); + } + } + Ok(found) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn conditions_after_the_seal() { + let seal = SEAL_CONDITION; + for (cond, ok) in [ + (format!("(success()) && {seal}"), true), + (format!("(a || (b)) && {seal}"), true), + ( + format!("!cancelled() && steps.x.outcome == 'success' && {seal}"), + true, + ), + (format!("(always()) || (true) && {seal}"), false), + (format!("(')') && {seal}"), true), + (format!("(a)) || ((b) && {seal}"), false), + (format!("${{{{ x }}}} && {seal}"), false), + (seal.to_owned(), false), + ] { + assert_eq!(after_seal(Some(&Value::from(cond.clone()))), ok, "{cond}"); + } + assert!(!after_seal(None)); + } + + #[test] + fn untrusted_text() { + for (e, want) in [ + (" github.event.issue.title }}", true), + (" github.event.pull_request.number }}", false), + (" GITHUB.EVENT.number }}", false), + (" github.head_ref }}", true), + (" toJSON(github) }}", true), + (" inputs.x }}", true), + (" needs.a.outputs.b }}", true), + (" needs.a.result }}", false), + (" github.sha }}", false), + ] { + assert_eq!(untrusted(e), want, "{e}"); + } + } + + #[test] + fn uncompiled_list() { + let (names, unexplained) = + read_uncompiled("# c\n\nci.yml # ours\n x.yml #why\nbare.yml\n"); + assert_eq!(names, ["ci.yml", "x.yml"]); + assert_eq!(unexplained, ["bare.yml"]); + } +} diff --git a/tests/accept/composite.expected.yml b/tests/accept/composite.expected.yml index 934bf45..b8c0fac 100644 --- a/tests/accept/composite.expected.yml +++ b/tests/accept/composite.expected.yml @@ -1072,6 +1072,7 @@ jobs: const runner = process.env.SUDO_USER; if (!runner || runner === "root") throw new Error("must be started with sudo by the runner user"); const user = CONFIG.user; + if (user === runner || user === "root") throw new Error(`the sandbox user can't be ${user}: it must be another user than the runner and root`); // A runner that ran a job before would hand this one the previous job's // sandbox and workspace: refuse it. (The user itself may come with the @@ -1084,6 +1085,10 @@ jobs: } const sandbox = passwd(user); const runnerHome = passwd(runner).home; + // Also by uid: another name for root or the runner is still them. + if (sandbox.uid === 0 || sandbox.uid === passwd(runner).uid) { + throw new Error(`the sandbox user ${user} has uid ${sandbox.uid}, root's or the runner's`); + } fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o755 }); // The sandbox works on its own copy of what the job hands it (the files git diff --git a/tests/reject/env-openssl-conf.ncl b/tests/reject/env-openssl-conf.ncl new file mode 100644 index 0000000..ce5748e --- /dev/null +++ b/tests/reject/env-openssl-conf.ncl @@ -0,0 +1,10 @@ +# expect: cannot be set in a sandboxed step +let gha = import "../../lib/gha.ncl" in +gha.compile { + name = "t", + on = { push = {} }, + jobs.t = { + "runs-on" = "ubuntu-26.04", + steps = [{ run = "id", env = { OPENSSL_CONF = "/tmp/x.cnf" } }], + }, +} diff --git a/tests/reject/sandbox-user-root.ncl b/tests/reject/sandbox-user-root.ncl new file mode 100644 index 0000000..7739dd4 --- /dev/null +++ b/tests/reject/sandbox-user-root.ncl @@ -0,0 +1,11 @@ +# expect: sandbox.user can't be `root` +let gha = import "../../lib/gha.ncl" in +gha.compile { + name = "t", + on = { push = {} }, + jobs.t = { + "runs-on" = "ubuntu-26.04", + sandbox.user = "root", + steps = [{ run = "id" }], + }, +} diff --git a/tests/reject/sandbox-user-runner.ncl b/tests/reject/sandbox-user-runner.ncl new file mode 100644 index 0000000..738323a --- /dev/null +++ b/tests/reject/sandbox-user-runner.ncl @@ -0,0 +1,11 @@ +# expect: sandbox.user can't be `runner` +let gha = import "../../lib/gha.ncl" in +gha.compile { + name = "t", + on = { push = {} }, + jobs.t = { + "runs-on" = "ubuntu-26.04", + sandbox.user = "runner", + steps = [{ run = "id" }], + }, +} diff --git a/tests/repo.rs b/tests/repo.rs index 8c5eaba..caec66a 100644 --- a/tests/repo.rs +++ b/tests/repo.rs @@ -1,7 +1,7 @@ -//! This repository's own check: every lock file matches its source, every -//! accept test compiles to its expected output, every reject test fails -//! with its message, and actions.lock.json matches the action.yml files it -//! holds. +//! This repository's own check: every lock file matches its source and +//! has the compiled shape, every accept test compiles to its expected +//! output, every reject test fails with its message, and +//! actions.lock.json matches the action.yml files it holds. use std::process::Command; diff --git a/tests/shape.rs b/tests/shape.rs new file mode 100644 index 0000000..90a9bb8 --- /dev/null +++ b/tests/shape.rs @@ -0,0 +1,500 @@ +//! Tests for the shape check: a job of the compiled shape passes, and +//! each way of leaving the sandbox that a hand-built "compiled" workflow +//! could take is found. + +use std::path::Path; +use std::sync::LazyLock; + +use serde_json::{Value, json}; +use workflow_compiler::repo::Repo; +use workflow_compiler::shape::{Runtime, check_tree, check_workflow, read_runtime}; + +const EXEC: &str = "/usr/local/bin/runner-sandbox-exec"; +const SEAL: &str = "steps.runner-sandbox-seal.outcome == 'success'"; +const UPLOAD: &str = "actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a"; + +static RUNTIME: LazyLock = LazyLock::new(|| { + read_runtime(&Repo::open(Path::new(env!("CARGO_MANIFEST_DIR"))).unwrap()).unwrap() +}); + +fn rt(name: &str) -> &'static str { + RUNTIME + .get(name) + .unwrap_or_else(|| panic!("no runtime/{name}")) +} + +fn config() -> Value { + json!({ + "user": "runner-sandbox", + "lockRunnerSudo": true, + "handoff": { "workspace": "tracked", "include": [".git"] }, + "workspace": "${{ github.workspace }}", + }) +} + +fn with(base: Value, changes: Value) -> Value { + let mut base = base; + for (k, v) in changes.as_object().unwrap() { + base[k] = v.clone(); + } + base +} + +fn wrap(run: &str) -> Value { + json!({ "shell": format!("{EXEC} {{0}}"), "run": run }) +} + +/// A workflow of the compiled shape, with `sandboxed` steps between +/// enter and seal and `publish` steps after the seal, and `job` and `top` +/// merged into the job and the workflow. +struct Workflow { + sandboxed: Vec, + publish: Vec, + job: Value, + top: Value, + config: Value, +} + +impl Default for Workflow { + fn default() -> Self { + Workflow { + sandboxed: vec![wrap("id")], + publish: vec![], + job: json!({}), + top: json!({}), + config: config(), + } + } +} + +impl Workflow { + fn build(self) -> Value { + let env = json!({ + "RUNNER_SANDBOX_EXEC_JS": rt("exec.cjs"), + "RUNNER_SANDBOX_RUN_JS": rt("run.cjs"), + "RUNNER_SANDBOX_HANDOFF_JS": rt("handoff.cjs"), + "RUNNER_SANDBOX_FILECMD_JS": rt("filecmd.cjs"), + "RUNNER_SANDBOX_LAUNCH_JS": rt("launch.cjs"), + }); + let mut steps = vec![ + json!({ "uses": "actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1", "with": { "persist-credentials": false } }), + json!({ "name": "Secure the host (generated)", "shell": "sudo node {0}", "run": rt("secure-host.cjs") }), + json!({ + "name": "Enter the sandbox (generated)", + "shell": "sudo --preserve-env=RUNNER_SANDBOX_EXEC_JS,RUNNER_SANDBOX_RUN_JS,RUNNER_SANDBOX_HANDOFF_JS,RUNNER_SANDBOX_FILECMD_JS,RUNNER_SANDBOX_LAUNCH_JS node {0}", + "env": env, + "run": format!("const CONFIG = {};\n{}", self.config, rt("install.cjs")), + }), + ]; + steps.extend(self.sandboxed); + steps.push(json!({ "name": "Seal the sandbox (generated)", "id": "runner-sandbox-seal", "if": "always()", "shell": "bash", "run": format!("{EXEC} --seal") })); + steps.extend(self.publish); + let job = with(json!({ "runs-on": "ubuntu-26.04" }), self.job); + let job = with(job, json!({ "steps": steps })); + with( + with(json!({ "name": "t" }), self.top), + json!({ "jobs": { "t": job } }), + ) + } +} + +fn problems(w: Workflow) -> Vec { + check_workflow(&w.build(), &RUNTIME) +} + +fn sandboxed(steps: Vec) -> Workflow { + Workflow { + sandboxed: steps, + ..Default::default() + } +} + +fn publish(steps: Vec) -> Workflow { + Workflow { + publish: steps, + ..Default::default() + } +} + +fn job(job: Value) -> Workflow { + Workflow { + job, + ..Default::default() + } +} + +fn with_config(config: Value) -> Workflow { + Workflow { + config, + ..Default::default() + } +} + +#[test] +fn the_compiled_shape_passes() { + let ok = Workflow { + sandboxed: vec![ + json!({ "shell": format!("{EXEC} {{0}}"), "run": "make", "env": { "CC": "gcc", "RUNNER_SANDBOX_ENV": "CC" } }), + json!({ "shell": format!("{EXEC} --action {{0}}"), "run": "{}", "env": { "RUNNER_SANDBOX_ENV_NAMES": "INPUT_X", "RUNNER_SANDBOX_VAR_0": "1" } }), + json!({ "shell": format!("{EXEC} --action-path o/r@{} {{0}}", "a".repeat(40)), "run": "true" }), + json!({ "id": "stage-log", "shell": "bash", "run": format!("{EXEC} --stage log out/test.log") }), + ], + publish: vec![ + json!({ "if": format!("!cancelled() && steps.stage-log.outcome == 'success' && {SEAL}"), "uses": UPLOAD }), + json!({ "if": format!("(always()) && {SEAL}"), "run": "gh pr comment" }), + ], + ..Default::default() + }; + assert_eq!(problems(ok), Vec::::new()); + // Without steps after the seal, a job may keep runner's sudo (as + // PublishNeedsLock in gha.ncl allows). + let no_lock = with_config(with(config(), json!({ "lockRunnerSudo": false }))); + assert_eq!(problems(no_lock), Vec::::new()); + // What the compiler emits for these passes: a publish step's own + // outputs, an event number, outcomes. + let ok = publish(vec![ + json!({ "if": format!("(success()) && {SEAL}"), "id": "read", "run": "echo n=1 >>\"$GITHUB_OUTPUT\"" }), + json!({ "if": format!("(steps.x.outcome == 'success') && {SEAL}"), "run": "echo ${{ steps.read.outputs.n }} ${{ github.event.pull_request.number }}" }), + ]); + assert_eq!(problems(ok), Vec::::new()); +} + +#[test] +fn finds_each_way_out_of_the_sandbox() { + let stage = |run: &str| json!({ "shell": "bash", "run": run }); + let cases = [ + ( + "an action mid-sandbox", + sandboxed(vec![json!({ "uses": UPLOAD })]), + "has uses, which a sandboxed step never has", + ), + ( + "a plain shell", + sandboxed(vec![json!({ "shell": "bash", "run": "id" })]), + "not the sandbox wrapper", + ), + ( + "a default shell", + sandboxed(vec![json!({ "run": "id" })]), + "not the sandbox wrapper", + ), + ( + "a stage that runs more", + sandboxed(vec![stage(&format!("{EXEC} --stage x y; curl evil"))]), + "not the sandbox wrapper", + ), + ( + "NODE_OPTIONS for the wrapper", + sandboxed(vec![with( + wrap("id"), + json!({ "env": { "NODE_OPTIONS": "--require /tmp/x" } }), + )]), + "sets NODE_OPTIONS", + ), + ( + "a second seal id", + sandboxed(vec![with( + wrap("true"), + json!({ "id": "runner-sandbox-seal" }), + )]), + "exactly one generated seal step", + ), + ( + "publish without the seal", + publish(vec![json!({ "run": "id" })]), + "without requiring the seal", + ), + ( + "publish escaping the seal", + publish(vec![ + json!({ "if": format!("(always()) || (true) && {SEAL}"), "run": "id" }), + ]), + "without requiring the seal", + ), + ( + "publish as a template", + publish(vec![ + json!({ "if": format!("${{{{ 'a' }}}} && {SEAL}"), "run": "id" }), + ]), + "without requiring the seal", + ), + ( + "a job env", + job(json!({ "env": { "LD_PRELOAD": "/tmp/x.so" } })), + "sets env", + ), + ( + "a job container", + job(json!({ "container": "alpine" })), + "sets container", + ), + ( + "job services", + job(json!({ "services": { "db": { "image": "postgres" } } })), + "sets services", + ), + ( + "job defaults", + job(json!({ "defaults": { "run": { "shell": "bash" } } })), + "sets defaults", + ), + ( + "a reusable workflow", + job(json!({ "uses": "o/r/.github/workflows/x.yml@main" })), + "sets uses", + ), + ( + "a key GitHub may add", + job(json!({ "snapshot": "x" })), + "sets snapshot", + ), + ( + "a workflow env", + Workflow { + top: json!({ "env": { "BASH_ENV": "/tmp/x" } }), + ..Default::default() + }, + "the workflow sets env", + ), + ( + "working-directory", + sandboxed(vec![with(wrap("id"), json!({ "working-directory": "/" }))]), + "has working-directory", + ), + ( + "a stage step with env", + sandboxed(vec![with( + stage(&format!("{EXEC} --stage x y")), + json!({ "env": { "SHELLOPTS": "xtrace", "PS4": "$(id)" } }), + )]), + "has env, which a stage step never has", + ), + ( + "an unknown step key", + sandboxed(vec![with(wrap("id"), json!({ "with": { "a": "b" } }))]), + "has with", + ), + ]; + for (name, w, want) in cases { + let found = problems(w); + assert!(found.iter().any(|p| p.contains(want)), "{name}: {found:?}"); + } +} + +#[test] +fn finds_changes_to_the_generated_steps() { + type Edit = fn(&mut Vec); + let edits: &[(&str, Edit, &str)] = &[ + ( + "a modified enter step", + |st| { + let run = format!( + "{}\nrequire('child_process').execSync('echo pwned');", + st[2]["run"].as_str().unwrap() + ); + st[2]["run"] = run.into(); + }, + "0 generated steps entering the sandbox", + ), + ( + "no enter step", + |st| { + st.remove(2); + }, + "0 generated steps entering the sandbox", + ), + ( + "an enter step that can be skipped", + |st| { + st[2]["if"] = "false".into(); + }, + "0 generated steps entering the sandbox", + ), + ( + "a missing secure-host step", + |st| { + st.remove(1); + }, + "isn't the generated secure-host step", + ), + ( + "a modified secure-host step", + |st| { + let run = format!("{}\n", st[1]["run"].as_str().unwrap()); + st[1]["run"] = run.into(); + }, + "isn't the generated secure-host step", + ), + ( + "a secure-host step allowed to fail", + |st| { + st[1]["continue-on-error"] = true.into(); + }, + "isn't the generated secure-host step", + ), + ( + "a modified seal", + |st| { + st.last_mut().unwrap()["run"] = format!("{EXEC} --seal || true").into(); + }, + "exactly one generated seal step", + ), + ( + "a seal that can be skipped", + |st| { + st.last_mut().unwrap()["if"] = "false".into(); + }, + "exactly one generated seal step", + ), + ( + "a seal with a timeout", + |st| { + st.last_mut().unwrap()["timeout-minutes"] = 0.into(); + }, + "exactly one generated seal step", + ), + ( + "a seal before entering", + |st| { + let seal = st.pop().unwrap(); + st.insert(2, seal); + }, + "exactly one generated seal step", + ), + ]; + for (name, edit, want) in edits { + let mut w = Workflow::default().build(); + edit(w["jobs"]["t"]["steps"].as_array_mut().unwrap()); + let found = check_workflow(&w, &RUNTIME).join("\n"); + assert!(found.contains(want), "{name}: {found}"); + } +} + +#[test] +fn finds_configs_other_than_the_compilers() { + let after = json!({ "if": format!("(success()) && {SEAL}"), "run": "id" }); + let cases = [ + ( + "the runner as sandbox user", + json!({ "user": "runner" }), + "sandbox user \"runner\"", + vec![], + ), + ( + "root as sandbox user", + json!({ "user": "root" }), + "sandbox user \"root\"", + vec![], + ), + ( + "no sudo lock with publish steps", + json!({ "lockRunnerSudo": false }), + "lockRunnerSudo false with steps after the seal", + vec![after], + ), + ( + "another workspace", + json!({ "workspace": "/home/runner" }), + "hands off \"/home/runner\"", + vec![], + ), + ( + "a hand-off out of the workspace", + json!({ "handoff": { "workspace": "tracked", "include": ["../x"] } }), + "the hand-off", + vec![], + ), + ( + "an unknown hand-off mode", + json!({ "handoff": { "workspace": "some", "include": [] } }), + "the hand-off", + vec![], + ), + ("an extra key", json!({ "extra": 1 }), "CONFIG keys", vec![]), + ]; + for (name, change, want, publish) in cases { + let w = Workflow { + config: with(config(), change), + publish, + ..Default::default() + }; + let found = problems(w).join("\n"); + assert!(found.contains(want), "{name}: {found}"); + } +} + +/// The review's probe cases, and the values the compiler's lints check: +/// each must be found. +#[test] +fn finds_what_the_compilers_contracts_refuse() { + let sha = "a".repeat(40); + let pubstep = |step: Value| { + publish(vec![with( + json!({ "if": format!("(success()) && {SEAL}") }), + step, + )]) + }; + let cases: Vec<(&str, Value)> = vec![ + ("runner as user without sudo lock", Workflow { config: with(config(), json!({ "user": "runner", "lockRunnerSudo": false, "workspace": "/home/runner" })), publish: vec![json!({ "if": format!("(always()) && {SEAL}"), "run": "x" })], ..Default::default() }.build()), + ("an empty CONFIG", with_config(json!({})).build()), + ("a stage path with ..", sandboxed(vec![json!({ "shell": "bash", "run": format!("{EXEC} --stage x ../../home/runner/.credentials") })]).build()), + ("an unknown key on a sandboxed step", sandboxed(vec![with(wrap("sleep 1000"), json!({ "background": true }))]).build()), + ("OPENSSL_CONF for the wrapper's node", sandboxed(vec![with(wrap("id"), json!({ "env": { "OPENSSL_CONF": "/tmp/x.cnf", "RUNNER_SANDBOX_ENV": "OPENSSL_CONF" } }))]).build()), + ("an action path with ..", sandboxed(vec![json!({ "shell": format!("{EXEC} --action-path o/../../x@{sha} {{0}}"), "run": "id" })]).build()), + ("job permissions as a string", job(json!({ "permissions": "write-all" })).build()), + ("a job environment", job(json!({ "environment": "prod" })).build()), + ("workflow permissions as a string", Workflow { top: json!({ "permissions": "write-all" }), ..Default::default() }.build()), + ("jobs as a string", json!({ "jobs": "abc" })), + ("a workflow that isn't a map", json!(["jobs"])), + ("a step that isn't a map", sandboxed(vec![json!("id")]).build()), + ("a hand-off include with an expression", with_config(with(config(), json!({ "handoff": { "workspace": "tracked", "include": ["${{ github.event.issue.title }}"] } }))).build()), + ("a secret in a sandboxed run", sandboxed(vec![wrap("echo ${{ secrets.X }}")]).build()), + ("the token in a sandboxed env", sandboxed(vec![with(wrap("id"), json!({ "env": { "T": "${{ github.token }}", "RUNNER_SANDBOX_ENV": "T" } }))]).build()), + ("github.* in a sandboxed step", sandboxed(vec![wrap("echo '${{ join(github.*, ',') }}'")]).build()), + ("an unpinned publish action", pubstep(json!({ "uses": "evil/x@main" })).build()), + ("a publish step with an unknown key", pubstep(json!({ "run": "id", "services": {} })).build()), + ("a publish step with run and uses", pubstep(json!({ "run": "id", "uses": format!("o/r@{sha}") })).build()), + ("sandbox outputs in a publish run", pubstep(json!({ "run": "echo ${{ steps.out.outputs.v }}" })).build()), + ("sandbox outputs in a publish with", pubstep(json!({ "uses": format!("o/r@{sha}"), "with": { "x": "${{ toJSON(steps) }}" } })).build()), + ("sandbox outputs in working-directory", pubstep(json!({ "run": "ls", "working-directory": "${{ steps.out.outputs.dir }}" })).build()), + ("event text in a publish run", pubstep(json!({ "run": "echo '${{ github.event.issue.title }}'" })).build()), + ("event text re-expanded from env", pubstep(json!({ "run": "echo '${{ env.T }}'", "env": { "T": "${{ github.head_ref }}" } })).build()), + ("event text in github-script", pubstep(json!({ "uses": format!("actions/github-script@{sha}"), "with": { "script": "core.info('${{ github.event.comment.body }}')" } })).build()), + ]; + for (name, w) in cases { + assert!( + !check_workflow(&w, &RUNTIME).is_empty(), + "{name}: not found" + ); + } +} + +#[test] +fn every_workflow_file_is_compiled_or_a_listed_exception() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + std::fs::create_dir_all(root.join(".github/workflows")).unwrap(); + std::fs::create_dir_all(root.join("workflows")).unwrap(); + std::fs::create_dir_all(root.join("runtime")).unwrap(); + for (name, text) in RUNTIME.iter() { + std::fs::write(root.join("runtime").join(name), text).unwrap(); + } + let put = |rel: &str, text: &str| std::fs::write(root.join(rel), text).unwrap(); + put(".github/workflows/ci.yml", "on: push\n"); + put(".github/workflows/extra.YML", "on: push\n"); + put(".github/workflows/orphan.lock.yml", "on: push\n"); + put( + ".github/uncompiled-workflows", + "# comment\nci.yml # our own checks\nnoreason.yml\ngone.yml # was here\n", + ); + let found = check_tree(&Repo::open(root).unwrap()).unwrap().join("\n"); + for want in [ + "extra.YML isn't compiled", + "orphan.lock.yml has no source", + "\"noreason.yml\" has no \"# reason\"", + "lists gone.yml, which doesn't exist", + ] { + assert!(found.contains(want), "{want}: {found}"); + } + assert!(!found.contains("ci.yml isn't compiled"), "{found}"); +}