🏡 index : quine-global/quorum.git

//! Checkpoints (<https://c2sp.org/tlog-checkpoint>) as signed notes
//! (<https://c2sp.org/signed-note>), with witness cosignatures
//! (<https://c2sp.org/tlog-cosignature>).
//!
//! Notes, Ed25519 note keys and checkpoints are Cloudflare's `signed_note`
//! and `tlog_tiles` crates (ports of Go's `sumdb/note` and `sumdb/tlog`).
//! What's here: cosignature/v1 keys (algorithm 0x04), which those crates
//! don't have yet, and the policy: the log signed, enough witnesses cosigned.

use anyhow::{Context, Result, bail};
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use signed_note::{Note, StandardSigner, StandardVerifier, Verifier, VerifierList};
use tlog_tiles::Checkpoint;

const ALG_ED25519: u8 = 0x01;
const ALG_COSIGNATURE_V1: u8 = 0x04;

/// A log's verifier key (`<name>+<key id>+<base64(0x01 ‖ Ed25519 key)>`).
pub fn log_verifier(vkey: &str) -> Result<StandardVerifier> {
    if Cosigner::parse(vkey).is_ok() {
        bail!("the log key {vkey:?} is a witness key (cosignature/v1, 0x04)");
    }
    StandardVerifier::new(vkey.trim())
        .map_err(|e| anyhow::anyhow!("the log's key {vkey:?}: {e} (want name+id+key, Ed25519)"))
}

/// A witness's verifier key: like a log's, with algorithm 0x04.
#[derive(Clone)]
pub struct Cosigner {
    name: String,
    id: u32,
    key: ed25519_dalek::VerifyingKey,
}

impl Cosigner {
    pub fn parse(vkey: &str) -> Result<Self> {
        let mut parts = vkey.trim().splitn(3, '+');
        let (Some(name), Some(id), Some(b64)) = (parts.next(), parts.next(), parts.next()) else {
            bail!("bad witness key {vkey:?} (want name+id+key)");
        };
        if !signed_note::is_key_name_valid(name) {
            bail!("bad witness key name {name:?}");
        }
        let raw = STANDARD.decode(b64).context("bad witness key base64")?;
        match raw.first() {
            Some(&ALG_COSIGNATURE_V1) => {}
            Some(&ALG_ED25519) => {
                bail!("{name}'s key is a log key (Ed25519, 0x01), not a witness key (0x04)")
            }
            _ => bail!("{name}'s key: only cosignature/v1 (0x04) witness keys"),
        }
        let key: [u8; 32] = raw[1..]
            .try_into()
            .ok()
            .context("Ed25519 keys are 32 bytes")?;
        let want = signed_note::key_id(name, &raw);
        if id.len() != 8 || u32::from_str_radix(id, 16).ok() != Some(want) {
            bail!("witness key {name}: its key id doesn't match");
        }
        Ok(Cosigner {
            name: name.into(),
            id: want,
            key: ed25519_dalek::VerifyingKey::from_bytes(&key)?,
        })
    }
}

impl Verifier for Cosigner {
    fn name(&self) -> &str {
        &self.name
    }
    fn key_id(&self) -> u32 {
        self.id
    }
    /// A cosignature is the time (8 bytes, big-endian) and an Ed25519
    /// signature over `cosignature/v1\ntime <t>\n` and the checkpoint.
    fn verify(&self, msg: &[u8], sig: &[u8]) -> bool {
        let Some((time, sig)) = sig.split_first_chunk::<8>() else {
            return false;
        };
        let mut signed =
            format!("cosignature/v1\ntime {}\n", u64::from_be_bytes(*time)).into_bytes();
        signed.extend_from_slice(msg);
        ed25519_dalek::Signature::from_slice(sig)
            .is_ok_and(|s| self.key.verify_strict(&signed, &s).is_ok())
    }
}

pub struct Verified {
    pub checkpoint: Checkpoint,
    /// Witnesses whose cosignature verified, with the time they signed.
    pub witnesses: Vec<(String, u64)>,
}

/// Verifies a checkpoint note: signed by `log`, and cosigned by at least
/// `threshold` of `witnesses`. A pinned key's signature that's present but
/// wrong fails the whole note, as Go's `note.Open` does.
pub fn verify_checkpoint(
    note: &[u8],
    log: &StandardVerifier,
    witnesses: &[Cosigner],
    threshold: usize,
) -> Result<Verified> {
    let note = Note::from_bytes(note).map_err(|e| anyhow::anyhow!("the checkpoint: {e}"))?;
    let (log_name, log_id) = (log.name().to_owned(), log.key_id());
    let mut known: Vec<Box<dyn Verifier>> = vec![Box::new(log.clone())];
    for w in witnesses {
        known.push(Box::new(w.clone()));
    }
    let (sigs, _) = note
        .verify(&VerifierList::new(known))
        .map_err(|e| anyhow::anyhow!("checkpoint signatures: {e}"))?;
    if !sigs
        .iter()
        .any(|s| s.name() == log_name && s.id() == log_id)
    {
        bail!("checkpoint not signed by the log's key ({log_name})");
    }
    let checkpoint =
        Checkpoint::from_bytes(note.text()).map_err(|_| anyhow::anyhow!("malformed checkpoint"))?;
    if checkpoint.origin() != log_name {
        bail!(
            "checkpoint origin {:?} isn't the log's ({log_name})",
            checkpoint.origin()
        );
    }
    // In the order the user pinned them.
    let witnesses: Vec<(String, u64)> = witnesses
        .iter()
        .filter_map(|w| {
            let s = sigs.iter().find(|s| w.name == s.name() && w.id == s.id())?;
            let t = s.signature()[..8].try_into().unwrap();
            Some((w.name.clone(), u64::from_be_bytes(t)))
        })
        .collect();
    if witnesses.len() < threshold {
        bail!(
            "checkpoint cosigned by {} of the witnesses you pinned; {threshold} needed",
            witnesses.len()
        );
    }
    Ok(Verified {
        checkpoint,
        witnesses,
    })
}

/// A new log key for `origin`: the private key in Go's note format (what
/// Tessera's LOG_PRIVATE_KEY takes) and its verifier key.
pub fn generate_log_key(origin: &str) -> Result<(String, String)> {
    let mut seed = [0u8; 32];
    getrandom::fill(&mut seed).map_err(|e| anyhow::anyhow!("no randomness: {e}"))?;
    let public = ed25519_dalek::SigningKey::from_bytes(&seed).verifying_key();
    let mut pubraw = vec![ALG_ED25519];
    pubraw.extend_from_slice(public.as_bytes());
    let id = signed_note::key_id(origin, &pubraw);
    let mut privraw = vec![ALG_ED25519];
    privraw.extend_from_slice(&seed);
    let skey = format!("PRIVATE+KEY+{origin}+{id:08x}+{}", STANDARD.encode(privraw));
    StandardSigner::new(&skey).map_err(|e| anyhow::anyhow!("bad log name {origin:?}: {e}"))?;
    let vkey = signed_note::new_ed25519_verifier_key(origin, &public);
    Ok((skey, vkey))
}