🏡 index : quine-global/quorum.git

//! quorum: trust a file when enough rebuilders you chose reproduced it.
//!
//! Each project has a feed (where its rebuilders publish signed attestations
//! of the hashes they built) and, in your trust store, the rebuilders you
//! pinned and a threshold. A file passes when at least `threshold` pinned
//! rebuilders signed its exact hash and none signed a different one.

mod cjson;
mod dsse;
mod feed;
mod keyring;
mod note;
mod pgp;
mod source;
mod store;
mod sums;
mod time;
mod tlog;
mod tuf;

use std::io::{BufRead, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::time::SystemTime;

use anyhow::{Context, Result, bail};
use clap::{Parser, Subcommand};

use feed::{Attestation, FeedKind};
use keyring::PubKey;
use pgp::SigStatus;
use source::Source;
use store::{Project, ProjectFile, Rebuilder};

#[derive(Parser)]
#[command(version, about)]
struct Cli {
    /// Trust store [default: %APPDATA%\quorum, or $QUORUM_HOME]
    #[arg(long, global = true)]
    home: Option<PathBuf>,
    #[command(subcommand)]
    cmd: Cmd,
}

#[derive(Subcommand)]
enum Cmd {
    /// Check files against the project's pinned rebuilders
    Check {
        /// Project [default: the only one]
        #[arg(short, long)]
        project: Option<String>,
        #[arg(required = true)]
        files: Vec<PathBuf>,
        /// The release [default: from the file name, with the project's release_prefix]
        #[arg(long)]
        release: Option<String>,
        /// Check the file under this name [default: its file name]
        #[arg(long = "as")]
        as_name: Option<String>,
        /// Count OpenPGP signatures from keys that have expired since (never revoked ones)
        #[arg(long)]
        allow_expired: bool,
        /// Check a release that isn't the latest (for a project with TUF)
        #[arg(long)]
        allow_old: bool,
    },
    /// Manage projects: which feed their attestations come from
    Project {
        #[command(subcommand)]
        cmd: ProjectCmd,
    },
    /// Manage which rebuilders you trust for a project
    Trust {
        /// Project [default: the only one]
        #[arg(short, long, global = true)]
        project: Option<String>,
        #[command(subcommand)]
        cmd: TrustCmd,
    },
    /// Transparency: keep, witness or monitor a log of attestations
    Log {
        #[command(subcommand)]
        cmd: LogCmd,
    },
    /// Publish freshness: a TUF repository saying which release is the latest
    Tuf {
        #[command(subcommand)]
        cmd: TufCmd,
    },
    /// Write the in-toto Statement that you rebuilt these files, for cosign
    /// to sign: `cosign attest-blob --statement <it> --key <yours> --bundle
    /// <release>/<your name>/attestation.sigstore.json`
    Statement {
        #[arg(long)]
        release: String,
        /// Where to write it [default: standard output]
        #[arg(long)]
        out: Option<PathBuf>,
        #[arg(required = true)]
        files: Vec<PathBuf>,
    },
}

#[derive(Subcommand)]
#[allow(clippy::large_enum_variant)] // parsed once
enum ProjectCmd {
    /// Add a project
    Add {
        name: String,
        /// A known project's settings: bitcoin-core
        #[arg(long, conflicts_with_all = ["feed", "source"])]
        preset: Option<String>,
        #[arg(long, value_enum, required_unless_present = "preset")]
        feed: Option<FeedKind>,
        /// The feed's base URL (https://…) or a local directory
        #[arg(long, required_unless_present = "preset")]
        source: Option<String>,
        /// Infer the release from file names starting with this
        #[arg(long)]
        release_prefix: Option<String>,
        /// The project's TUF repository (https://… or a directory, holding metadata/ and targets/), for freshness
        #[arg(long)]
        tuf: Option<String>,
        /// The SHA-256 of its 1.root.json, from a source other than the repository
        #[arg(long, requires = "tuf")]
        tuf_root_sha256: Option<String>,
        /// Pin the TUF root without asking (only sensible with --tuf-root-sha256)
        #[arg(long)]
        yes: bool,
        /// A transparency log (https://… or a directory): attestations count only if logged
        #[arg(long, requires = "log_key")]
        log: Option<String>,
        /// The log's verifier key (name+hash+key)
        #[arg(long, requires = "log")]
        log_key: Option<String>,
        /// A witness's verifier key (repeat for several)
        #[arg(long = "witness", requires = "log")]
        witnesses: Vec<String>,
        /// How many witnesses must have cosigned [default: all of them]
        #[arg(long, requires = "log")]
        witness_threshold: Option<usize>,
    },
    List,
    Remove {
        name: String,
    },
}

#[derive(Subcommand)]
enum TrustCmd {
    /// Show pinned rebuilders and the threshold
    List,
    /// Pin a rebuilder: fetch their key from the feed (or --key-file) and pin its fingerprint
    Add {
        name: String,
        /// The fingerprint you expect, from a source other than the feed; refuses a mismatch
        #[arg(long)]
        fingerprint: Option<String>,
        /// Take the key from this file instead of the feed
        #[arg(long)]
        key_file: Option<PathBuf>,
        /// Pin without asking (only sensible with --fingerprint)
        #[arg(long)]
        yes: bool,
    },
    Remove {
        name: String,
    },
    /// How many pinned rebuilders must agree
    Threshold {
        n: usize,
    },
    /// Re-fetch pinned rebuilders' keys from the feed; fingerprints must not change
    Refresh,
}

fn main() -> ExitCode {
    match run(Cli::parse()) {
        Ok(true) => ExitCode::SUCCESS,
        Ok(false) => ExitCode::from(1),
        Err(e) => {
            eprintln!("error: {e:#}");
            ExitCode::from(2)
        }
    }
}

fn run(cli: Cli) -> Result<bool> {
    let home = match cli.home {
        Some(h) => h,
        None => store::default_home()?,
    };
    match cli.cmd {
        Cmd::Check {
            project,
            files,
            release,
            as_name,
            allow_expired,
            allow_old,
        } => {
            if as_name.is_some() && files.len() > 1 {
                bail!("--as needs a single file");
            }
            let p = open_project(&home, project.as_deref())?;
            let mut ok = true;
            for f in &files {
                ok &= check(
                    &p,
                    f,
                    release.as_deref(),
                    as_name.as_deref(),
                    allow_expired,
                    allow_old,
                )?;
            }
            Ok(ok)
        }
        Cmd::Project { cmd } => project_cmd(&home, cmd).map(|_| true),
        Cmd::Trust { project, cmd } => {
            let mut p = open_project(&home, project.as_deref())?;
            trust_cmd(&mut p, cmd).map(|_| true)
        }
        Cmd::Tuf { cmd } => tuf_cmd(cmd).map(|_| true),
        Cmd::Log { cmd } => log_cmd(&home, cmd),
        Cmd::Statement {
            release,
            out,
            files,
        } => statement(&release, out.as_deref(), &files).map(|_| true),
    }
}

fn open_project(home: &Path, name: Option<&str>) -> Result<Project> {
    match name {
        Some(n) => Project::open(home, n),
        None => match store::list(home)?.as_slice() {
            [only] => Project::open(home, only),
            [] => bail!("no projects yet: `quorum project add …`"),
            many => bail!("several projects ({}): pass --project", many.join(", ")),
        },
    }
}

fn project_cmd(home: &Path, cmd: ProjectCmd) -> Result<()> {
    match cmd {
        ProjectCmd::Add {
            name,
            preset,
            feed,
            source,
            release_prefix,
            tuf,
            tuf_root_sha256,
            yes,
            log,
            log_key,
            witnesses,
            witness_threshold,
        } => {
            let log = match (log, log_key) {
                (Some(url), Some(key)) => {
                    let cfg = tlog::LogConfig {
                        url,
                        key,
                        witness_threshold: witness_threshold.unwrap_or(witnesses.len()),
                        witnesses,
                    };
                    if cfg.witness_threshold > cfg.witnesses.len() {
                        bail!(
                            "--witness-threshold {} but {} witness(es)",
                            cfg.witness_threshold,
                            cfg.witnesses.len()
                        );
                    }
                    let v = tlog::fetch(&cfg, None).context("checking the transparency log")?;
                    println!(
                        "Log {}: {} entries, signed and cosigned as required.",
                        v.checkpoint.origin(),
                        v.checkpoint.size()
                    );
                    Some(cfg)
                }
                _ => None,
            };
            let file = match preset.as_deref() {
                Some("bitcoin-core") => ProjectFile {
                    feed: FeedKind::GuixSigs,
                    source: source::GUIX_SIGS_URL.into(),
                    release_prefix: Some(release_prefix.unwrap_or_else(|| "bitcoin-".into())),
                    threshold: None,
                    tuf: tuf.clone(),
                    log: log.clone(),
                    rebuilders: vec![],
                },
                Some(other) => bail!("no preset {other:?} (there is: bitcoin-core)"),
                None => ProjectFile {
                    feed: feed.context("--feed")?,
                    source: source.context("--source")?,
                    release_prefix,
                    threshold: None,
                    tuf: tuf.clone(),
                    log: log.clone(),
                    rebuilders: vec![],
                },
            };
            // Fetch and check the TUF root before creating anything.
            let root = match &tuf {
                Some(url) => {
                    let src = tuf::metadata(url);
                    let data = src
                        .get("1.root.json")?
                        .with_context(|| format!("no 1.root.json in {}", src.describe()))?;
                    let pin = tuf::root_pin(&data);
                    println!("TUF root 1.root.json from {}:", src.describe());
                    println!("  sha256 {pin}");
                    println!("  {}", tuf::describe_root(&data)?);
                    match tuf_root_sha256.as_deref() {
                        Some(want) if want.eq_ignore_ascii_case(&pin) => {}
                        Some(want) => bail!("its SHA-256 isn't {want}; not adding {name}"),
                        None if yes => {}
                        None => {
                            println!(
                                "Check the SHA-256 somewhere other than the repository: this root decides\n\
                                 who may say which release is the latest."
                            );
                            if !confirm("Pin this TUF root?")? {
                                bail!("not added");
                            }
                        }
                    }
                    Some(data)
                }
                None => None,
            };
            let p = Project::create(home, &name, file)?;
            if let Some(data) = root
                && let Err(e) = tuf::pin_root(&p.tuf_dir(), &data)
            {
                let _ = Project::remove(home, &name);
                return Err(e.context("pinning the TUF root"));
            }
            println!(
                "Added {} ({:?} feed at {}). Next: `quorum trust -p {} add <rebuilder>`.",
                p.name, p.file.feed, p.file.source, p.name
            );
        }
        ProjectCmd::List => {
            for n in store::list(home)? {
                let p = Project::open(home, &n)?;
                println!(
                    "{:<20} {:?}  {}  {} rebuilder(s), threshold {}",
                    n,
                    p.file.feed,
                    p.file.source,
                    p.file.rebuilders.len(),
                    p.threshold()
                );
            }
        }
        ProjectCmd::Remove { name } => {
            Project::remove(home, &name)?;
            println!("Removed {name} and its pinned keys.");
        }
    }
    Ok(())
}

fn normalize_fpr(s: &str) -> String {
    s.chars()
        .filter(|c| !c.is_whitespace())
        .collect::<String>()
        .to_ascii_uppercase()
}

fn same_fpr(a: &str, b: &str) -> bool {
    a.eq_ignore_ascii_case(b)
}

fn pinned_keys(p: &Project, r: &Rebuilder) -> Result<Vec<PubKey>> {
    let keys = keyring::parse(&p.read_key(&r.name)?)?;
    Ok(keys
        .into_iter()
        .filter(|k| r.fingerprints.iter().any(|f| same_fpr(f, &k.fingerprint())))
        .collect())
}

fn trust_cmd(p: &mut Project, cmd: TrustCmd) -> Result<()> {
    let src = Source::parse(&p.file.source);
    let now = SystemTime::now();
    match cmd {
        TrustCmd::List => {
            println!(
                "Project:   {} ({:?} feed at {})",
                p.name, p.file.feed, p.file.source
            );
            println!(
                "Threshold: {} pinned rebuilder(s) must agree",
                p.threshold()
            );
            if p.file.rebuilders.is_empty() {
                println!(
                    "No pinned rebuilders yet: `quorum trust -p {} add <name>`.",
                    p.name
                );
            }
            for r in &p.file.rebuilders {
                let note = match pinned_keys(p, r) {
                    Ok(keys) => keys
                        .iter()
                        .map(|k| k.validity(now))
                        .collect::<Vec<_>>()
                        .join("; "),
                    Err(e) => format!("key unreadable: {e:#}"),
                };
                println!("  {:<20} {}  {}", r.name, r.fingerprints.join(","), note);
            }
        }
        TrustCmd::Add {
            name,
            fingerprint,
            key_file,
            yes,
        } => {
            store::check_name("rebuilder name", &name)?;
            if p.rebuilder(&name).is_some() {
                bail!("{name} is already pinned (`trust refresh` updates keys)");
            }
            let (data, from) = match &key_file {
                Some(f) => (
                    std::fs::read(f).with_context(|| format!("reading {}", f.display()))?,
                    f.display().to_string(),
                ),
                None => {
                    let path = p.file.feed.key_path(&name);
                    let data = src
                        .get(&path)?
                        .with_context(|| format!("no {path} in {}", src.describe()))?;
                    (data, format!("{path} from {}", src.describe()))
                }
            };
            let keys = keyring::parse(&data)?;
            println!("{from}:");
            for k in &keys {
                println!(
                    "  {}  {}  {}",
                    k.fingerprint(),
                    k.kind(),
                    k.label().unwrap_or("")
                );
            }
            let pinned: Vec<String> = match fingerprint.as_deref().map(normalize_fpr) {
                Some(want) => {
                    let Some(k) = keys.iter().find(|k| same_fpr(&k.fingerprint(), &want)) else {
                        bail!("none of these keys has fingerprint {want}; not pinning {name}");
                    };
                    vec![k.fingerprint()]
                }
                None => keys.iter().map(PubKey::fingerprint).collect(),
            };
            // One key, one vote: the threshold counts people, not names.
            for other in &p.file.rebuilders {
                if let Some(f) = pinned
                    .iter()
                    .find(|f| other.fingerprints.iter().any(|o| same_fpr(o, f)))
                {
                    bail!(
                        "{f} is already pinned as {}; a key can only count once",
                        other.name
                    );
                }
            }
            if !yes {
                println!(
                    "Check the fingerprint(s) somewhere other than the feed (the rebuilder,\n\
                     their website, a key you already hold): pinning means trusting what they sign."
                );
                if !confirm(&format!("Pin {name} with {}?", pinned.join(", ")))? {
                    bail!("not pinned");
                }
            }
            p.write_key(&name, &data)?;
            p.file.rebuilders.push(Rebuilder {
                name: name.clone(),
                fingerprints: pinned,
            });
            p.save()?;
            println!(
                "Pinned {name}. {} rebuilder(s), threshold {}.",
                p.file.rebuilders.len(),
                p.threshold()
            );
        }
        TrustCmd::Remove { name } => {
            let before = p.file.rebuilders.len();
            p.file.rebuilders.retain(|r| r.name != name);
            if p.file.rebuilders.len() == before {
                bail!("{name} isn't pinned");
            }
            p.save()?;
            let _ = std::fs::remove_file(p.key_path(&name));
            println!("Removed {name}.");
        }
        TrustCmd::Threshold { n } => {
            if n == 0 {
                bail!("the threshold must be at least 1");
            }
            p.file.threshold = Some(n);
            p.save()?;
            println!("Threshold set to {n}.");
            if n > p.file.rebuilders.len() {
                println!(
                    "Note: only {} rebuilder(s) are pinned, so nothing can pass yet.",
                    p.file.rebuilders.len()
                );
            }
        }
        TrustCmd::Refresh => {
            let mut failed = false;
            for r in p.file.rebuilders.clone() {
                let res = (|| -> Result<String> {
                    let data = src
                        .get(&p.file.feed.key_path(&r.name))?
                        .context("no longer in the feed")?;
                    let keys = keyring::parse(&data)?;
                    if let Some(missing) = r
                        .fingerprints
                        .iter()
                        .find(|f| !keys.iter().any(|k| same_fpr(&k.fingerprint(), f)))
                    {
                        bail!("pinned key {missing} is gone; kept the cached key");
                    }
                    p.write_key(&r.name, &data)?;
                    Ok(keys
                        .iter()
                        .filter(|k| r.fingerprints.iter().any(|f| same_fpr(f, &k.fingerprint())))
                        .map(|k| k.validity(now))
                        .collect::<Vec<_>>()
                        .join("; "))
                })();
                match res {
                    Ok(note) => println!("  {:<20} updated  {note}", r.name),
                    Err(e) => {
                        failed = true;
                        println!("  {:<20} NOT updated: {e:#}", r.name)
                    }
                }
            }
            if failed {
                bail!("some keys weren't refreshed");
            }
        }
    }
    Ok(())
}

fn confirm(question: &str) -> Result<bool> {
    print!("{question} [y/N] ");
    std::io::stdout().flush()?;
    let mut line = String::new();
    std::io::stdin().lock().read_line(&mut line)?;
    Ok(matches!(line.trim(), "y" | "Y" | "yes"))
}

// ── checking ────────────────────────────────────────────────────────────────

enum Verdict {
    Match(SigStatus),
    Mismatch(String),
    NotListed,
    NoAttestation,
    /// With the key(s) the attestation says it was signed by.
    BadSignature(Vec<String>),
    /// A rebuild attestation for another release, moved here.
    WrongRelease(String),
    Error(String),
}

fn check(
    p: &Project,
    file: &Path,
    release: Option<&str>,
    as_name: Option<&str>,
    allow_expired: bool,
    allow_old: bool,
) -> Result<bool> {
    let name = match as_name {
        Some(n) => n.to_string(),
        None => file
            .file_name()
            .context("not a file")?
            .to_string_lossy()
            .into_owned(),
    };
    let release = match release {
        Some(r) => r.to_string(),
        None => p
            .file
            .release_prefix
            .as_deref()
            .and_then(|pre| sums::release_from_name(&name, pre))
            .with_context(|| format!("can't tell the release from {name:?}; pass --release"))?,
    };
    store::check_name("release", &release)?;
    let threshold = p.threshold();
    if p.file.rebuilders.is_empty() {
        bail!(
            "no pinned rebuilders: `quorum trust -p {} add <name>`",
            p.name
        );
    }
    if threshold > p.file.rebuilders.len() {
        bail!(
            "threshold {threshold} but only {} pinned rebuilder(s): pin more, or lower it with `trust threshold`",
            p.file.rebuilders.len()
        );
    }

    let src = Source::parse(&p.file.source);
    let hash = sums::sha256_file(file)?;
    println!("{name}");
    println!("  sha256  {hash}");
    println!(
        "  {} {release}, attestations from {}",
        p.name,
        src.describe()
    );
    if let Some(url) = &p.file.tuf {
        match tuf::update(
            &p.tuf_dir(),
            &tuf::metadata(url),
            &tuf::targets(url),
            SystemTime::now(),
        ) {
            Ok(f) => {
                println!(
                    "  latest  {} (TUF root v{}, timestamp valid until {})",
                    f.latest,
                    f.root_version,
                    time::format(f.timestamp_expires)
                );
                if f.latest != release {
                    if !allow_old {
                        println!(
                            "FAIL: OUTDATED: {release} isn't the latest {} release; {} is. Get {}, or pass \
                             --allow-old to check an older release on purpose.",
                            p.name, f.latest, f.latest
                        );
                        return Ok(false);
                    }
                    println!(
                        "  OLD RELEASE: {release} isn't the latest ({}); checking it anyway",
                        f.latest
                    );
                }
            }
            Err(e) => {
                println!(
                    "FAIL: can't tell which {} release is the latest: {e:#}",
                    p.name
                );
                return Ok(false);
            }
        }
    }

    let now = SystemTime::now();
    // Every key (and subkey) of every pinned rebuilder, to say whose a stray signature is.
    let owners: Vec<(String, String)> = p
        .file
        .rebuilders
        .iter()
        .flat_map(|r| {
            pinned_keys(p, r)
                .unwrap_or_default()
                .iter()
                .flat_map(PubKey::all_fingerprints)
                .map(|f| (f, r.name.clone()))
                .collect::<Vec<_>>()
        })
        .collect();
    let whose = |id: &str| -> String {
        let found = owners.iter().find(|(f, _)| {
            !id.is_empty()
                && (same_fpr(f, id) || f.to_ascii_uppercase().ends_with(&id.to_ascii_uppercase()))
        });
        match found {
            Some((_, owner)) => format!("{id}, {owner}'s key"),
            None => id.to_string(),
        }
    };

    let logged = match &p.file.log {
        Some(cfg) => match tlog::fetch(cfg, Some(&p.log_state_path())) {
            Ok(v) => {
                let by = if v.witnesses.is_empty() {
                    String::new()
                } else {
                    let names: Vec<&str> = v.witnesses.iter().map(|(n, _)| n.as_str()).collect();
                    format!(", cosigned by {}", names.join(", "))
                };
                println!(
                    "  log     {}: {} entries{by}",
                    v.checkpoint.origin(),
                    v.checkpoint.size()
                );
                Some(v.contains())
            }
            Err(e) => {
                println!("FAIL: the transparency log doesn't check out: {e:#}");
                return Ok(false);
            }
        },
        None => None,
    };

    let mut counted = 0usize;
    let mut conflicts = 0usize;
    for r in &p.file.rebuilders {
        let (verdict, leaf) = judge(p, &src, r, &release, &name, &hash, now);
        let signed =
            |c: &Option<SystemTime>| c.map(|c| format!("signed {}", date(c))).unwrap_or_default();
        let (label, detail, counts) = match &verdict {
            Verdict::Match(SigStatus::Good { created }) => ("OK", signed(created), true),
            Verdict::Match(SigStatus::Expired {
                created,
                made_while_valid,
            }) => {
                let counts = allow_expired && *made_while_valid;
                let why = if !made_while_valid {
                    ", after the key expired: never counts"
                } else if !allow_expired {
                    ", key expired since: not counted without --allow-expired"
                } else {
                    ", key expired since"
                };
                (
                    if counts { "OK" } else { "EXPIRED KEY" },
                    format!("{}{why}", signed(created)),
                    counts,
                )
            }
            Verdict::Match(SigStatus::Revoked) => ("REVOKED KEY", "never counts".into(), false),
            Verdict::Match(SigStatus::Bad) => (
                "BAD SIGNATURE",
                "not signed by the pinned key".into(),
                false,
            ),
            Verdict::BadSignature(ids) if ids.is_empty() => (
                "BAD SIGNATURE",
                "not signed by the pinned key".into(),
                false,
            ),
            Verdict::BadSignature(ids) => (
                "BAD SIGNATURE",
                format!(
                    "not by the pinned key (made by {})",
                    ids.iter().map(|i| whose(i)).collect::<Vec<_>>().join("; ")
                ),
                false,
            ),
            Verdict::WrongRelease(theirs) => (
                "WRONG RELEASE",
                format!("their signed attestation is for {theirs}, not {release}"),
                false,
            ),
            Verdict::Mismatch(theirs) => ("MISMATCH", format!("they signed {theirs}"), false),
            Verdict::NotListed => (
                "NOT LISTED",
                "their attestation doesn't include this file".into(),
                false,
            ),
            Verdict::NoAttestation => ("NO ATTESTATION", format!("nothing for {release}"), false),
            Verdict::Error(e) => ("ERROR", e.clone(), false),
        };
        // With a log, an attestation counts only if it's in there for all to see.
        let (label, detail, counts) = match &logged {
            Some(set) if counts && !leaf.is_some_and(|h| set.contains(&h)) => (
                "NOT LOGGED",
                "their attestation isn't in the transparency log, so it doesn't count".to_string(),
                false,
            ),
            _ => (label, detail, counts),
        };
        conflicts += usize::from(matches!(verdict, Verdict::Mismatch(_)));
        counted += usize::from(counts);
        println!("  {:<20} {:<15} {}", r.name, label, detail);
    }

    let ok = counted >= threshold && conflicts == 0;
    if ok {
        println!(
            "PASS: {counted} pinned rebuilder(s) reproduced this exact file (threshold {threshold})."
        );
    } else if conflicts > 0 {
        println!(
            "FAIL: {conflicts} pinned rebuilder(s) signed a DIFFERENT hash for {name}. Don't run it: \
             your file doesn't match what they built."
        );
    } else {
        println!(
            "FAIL: only {counted} pinned rebuilder(s) vouch for this file; the threshold is {threshold}."
        );
    }
    Ok(ok)
}

fn judge(
    p: &Project,
    src: &Source,
    r: &Rebuilder,
    release: &str,
    name: &str,
    hash: &str,
    now: SystemTime,
) -> (Verdict, Option<tlog::Hash>) {
    let mut leaf = None;
    let res = (|| -> Result<Verdict> {
        let Some(att) = p.file.feed.fetch(src, release, &r.name, name)? else {
            return Ok(Verdict::NoAttestation);
        };
        leaf = Some(tlog::leaf_hash(&tlog::entry(
            p.file.feed,
            &r.name,
            release,
            &att,
        )?));
        let keys = pinned_keys(p, r)?;
        let (status, entries) = match att {
            Attestation::PgpSums { sums: data, sig } => {
                let mut status = SigStatus::Bad;
                for k in &keys {
                    if let PubKey::Pgp(c) = k {
                        let s = c.check(&sig, &data, now)?;
                        if rank(&s) > rank(&status) {
                            status = s;
                        }
                    }
                }
                match status {
                    SigStatus::Bad => return Ok(Verdict::BadSignature(pgp::claimed_issuers(&sig))),
                    // A revoked key's word doesn't count, for or against.
                    SigStatus::Revoked => return Ok(Verdict::Match(SigStatus::Revoked)),
                    _ => {}
                }
                // Only now, with the signature checked, read what it says.
                (status, sums::parse(&data))
            }
            Attestation::Dsse(data) => {
                let refs: Vec<&PubKey> = keys.iter().collect();
                match dsse::verify(&data, &refs)? {
                    dsse::Outcome::Bad(ids) => return Ok(Verdict::BadSignature(ids)),
                    dsse::Outcome::Good(st) => {
                        if let Some(theirs) = st.release.filter(|t| t != release) {
                            return Ok(Verdict::WrongRelease(theirs));
                        }
                        let subjects = st.subjects.into_iter().map(|(n, h)| (h, n)).collect();
                        (SigStatus::Good { created: None }, subjects)
                    }
                }
            }
        };
        // entries: (sha256, name), as sums::parse gives them.
        let theirs: Vec<String> = entries
            .into_iter()
            .filter(|(_, n)| n == name)
            .map(|(h, _)| h)
            .collect();
        Ok(match theirs.iter().find(|h| h.as_str() != hash) {
            _ if theirs.is_empty() => Verdict::NotListed,
            Some(other) => Verdict::Mismatch(other.clone()),
            None => Verdict::Match(status),
        })
    })();
    let verdict = res.unwrap_or_else(|e| Verdict::Error(format!("{e:#}")));
    (verdict, leaf)
}

pub fn rank(s: &SigStatus) -> u8 {
    match s {
        SigStatus::Bad => 0,
        SigStatus::Revoked => 1,
        SigStatus::Expired {
            made_while_valid: false,
            ..
        } => 2,
        SigStatus::Expired { .. } => 3,
        SigStatus::Good { .. } => 4,
    }
}

// ── making attestations ─────────────────────────────────────────────────────

fn write_private(path: &Path, data: &[u8]) -> Result<()> {
    let mut opts = std::fs::OpenOptions::new();
    opts.write(true).create_new(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        opts.mode(0o600);
    }
    opts.open(path)?.write_all(data)?;
    Ok(())
}

fn statement(release: &str, out: Option<&Path>, files: &[PathBuf]) -> Result<()> {
    store::check_name("release", release)?;
    let mut subjects = Vec::new();
    for f in files {
        let name = f
            .file_name()
            .context("not a file")?
            .to_string_lossy()
            .into_owned();
        subjects.push((name, sums::sha256_file(f)?));
    }
    let st = dsse::rebuild_statement(release, &subjects)?;
    match out {
        Some(o) => {
            std::fs::write(o, &st)?;
            eprintln!(
                "Wrote {} ({} file(s), release {release}); sign it with cosign attest-blob --statement.",
                o.display(),
                subjects.len()
            );
        }
        None => print!("{st}"),
    }
    Ok(())
}

pub fn date(t: SystemTime) -> String {
    time::date(t)
}

// ── publishing freshness ────────────────────────────────────────────────────

#[derive(Subcommand)]
enum TufCmd {
    /// Re-sign the timestamp (and the snapshot, with its key) of a tuftool-made
    /// repository with new expiry dates; run it daily
    Refresh {
        /// The repository's metadata directory
        dir: PathBuf,
        #[arg(long)]
        snapshot_key: Option<PathBuf>,
        #[arg(long)]
        timestamp_key: PathBuf,
        #[arg(long, default_value = "7d")]
        snapshot_expires: String,
        #[arg(long, default_value = "1d")]
        timestamp_expires: String,
    },
}

fn tuf_cmd(cmd: TufCmd) -> Result<()> {
    let TufCmd::Refresh {
        dir,
        snapshot_key,
        timestamp_key,
        snapshot_expires,
        timestamp_expires,
    } = cmd;
    let sk = snapshot_key
        .as_deref()
        .map(tuf::SignKey::load)
        .transpose()?;
    tuf::refresh(
        &dir,
        sk.as_ref(),
        &tuf::SignKey::load(&timestamp_key)?,
        &tuf::Expiries {
            snapshot: time::parse_duration(&snapshot_expires)?,
            timestamp: time::parse_duration(&timestamp_expires)?,
        },
        SystemTime::now(),
    )?;
    println!("Refreshed {}.", dir.display());
    Ok(())
}

// ── transparency ────────────────────────────────────────────────────────────

#[derive(Subcommand)]
enum LogCmd {
    /// Make a log's key: writes the private key in Go's note format (Tessera's
    /// LOG_PRIVATE_KEY) and prints the verifier key projects pin
    Keygen {
        /// The log's name, e.g. example.org/hello-log; checkpoints carry it
        #[arg(long)]
        origin: String,
        /// Where to write the private key
        #[arg(long)]
        out: PathBuf,
    },
    /// Write a rebuilder's attestation as a log entry, for the log to take in
    /// (Tessera: posix-oneshot --entries)
    Entry {
        #[arg(long)]
        rebuilder: String,
        #[arg(long)]
        release: String,
        /// attestation.sigstore.json (or .dsse.json), or for guix.sigs a SHA256SUMS file
        attestation: PathBuf,
        /// For guix.sigs: the SHA256SUMS file's .asc
        #[arg(long)]
        signature: Option<PathBuf>,
        /// Where to write the entry
        #[arg(long)]
        out: PathBuf,
    },
    /// Read every entry of a project's log and report conflicting hashes
    Monitor {
        #[arg(short, long)]
        project: Option<String>,
    },
}

fn log_cmd(home: &Path, cmd: LogCmd) -> Result<bool> {
    match cmd {
        LogCmd::Keygen { origin, out } => {
            if out.exists() {
                bail!("{} exists; not overwriting a key", out.display());
            }
            let (skey, vkey) = note::generate_log_key(&origin)?;
            write_private(&out, format!("{skey}\n").as_bytes())?;
            println!("Private key: {} (keep it secret)", out.display());
            println!("Its verifier key, for `quorum project add … --log-key`:");
            println!("{vkey}");
        }
        LogCmd::Entry {
            rebuilder,
            release,
            attestation,
            signature,
            out,
        } => {
            store::check_name("rebuilder name", &rebuilder)?;
            store::check_name("release", &release)?;
            let data = std::fs::read(&attestation)
                .with_context(|| format!("reading {}", attestation.display()))?;
            let (kind, att) = match signature {
                Some(sig) => (
                    FeedKind::GuixSigs,
                    Attestation::PgpSums {
                        sums: data,
                        sig: std::fs::read(&sig)
                            .with_context(|| format!("reading {}", sig.display()))?,
                    },
                ),
                None => (FeedKind::InToto, Attestation::Dsse(data)),
            };
            let entry = tlog::entry(kind, &rebuilder, &release, &att)?;
            std::fs::write(&out, &entry).with_context(|| format!("writing {}", out.display()))?;
            println!(
                "Wrote {} (leaf hash {}).",
                out.display(),
                hex::encode(tlog::leaf_hash(&entry))
            );
        }
        LogCmd::Monitor { project } => return monitor(&open_project(home, project.as_deref())?),
    }
    Ok(true)
}

/// Reads the whole log: every entry must hash to its leaf; entries by pinned
/// rebuilders are verified and their claims compared.
fn monitor(p: &Project) -> Result<bool> {
    let cfg = p
        .file
        .log
        .as_ref()
        .context("this project has no transparency log (`project add … --log`)")?;
    let view = tlog::fetch(cfg, Some(&p.log_state_path()))?;
    println!(
        "{}: {} entries, checkpoint verified",
        view.checkpoint.origin(),
        view.checkpoint.size()
    );
    let now = SystemTime::now();
    let mut claims: Vec<tlog::Claim> = Vec::new();
    let (mut unverified, mut mislabelled) = (0usize, Vec::new());
    for (i, data) in tlog::entries(cfg, &view)?.iter().enumerate() {
        let e = tlog::parse_entry(data).with_context(|| format!("entry {i}"))?;
        let Some(r) = p.rebuilder(&e.rebuilder) else {
            unverified += 1;
            continue;
        };
        let keys = pinned_keys(p, r)?;
        let subjects: Option<Vec<(String, String)>> = match &e.att {
            Attestation::PgpSums { sums: data, sig } => {
                let mut best = SigStatus::Bad;
                for k in &keys {
                    if let PubKey::Pgp(c) = k {
                        let s = c.check(sig, data, now)?;
                        if rank(&s) > rank(&best) {
                            best = s;
                        }
                    }
                }
                // An expired key still said what it said; a revoked one didn't count.
                (rank(&best) >= 2)
                    .then(|| sums::parse(data).into_iter().map(|(h, n)| (n, h)).collect())
            }
            Attestation::Dsse(data) => {
                let refs: Vec<&PubKey> = keys.iter().collect();
                match dsse::verify(data, &refs)? {
                    dsse::Outcome::Good(st) => {
                        if let Some(theirs) = st.release.as_ref().filter(|t| **t != e.release) {
                            mislabelled.push(format!(
                                "entry {i}: {}'s attestation for {theirs} logged as {}",
                                e.rebuilder, e.release
                            ));
                        }
                        Some(st.subjects)
                    }
                    dsse::Outcome::Bad(_) => None,
                }
            }
        };
        match subjects {
            Some(s) => claims.extend(
                s.into_iter()
                    .map(|(n, h)| (e.release.clone(), e.rebuilder.clone(), n, h)),
            ),
            None => unverified += 1,
        }
    }
    let (equivocations, disagreements) = tlog::conflicts(&claims);
    println!(
        "{} claim(s) by pinned rebuilders; {unverified} entr(y/ies) by others or not verifiable with your keys",
        claims.len()
    );
    for m in &mislabelled {
        println!("MISLABELLED: {m}");
    }
    for e in &equivocations {
        println!("EQUIVOCATION: {e}");
    }
    for d in &disagreements {
        println!("DISAGREEMENT: {d}");
    }
    let clean = equivocations.is_empty() && disagreements.is_empty() && mislabelled.is_empty();
    if clean {
        println!("OK: no conflicting hashes.");
    }
    Ok(clean)
}