use std::collections::{BTreeMap, HashSet};
use std::fs;
use std::path::Path;
use anyhow::{Context, Result, bail};
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use tlog_tiles::{
Checkpoint, Hash as TlogHash, HashReader, Tile, TileHashReader, TileReader, stored_hash_index,
};
use crate::cjson;
use crate::feed::{Attestation, FeedKind};
use crate::note::{self, Cosigner};
use crate::source::Source;
pub type Hash = [u8; 32];
pub const MAX_ENTRY: usize = u16::MAX as usize;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogConfig {
pub url: String,
pub key: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub witnesses: Vec<String>,
#[serde(default)]
pub witness_threshold: usize,
}
pub fn entry(kind: FeedKind, rebuilder: &str, release: &str, att: &Attestation) -> Result<Vec<u8>> {
let v = match att {
Attestation::Dsse(data) => json!({
"kind": "in-toto", "rebuilder": rebuilder, "release": release,
"attestation": STANDARD.encode(data),
}),
Attestation::PgpSums { sums, sig } => json!({
"kind": "guix-sigs", "rebuilder": rebuilder, "release": release,
"attestation": STANDARD.encode(sums), "signature": STANDARD.encode(sig),
}),
};
debug_assert!(matches!(
(kind, att),
(FeedKind::InToto, Attestation::Dsse(_))
| (FeedKind::GuixSigs, Attestation::PgpSums { .. })
));
let e = cjson::encode(&v)?;
if e.len() > MAX_ENTRY {
bail!(
"the attestation makes a {}-byte log entry; logs take at most {MAX_ENTRY}",
e.len()
);
}
Ok(e)
}
pub struct Parsed {
pub rebuilder: String,
pub release: String,
pub att: Attestation,
}
pub fn parse_entry(data: &[u8]) -> Result<Parsed> {
let v: Value = serde_json::from_slice(data).context("entry isn't JSON")?;
let s = |k: &str| {
v[k].as_str()
.map(String::from)
.with_context(|| format!("entry without {k}"))
};
let att = STANDARD.decode(s("attestation")?)?;
let att = match v["kind"].as_str() {
Some("in-toto") => Attestation::Dsse(att),
Some("guix-sigs") => Attestation::PgpSums {
sums: att,
sig: STANDARD.decode(s("signature")?)?,
},
other => bail!("entry of unknown kind {other:?}"),
};
Ok(Parsed {
rebuilder: s("rebuilder")?,
release: s("release")?,
att,
})
}
pub fn leaf_hash(entry: &[u8]) -> Hash {
tlog_tiles::record_hash(entry).0
}
fn tile_path(level: &str, n: u64, width: u32) -> String {
let mut n_str = format!("{:03}", n % 1000);
let mut n = n;
while n >= 1000 {
n /= 1000;
n_str = format!("x{:03}/{n_str}", n % 1000);
}
let partial = if width < 256 {
format!(".p/{width}")
} else {
String::new()
};
format!("tile/{level}/{n_str}{partial}")
}
fn get_tile(src: &Source, level: &str, n: u64, width: u32) -> Result<Vec<u8>> {
let path = tile_path(level, n, width);
if let Some(d) = src.get(&path)? {
return Ok(d);
}
if width < 256
&& let Some(d) = src.get(&tile_path(level, n, 256))?
{
return Ok(d);
}
bail!("the log serves no {path}")
}
struct Tiles<'a>(&'a Source);
impl TileReader for Tiles<'_> {
fn height(&self) -> u8 {
8
}
fn read_tiles(&self, tiles: &[Tile]) -> Result<Vec<Vec<u8>>, tlog_tiles::Error> {
tiles
.iter()
.map(|t| {
let want = t.width() as usize * 32;
let mut d = get_tile(self.0, &t.level().to_string(), t.level_index(), t.width())
.map_err(|e| tlog_tiles::Error::InvalidInput(format!("{e:#}")))?;
if d.len() < want {
return Err(tlog_tiles::Error::InvalidTile);
}
d.truncate(want);
Ok(d)
})
.collect()
}
fn save_tiles(&self, _: &[Tile], _: &[Vec<u8>]) {}
}
pub struct View {
pub checkpoint: Checkpoint,
pub leaves: Vec<Hash>,
pub witnesses: Vec<(String, u64)>,
}
pub fn fetch(cfg: &LogConfig, state: Option<&Path>) -> Result<View> {
let src = Source::parse(&cfg.url);
let log = note::log_verifier(&cfg.key)?;
let witnesses: Vec<Cosigner> = cfg
.witnesses
.iter()
.map(|w| Cosigner::parse(w).context("a witness key"))
.collect::<Result<_>>()?;
let cp = src
.get("checkpoint")?
.context("the log serves no checkpoint")?;
let v = note::verify_checkpoint(&cp, &log, &witnesses, cfg.witness_threshold)?;
let (size, root) = (v.checkpoint.size(), *v.checkpoint.hash());
let tiles = Tiles(&src);
let reader = TileHashReader::new(size, root, &tiles);
if let Some(state) = state {
if let Ok(old) = fs::read(state) {
let old: Value = serde_json::from_slice(&old).context("the saved log state")?;
let old_size = old["size"].as_u64().unwrap_or(0);
let old_root = old["root"].as_str().unwrap_or("");
if size < old_size {
bail!(
"FORK: the log shrank to {size} entries; it had {old_size} when you last checked"
);
}
if old_size > 0 {
let old_root: Hash = hex::decode(old_root)
.ok()
.and_then(|r| r.try_into().ok())
.context("the saved log state's root")?;
let consistent = if old_size == size {
root.0 == old_root
} else {
let proof = tlog_tiles::prove_tree(size, old_size, &reader)
.context("reading the log's tiles")?;
tlog_tiles::check_tree(&proof, size, root, old_size, TlogHash(old_root)).is_ok()
};
if !consistent {
bail!(
"FORK: the log's first {old_size} entries aren't the ones you saw before: its history changed"
);
}
}
}
if let Some(dir) = state.parent().filter(|d| !d.as_os_str().is_empty()) {
fs::create_dir_all(dir)?;
}
let tmp = state.with_extension("tmp");
fs::write(
&tmp,
serde_json::to_vec(&json!({"size": size, "root": hex::encode(root.0)}))?,
)?;
fs::rename(&tmp, state)?;
}
let indexes: Vec<u64> = (0..size).map(|i| stored_hash_index(0, i)).collect();
let leaves = reader
.read_hashes(&indexes)
.context("the log's leaf hashes don't add up to its signed root")?
.into_iter()
.map(|h| h.0)
.collect();
Ok(View {
checkpoint: v.checkpoint,
leaves,
witnesses: v.witnesses,
})
}
impl View {
pub fn contains(&self) -> HashSet<Hash> {
self.leaves.iter().copied().collect()
}
}
pub fn entries(cfg: &LogConfig, view: &View) -> Result<Vec<Vec<u8>>> {
let src = Source::parse(&cfg.url);
let size = view.leaves.len() as u64;
let mut out: Vec<Vec<u8>> = Vec::with_capacity(view.leaves.len());
let mut n = 0;
while (out.len() as u64) < size {
let width = (size - n * 256).min(256) as u32;
let bundle = get_tile(&src, "entries", n, width)?;
let mut rest = bundle.as_slice();
for _ in 0..width {
let Some((len, tail)) = rest.split_first_chunk::<2>() else {
bail!("entry bundle {n} ends early");
};
let len = u16::from_be_bytes(*len) as usize;
if tail.len() < len {
bail!("entry bundle {n} ends early");
}
out.push(tail[..len].to_vec());
rest = &tail[len..];
}
n += 1;
}
for (i, (e, leaf)) in out.iter().zip(&view.leaves).enumerate() {
if &leaf_hash(e) != leaf {
bail!(
"entry {i} doesn't match its leaf hash: the log serves something else than it signed"
);
}
}
Ok(out)
}
pub type Claim = (String, String, String, String);
pub fn conflicts(claims: &[Claim]) -> (Vec<String>, Vec<String>) {
let mut by_rebuilder: BTreeMap<(&str, &str, &str), Vec<&str>> = BTreeMap::new();
let mut by_file: BTreeMap<(&str, &str), BTreeMap<&str, Vec<&str>>> = BTreeMap::new();
for (rel, who, file, hash) in claims {
let hs = by_rebuilder.entry((rel, who, file)).or_default();
if !hs.contains(&hash.as_str()) {
hs.push(hash);
}
let ws = by_file
.entry((rel, file))
.or_default()
.entry(hash)
.or_default();
if !ws.contains(&who.as_str()) {
ws.push(who);
}
}
let equivocations = by_rebuilder
.iter()
.filter(|(_, hs)| hs.len() > 1)
.map(|((rel, who, file), hs)| {
format!(
"{who} signed {} different hashes for {rel}/{file}: {}",
hs.len(),
hs.join(", ")
)
})
.collect();
let disagreements = by_file
.iter()
.filter(|(_, hs)| hs.len() > 1)
.map(|((rel, file), hs)| {
let parts: Vec<String> = hs
.iter()
.map(|(h, ws)| format!("{h} ({})", ws.join(", ")))
.collect();
format!("{rel}/{file}: {}", parts.join(" vs "))
})
.collect();
(equivocations, disagreements)
}