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 {
#[arg(long, global = true)]
home: Option<PathBuf>,
#[command(subcommand)]
cmd: Cmd,
}
#[derive(Subcommand)]
enum Cmd {
Check {
#[arg(short, long)]
project: Option<String>,
#[arg(required = true)]
files: Vec<PathBuf>,
#[arg(long)]
release: Option<String>,
#[arg(long = "as")]
as_name: Option<String>,
#[arg(long)]
allow_expired: bool,
#[arg(long)]
allow_old: bool,
},
Project {
#[command(subcommand)]
cmd: ProjectCmd,
},
Trust {
#[arg(short, long, global = true)]
project: Option<String>,
#[command(subcommand)]
cmd: TrustCmd,
},
Log {
#[command(subcommand)]
cmd: LogCmd,
},
Tuf {
#[command(subcommand)]
cmd: TufCmd,
},
Statement {
#[arg(long)]
release: String,
#[arg(long)]
out: Option<PathBuf>,
#[arg(required = true)]
files: Vec<PathBuf>,
},
}
#[derive(Subcommand)]
#[allow(clippy::large_enum_variant)]
enum ProjectCmd {
Add {
name: String,
#[arg(long, conflicts_with_all = ["feed", "source"])]
preset: Option<String>,
#[arg(long, value_enum, required_unless_present = "preset")]
feed: Option<FeedKind>,
#[arg(long, required_unless_present = "preset")]
source: Option<String>,
#[arg(long)]
release_prefix: Option<String>,
#[arg(long)]
tuf: Option<String>,
#[arg(long, requires = "tuf")]
tuf_root_sha256: Option<String>,
#[arg(long)]
yes: bool,
#[arg(long, requires = "log_key")]
log: Option<String>,
#[arg(long, requires = "log")]
log_key: Option<String>,
#[arg(long = "witness", requires = "log")]
witnesses: Vec<String>,
#[arg(long, requires = "log")]
witness_threshold: Option<usize>,
},
List,
Remove {
name: String,
},
}
#[derive(Subcommand)]
enum TrustCmd {
List,
Add {
name: String,
#[arg(long)]
fingerprint: Option<String>,
#[arg(long)]
key_file: Option<PathBuf>,
#[arg(long)]
yes: bool,
},
Remove {
name: String,
},
Threshold {
n: usize,
},
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![],
},
};
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(),
};
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"))
}
enum Verdict {
Match(SigStatus),
Mismatch(String),
NotListed,
NoAttestation,
BadSignature(Vec<String>),
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();
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),
};
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))),
SigStatus::Revoked => return Ok(Verdict::Match(SigStatus::Revoked)),
_ => {}
}
(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)
}
}
}
};
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,
}
}
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)
}
#[derive(Subcommand)]
enum TufCmd {
Refresh {
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(×tamp_key)?,
&tuf::Expiries {
snapshot: time::parse_duration(&snapshot_expires)?,
timestamp: time::parse_duration(×tamp_expires)?,
},
SystemTime::now(),
)?;
println!("Refreshed {}.", dir.display());
Ok(())
}
#[derive(Subcommand)]
enum LogCmd {
Keygen {
#[arg(long)]
origin: String,
#[arg(long)]
out: PathBuf,
},
Entry {
#[arg(long)]
rebuilder: String,
#[arg(long)]
release: String,
attestation: PathBuf,
#[arg(long)]
signature: Option<PathBuf>,
#[arg(long)]
out: PathBuf,
},
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)
}
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;
}
}
}
(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)
}