🏡 index : quine-global/quorum.git

//! What the end-to-end tests share: finding the off-the-shelf tools, and
//! rebuilders signing attestations with cosign.
#![allow(dead_code)] // each test file uses some of it

use std::path::{Path, PathBuf};
use std::process::Command;

/// A tool on PATH, or in $NAME (upper case, `-` as `_`).
pub fn tool(name: &str) -> PathBuf {
    let var = name.to_uppercase().replace('-', "_");
    if let Some(p) = std::env::var_os(&var) {
        return p.into();
    }
    std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default())
        .map(|d| d.join(name))
        .find(|p| p.is_file())
        .unwrap_or_else(|| panic!("{name} not found: `nix develop` has it, or set ${var}"))
}

/// cosign, offline: a signing config with no transparency log, timestamp
/// authority or Fulcio, and a dead proxy, so nothing is ever sent anywhere
/// (cosign still tries to read Sigstore's TUF root, and carries on).
fn cosign(dir: &Path, args: &[&str]) {
    let o = Command::new(tool("cosign"))
        .args(args)
        .current_dir(dir)
        .env("COSIGN_PASSWORD", "")
        .env("HTTPS_PROXY", "http://127.0.0.1:9")
        .env("HTTP_PROXY", "http://127.0.0.1:9")
        .env("NO_PROXY", "")
        .output()
        .unwrap();
    assert!(
        o.status.success(),
        "cosign {args:?}: {}{}",
        String::from_utf8_lossy(&o.stdout),
        String::from_utf8_lossy(&o.stderr)
    );
}

/// A rebuilder's cosign key pair, keys/<who>.key and .pub (ECDSA P-256), and
/// the public key published in the feed as builder-keys/<who>.pem.
pub fn rebuilder_key(dir: &Path, who: &str) {
    std::fs::create_dir_all(dir.join("keys")).unwrap();
    std::fs::create_dir_all(dir.join("feed/builder-keys")).unwrap();
    cosign(
        dir,
        &[
            "generate-key-pair",
            "--output-key-prefix",
            &format!("keys/{who}"),
        ],
    );
    std::fs::copy(
        dir.join(format!("keys/{who}.pub")),
        dir.join(format!("feed/builder-keys/{who}.pem")),
    )
    .unwrap();
}

/// `who` attests `files` for `release`: `quorum statement`, signed by
/// cosign into feed/<release>/<who>/attestation.sigstore.json.
pub fn attest(dir: &Path, who: &str, release: &str, files: &[&str]) {
    let sc = dir.join("signing-config.json");
    if !sc.exists() {
        cosign(
            dir,
            &["signing-config", "create", "--out", "signing-config.json"],
        );
    }
    let st = dir.join(format!("statement-{who}.json"));
    let o = Command::new(env!("CARGO_BIN_EXE_quorum"))
        .args(["statement", "--release", release, "--out"])
        .arg(&st)
        .args(files)
        .output()
        .unwrap();
    assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr));
    let out = dir.join(format!("feed/{release}/{who}"));
    std::fs::create_dir_all(&out).unwrap();
    let _ = std::fs::remove_file(out.join("attestation.dsse.json"));
    cosign(
        dir,
        &[
            "attest-blob",
            "--statement",
            &st.to_string_lossy(),
            "--key",
            &format!("keys/{who}.key"),
            "--signing-config",
            "signing-config.json",
            "--bundle",
            &out.join("attestation.sigstore.json").to_string_lossy(),
            "-y",
        ],
    );
}

/// An Ed25519 PKCS#8 key pair for TUF: keys/<name>.pem, and .der (what
/// tuftool takes).
pub fn ed25519_key(dir: &Path, name: &str) {
    use ed25519_dalek::pkcs8::{EncodePrivateKey, spki::der::pem::LineEnding};
    let mut seed = [0u8; 32];
    getrandom::fill(&mut seed).unwrap();
    let sk = ed25519_dalek::SigningKey::from_bytes(&seed);
    std::fs::create_dir_all(dir.join("keys")).unwrap();
    std::fs::write(
        dir.join(format!("keys/{name}.pem")),
        sk.to_pkcs8_pem(LineEnding::LF).unwrap().as_bytes(),
    )
    .unwrap();
    std::fs::write(
        dir.join(format!("keys/{name}.der")),
        sk.to_pkcs8_der().unwrap().as_bytes(),
    )
    .unwrap();
}