From d44ac731840bd96e564daf5971e63be2409924ef Mon Sep 17 00:00:00 2001 From: Rodrigo Mompo Redoli Date: Fri, 20 Nov 2026 19:34:27 +0000 Subject: [PATCH] Check build provenance in proofline update with PROOFLINE_VERIFY_PROVENANCE=1 --- README.md | 2 + src/update.rs | 102 ++++++++++++++++++++++++++- src/update/tests.rs | 167 +++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 268 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index c56770c..67b7e71 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,8 @@ This repository is the published distribution of the Proofline CLI. `openapi.pub On Linux and macOS, install the CLI with `curl -fsSL https://proofline.sh/cli | sh`, then run `proofline login`. Run `proofline setup` to open the browser organization selector. Pass `--organization NAME` to open that GitHub organization's installation page, or `--print` to only print its address. Cloud trust and connection changes still require a signed-in administrator browser. +`proofline update` replaces a binary in the installer directory with the newest release after checking it against that release's `SHA256SUMS`. With `PROOFLINE_VERIFY_PROVENANCE=1`, it also runs `gh attestation verify` on the archive and replaces the binary only if GitHub signed the archive for this repository's `release.yml`, on a GitHub-hosted runner, at that version's `vX.Y.Z` tag or at `main`. The check needs the [GitHub CLI](https://cli.github.com/) signed in to github.com. Without `gh`, the update downloads nothing. If the check fails, it keeps the installed binary. Any value other than `1` or `0` is refused. + `proofline completions SHELL` prints a completion script for `zsh`, `bash`, `fish`, `powershell`, or `elvish` without signing in or making a network call. For example, add `source <(proofline completions zsh)` to `~/.zshrc`. ### Windows installation diff --git a/src/update.rs b/src/update.rs index d001d62..533e7e5 100644 --- a/src/update.rs +++ b/src/update.rs @@ -1,5 +1,6 @@ //! Official release installation and best-effort discovery between invocations. +use std::ffi::OsStr; use std::fs::{self, File}; use std::io::{IsTerminal as _, Read as _}; use std::path::{Path, PathBuf}; @@ -373,13 +374,94 @@ fn verify(archive: &[u8], sums: &[u8], name: &str) -> anyhow::Result<()> { Ok(()) } +/// A build provenance check by the GitHub CLI, as `install.sh` runs it with +/// `PROOFLINE_VERIFY_PROVENANCE=1`. +struct Provenance { + gh: PathBuf, + version: String, +} + +/// `PROOFLINE_VERIFY_PROVENANCE`: unset, empty or `0` is off and `1` is on. +/// Anything else is refused, so a misspelt value cannot turn the check off. +fn provenance_requested(value: Option<&OsStr>) -> anyhow::Result { + match value.map(OsStr::to_str) { + None | Some(Some("" | "0")) => Ok(false), + Some(Some("1")) => Ok(true), + _ => bail!("PROOFLINE_VERIFY_PROVENANCE must be 1 or 0; nothing was installed"), + } +} + +/// The first executable `name` on `path`, resolved once so the check runs the +/// program that was found. +fn find_program(name: &str, path: Option<&OsStr>) -> Option { + std::env::split_paths(path?) + .filter(|directory| directory.is_absolute()) + .map(|directory| directory.join(name)) + .find(|candidate| { + fs::metadata(candidate).is_ok_and(|metadata| { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt as _; + metadata.is_file() && metadata.permissions().mode() & 0o111 != 0 + } + #[cfg(not(unix))] + { + metadata.is_file() + } + }) + }) +} + +/// The signing certificate's identity: this repository's release workflow, at +/// the release's tag or at main, the two refs a release is published from. +fn provenance_identity(version: &str) -> String { + format!( + r"^https://github\.com/prooflinedev/cli/\.github/workflows/release\.yml@refs/(tags/v{}|heads/main)$", + version.replace('.', r"\.") + ) +} + +fn verify_provenance(provenance: &Provenance, archive: &[u8], name: &str) -> anyhow::Result<()> { + // `gh` reads a file, so the verified bytes are the ones installed next. + let directory = tempfile::tempdir()?; + let path = directory.path().join(name); + fs::write(&path, archive)?; + crate::say(&format!( + "checking build provenance of {name} with gh attestation verify" + )); + let status = Command::new(&provenance.gh) + .args(["attestation", "verify"]) + .arg(&path) + .args(["--hostname", "github.com", "--repo", "prooflinedev/cli"]) + .args([ + "--cert-identity-regex", + &provenance_identity(&provenance.version), + ]) + .arg("--deny-self-hosted-runners") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .status() + .context("could not run the GitHub CLI (gh); nothing was installed")?; + if !status.success() { + bail!( + "{name} has no build provenance from prooflinedev/cli's release workflow for {}; nothing was installed; run 'gh auth login' if gh is not signed in", + provenance.version + ); + } + Ok(()) +} + fn verify_and_replace( archive: &[u8], sums: &[u8], name: &str, destination: &Path, + provenance: Option<&Provenance>, ) -> anyhow::Result<()> { verify(archive, sums, name)?; + if let Some(provenance) = provenance { + verify_provenance(provenance, archive, name)?; + } replace(archive, destination) } @@ -422,6 +504,16 @@ fn replace(archive: &[u8], destination: &Path) -> anyhow::Result<()> { /// Updates an official installer location after verifying the pinned archive. pub(crate) async fn install() -> anyhow::Result<()> { + // A provenance check that cannot run downloads nothing, as in install.sh. + let gh = if provenance_requested(std::env::var_os("PROOFLINE_VERIFY_PROVENANCE").as_deref())? { + Some( + find_program("gh", std::env::var_os("PATH").as_deref()).context( + "PROOFLINE_VERIFY_PROVENANCE=1 needs the GitHub CLI (gh), which is not on PATH; nothing was installed", + )?, + ) + } else { + None + }; let (destination, target) = tokio::task::spawn_blocking(|| Ok::<_, anyhow::Error>((destination()?, target()?))) .await??; @@ -438,8 +530,14 @@ pub(crate) async fn install() -> anyhow::Result<()> { let release = format!("{RELEASES}/download/{version}"); let sums = download(&client, &format!("{release}/SHA256SUMS"), 4096).await?; let archive = download(&client, &format!("{release}/{name}"), MAX_ARCHIVE).await?; - tokio::task::spawn_blocking(move || verify_and_replace(&archive, &sums, &name, &destination)) - .await??; + let provenance = gh.map(|gh| Provenance { + gh, + version: version.clone(), + }); + tokio::task::spawn_blocking(move || { + verify_and_replace(&archive, &sums, &name, &destination, provenance.as_ref()) + }) + .await??; crate::say(&format!("updated proofline to {version}")); Ok(()) } diff --git a/src/update/tests.rs b/src/update/tests.rs index d7387c5..4e841e8 100644 --- a/src/update/tests.rs +++ b/src/update/tests.rs @@ -30,7 +30,14 @@ fn integrity_and_archive_refusals_preserve_installed_binary() { format!("{digest} other.tar.gz\n"), ] { assert!( - verify_and_replace(&good, invalid.as_bytes(), "release.tar.gz", &destination).is_err() + verify_and_replace( + &good, + invalid.as_bytes(), + "release.tar.gz", + &destination, + None + ) + .is_err() ); assert_eq!(fs::read(&destination).unwrap(), b"old binary"); } @@ -372,3 +379,161 @@ fn installed_symlink_is_reported_as_a_symlink() { assert!(error.contains("symbolic link"), "{executable:?}: {error}"); } } + +#[test] +fn provenance_setting_accepts_only_one_or_zero() { + for off in [None, Some(""), Some("0")] { + assert!(!provenance_requested(off.map(OsStr::new)).unwrap()); + } + assert!(provenance_requested(Some(OsStr::new("1"))).unwrap()); + for invalid in ["yes", "true", "on", " 1", "2"] { + let error = provenance_requested(Some(OsStr::new(invalid))).unwrap_err(); + assert!(error.to_string().contains("must be 1 or 0"), "{invalid}"); + } +} + +#[test] +fn provenance_identity_pins_the_release_workflow_and_tag() { + assert_eq!( + provenance_identity("0.3.9"), + r"^https://github\.com/prooflinedev/cli/\.github/workflows/release\.yml@refs/(tags/v0\.3\.9|heads/main)$" + ); +} + +#[cfg(unix)] +mod provenance { + use super::*; + use std::os::unix::fs::PermissionsExt as _; + + fn executable(path: &Path, contents: &str) { + fs::write(path, contents).unwrap(); + fs::set_permissions(path, fs::Permissions::from_mode(0o755)).unwrap(); + } + + /// A stand-in `gh` that records its arguments and the file it was given. + fn fake_gh(directory: &Path, status: i32) -> PathBuf { + let gh = directory.join("gh"); + let log = directory.join("gh.log"); + let seen = directory.join("gh.archive"); + executable( + &gh, + &format!( + "#!/bin/sh\nprintf '%s\\n' \"$@\" > '{}'\ncp \"$3\" '{}'\nexit {status}\n", + log.display(), + seen.display() + ), + ); + gh + } + + fn release() -> (Vec, String) { + let good = archive("proofline", tar::EntryType::Regular, b"new binary"); + let sums = format!("{:x} release.tar.gz\n", Sha256::digest(&good)); + (good, sums) + } + + #[test] + fn programs_are_found_only_as_executable_files_on_absolute_path_entries() { + let directory = tempfile::tempdir().unwrap(); + let bin = directory.path().join("bin"); + fs::create_dir_all(bin.join("gh-directory/gh")).unwrap(); + fs::write(bin.join("plain"), b"not executable").unwrap(); + executable(&bin.join("gh"), "#!/bin/sh\n"); + let path = std::env::join_paths([Path::new("relative"), &bin]).unwrap(); + assert_eq!(find_program("gh", Some(&path)), Some(bin.join("gh"))); + assert_eq!(find_program("plain", Some(&path)), None); + let only_directory = std::env::join_paths([bin.join("gh-directory")]).unwrap(); + assert_eq!(find_program("gh", Some(&only_directory)), None); + assert_eq!(find_program("gh", None), None); + executable(&directory.path().join("relative-gh"), "#!/bin/sh\n"); + assert_eq!(find_program("gh", Some(OsStr::new("relative"))), None); + } + + #[test] + fn verified_provenance_checks_the_downloaded_bytes_before_replacing() { + let directory = tempfile::tempdir().unwrap(); + let destination = directory.path().join("proofline"); + fs::write(&destination, b"old binary").unwrap(); + let (good, sums) = release(); + let provenance = Provenance { + gh: fake_gh(directory.path(), 0), + version: "0.3.9".to_owned(), + }; + verify_and_replace( + &good, + sums.as_bytes(), + "release.tar.gz", + &destination, + Some(&provenance), + ) + .unwrap(); + assert_eq!(fs::read(&destination).unwrap(), b"new binary"); + assert_eq!(fs::read(directory.path().join("gh.archive")).unwrap(), good); + + let log = fs::read_to_string(directory.path().join("gh.log")).unwrap(); + let arguments: Vec<_> = log.lines().collect(); + assert_eq!(arguments[..2], ["attestation", "verify"]); + assert!(arguments[2].ends_with("/release.tar.gz")); + assert_eq!( + arguments[3..], + [ + "--hostname", + "github.com", + "--repo", + "prooflinedev/cli", + "--cert-identity-regex", + &provenance_identity("0.3.9"), + "--deny-self-hosted-runners", + ] + ); + } + + #[test] + fn failed_provenance_keeps_the_installed_binary() { + let directory = tempfile::tempdir().unwrap(); + let destination = directory.path().join("proofline"); + fs::write(&destination, b"old binary").unwrap(); + let (good, sums) = release(); + let provenance = Provenance { + gh: fake_gh(directory.path(), 1), + version: "0.3.9".to_owned(), + }; + let error = verify_and_replace( + &good, + sums.as_bytes(), + "release.tar.gz", + &destination, + Some(&provenance), + ) + .unwrap_err() + .to_string(); + assert!(error.contains("has no build provenance"), "{error}"); + assert!(error.contains("nothing was installed"), "{error}"); + assert_eq!(fs::read(&destination).unwrap(), b"old binary"); + } + + #[test] + fn checksum_mismatch_stops_before_provenance_check() { + let directory = tempfile::tempdir().unwrap(); + let destination = directory.path().join("proofline"); + fs::write(&destination, b"old binary").unwrap(); + let (good, _) = release(); + let wrong = format!("{} release.tar.gz\n", "0".repeat(64)); + let provenance = Provenance { + gh: fake_gh(directory.path(), 0), + version: "0.3.9".to_owned(), + }; + assert!( + verify_and_replace( + &good, + wrong.as_bytes(), + "release.tar.gz", + &destination, + Some(&provenance), + ) + .is_err() + ); + assert!(!directory.path().join("gh.log").exists()); + assert_eq!(fs::read(&destination).unwrap(), b"old binary"); + } +}