🏡 index : quine-global/quorum.git

//! Transparency (charter M3), end to end, against the real thing: a log
//! written by Tessera's posix-oneshot, cosigned by two litewitness
//! witnesses over c2sp.org/tlog-witness. Checks count only logged
//! attestations, refuse rewritten history and uncosigned checkpoints; the
//! monitor finds equivocation.
//!
//! Needs posix-oneshot, litewitness and witnessctl on PATH (or in
//! $POSIX_ONESHOT, $LITEWITNESS, $WITNESSCTL), and OpenSSH's ssh-agent:
//!   go install github.com/transparency-dev/tessera/cmd/examples/posix-oneshot@v1.0.4
//!   go install filippo.io/torchwood/cmd/{litewitness,witnessctl}@v0.10.0
//! `nix develop` has them.

mod common;

use std::net::{TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Output, Stdio};
use std::time::{Duration, Instant};

const ORIGIN: &str = "example.org/hello-log";

use common::tool;

fn run(cmd: &mut Command) -> Output {
    let o = cmd.output().unwrap();
    assert!(
        o.status.success(),
        "{cmd:?}: {}{}",
        String::from_utf8_lossy(&o.stdout),
        String::from_utf8_lossy(&o.stderr)
    );
    o
}

fn wait_for(what: &str, mut ready: impl FnMut() -> bool) {
    let t = Instant::now();
    while !ready() {
        assert!(t.elapsed() < Duration::from_secs(20), "{what}: timed out");
        std::thread::sleep(Duration::from_millis(50));
    }
}

/// A litewitness, with its own ssh-agent holding its key.
struct Witness {
    name: String,
    dir: PathBuf,
    sock: PathBuf,
    port: u16,
    vkey: String,
    procs: Vec<Child>,
}

impl Witness {
    fn start(dir: &Path, name: &str) -> Witness {
        let dir = dir.join(name);
        std::fs::create_dir_all(&dir).unwrap();
        // Unix sockets want a short path.
        let sock = PathBuf::from(format!("/tmp/qt-{}-{}", std::process::id(), unique()));
        let key = dir.join("key");
        run(Command::new("ssh-keygen")
            .args(["-q", "-t", "ed25519", "-N", "", "-f"])
            .arg(&key));
        let mut w = Witness {
            name: name.into(),
            dir,
            sock,
            port: 0,
            vkey: String::new(),
            procs: vec![],
        };
        let agent = Command::new("ssh-agent")
            .arg("-D")
            .arg("-a")
            .arg(&w.sock)
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .unwrap();
        w.procs.push(agent);
        wait_for("ssh-agent", || w.sock.exists());
        run(Command::new("ssh-add")
            .arg("-q")
            .arg(&key)
            .env("SSH_AUTH_SOCK", &w.sock));
        w.serve();
        w
    }

    fn db(&self) -> PathBuf {
        self.dir.join("witness.db")
    }

    /// Knows the log (from size 0) and listens.
    fn serve(&mut self) {
        let ctl = |args: &[&str]| {
            run(Command::new(tool("witnessctl"))
                .args(args)
                .arg("-db")
                .arg(self.db())
                .args(["-origin", ORIGIN]))
        };
        ctl(&["add-log"]);
        ctl(&["add-key", "-key", &log_vkey(self.dir.parent().unwrap())]);
        let fpr = run(Command::new("ssh-keygen")
            .arg("-lf")
            .arg(self.dir.join("key.pub")));
        let fpr = String::from_utf8_lossy(&fpr.stdout)
            .split_whitespace()
            .nth(1)
            .unwrap()
            .to_string();
        self.port = TcpListener::bind("127.0.0.1:0")
            .unwrap()
            .local_addr()
            .unwrap()
            .port();
        let log = self.dir.join("litewitness.log");
        let p = Command::new(tool("litewitness"))
            .arg("-db")
            .arg(self.db())
            .args(["-name", &self.name, "-key", &fpr, "-ssh-agent"])
            .arg(&self.sock)
            .args(["-listen", &format!("127.0.0.1:{}", self.port)])
            .stdout(Stdio::null())
            .stderr(std::fs::File::create(&log).unwrap())
            .spawn()
            .unwrap();
        self.procs.push(p);
        let port = self.port;
        wait_for("litewitness", || {
            TcpStream::connect(("127.0.0.1", port)).is_ok()
        });
        let out = std::fs::read_to_string(&log).unwrap();
        self.vkey = out
            .split_whitespace()
            .find_map(|w| w.strip_prefix("vkey="))
            .expect("litewitness prints its vkey")
            .trim_matches('"')
            .to_string();
    }

    /// Forgets every checkpoint it saw: a new witness with the old key, or a
    /// colluding one.
    fn reset(&mut self) {
        let mut p = self.procs.pop().unwrap();
        let _ = p.kill();
        let _ = p.wait();
        for ext in ["", "-wal", "-shm"] {
            let _ = std::fs::remove_file(format!("{}{ext}", self.db().display()));
        }
        self.serve();
    }
}

impl Drop for Witness {
    fn drop(&mut self) {
        for p in self.procs.iter_mut().rev() {
            let _ = p.kill();
            let _ = p.wait();
        }
        let _ = std::fs::remove_file(&self.sock);
    }
}

fn unique() -> u64 {
    use std::sync::atomic::{AtomicU64, Ordering};
    static N: AtomicU64 = AtomicU64::new(0);
    N.fetch_add(1, Ordering::Relaxed)
}

fn log_vkey(dir: &Path) -> String {
    std::fs::read_to_string(dir.join("keys/log.vkey"))
        .unwrap()
        .trim()
        .to_string()
}

struct Env {
    dir: PathBuf,
    witnesses: Vec<Witness>,
}

impl Drop for Env {
    fn drop(&mut self) {
        self.witnesses.clear();
        let _ = std::fs::remove_dir_all(&self.dir);
    }
}

impl Env {
    fn q(&self, args: &[&str]) -> Output {
        Command::new(env!("CARGO_BIN_EXE_quorum"))
            .arg("--home")
            .arg(self.dir.join("home"))
            .args(args)
            .output()
            .unwrap()
    }

    fn ok(&self, args: &[&str]) -> String {
        let o = self.q(args);
        assert!(
            o.status.success(),
            "{args:?}: {}{}",
            String::from_utf8_lossy(&o.stdout),
            String::from_utf8_lossy(&o.stderr)
        );
        String::from_utf8_lossy(&o.stdout).into_owned()
    }

    fn p(&self, rel: &str) -> String {
        self.dir.join(rel).to_string_lossy().into_owned()
    }

    fn write(&self, rel: &str, data: &[u8]) -> String {
        let p = self.dir.join(rel);
        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
        std::fs::write(&p, data).unwrap();
        p.to_string_lossy().into_owned()
    }

    fn attest(&self, who: &str, files: &[&str]) {
        common::attest(&self.dir, who, "1.0", files);
    }

    /// Logs the rebuilders' current attestations, in order, into `log` with
    /// posix-oneshot; with `witnessed`, it has both witnesses cosign (2 of 2)
    /// before it publishes the checkpoint.
    fn log_add(&self, log: &str, who: &[&str], witnessed: bool) -> Result<(), String> {
        let batch = self.dir.join(format!("entries-{}", unique()));
        std::fs::create_dir_all(&batch).unwrap();
        for (i, w) in who.iter().enumerate() {
            self.ok(&[
                "log",
                "entry",
                "--rebuilder",
                w,
                "--release",
                "1.0",
                &self.p(&format!("feed/1.0/{w}/attestation.sigstore.json")),
                "--out",
                &batch.join(format!("{i:03}")).to_string_lossy(),
            ]);
        }
        let mut cmd = Command::new(tool("posix-oneshot"));
        cmd.arg(format!("--storage_dir={}", self.p(log)))
            .arg(format!("--entries={}/*", batch.display()))
            .arg(format!("--private_key={}", self.p("keys/log.key")));
        if witnessed {
            let mut policy = String::new();
            for w in &self.witnesses {
                policy += &format!(
                    "witness {} {} http://127.0.0.1:{}\n",
                    w.name, w.vkey, w.port
                );
            }
            policy += "group both all w1 w2\nquorum both\n";
            cmd.arg(format!(
                "--witness_policy_file={}",
                self.write("policy", policy.as_bytes())
            ));
        }
        let o = cmd.output().unwrap();
        if o.status.success() {
            Ok(())
        } else {
            Err(String::from_utf8_lossy(&o.stderr).into_owned())
        }
    }

    fn check(&self) -> (Option<i32>, String) {
        let o = self.q(&["check", &self.p("dl/hello-1.0.exe")]);
        (
            o.status.code(),
            String::from_utf8_lossy(&o.stdout).into_owned(),
        )
    }
}

/// Project "hello" (alice, bob; threshold 2), a log holding both
/// attestations, cosigned by witnesses w1 and w2, both of which the user pins.
fn setup(name: &str) -> Env {
    let dir = std::env::temp_dir().join(format!("quorum-tlog-{name}-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let mut env = Env {
        dir,
        witnesses: vec![],
    };
    for k in ["alice", "bob"] {
        common::rebuilder_key(&env.dir, k);
    }
    let out = env.ok(&[
        "log",
        "keygen",
        "--origin",
        ORIGIN,
        "--out",
        &env.p("keys/log.key"),
    ]);
    env.write("keys/log.vkey", out.lines().last().unwrap().as_bytes());
    env.witnesses = vec![
        Witness::start(&env.dir, "w1"),
        Witness::start(&env.dir, "w2"),
    ];
    let file = env.write("dl/hello-1.0.exe", b"MZ hello 1.0\n");
    env.attest("alice", &[&file]);
    env.attest("bob", &[&file]);
    env.log_add("log", &["alice", "bob"], true).unwrap();
    let (w1, w2) = (env.witnesses[0].vkey.clone(), env.witnesses[1].vkey.clone());
    env.ok(&[
        "project",
        "add",
        "hello",
        "--feed",
        "in-toto",
        "--source",
        &env.p("feed"),
        "--release-prefix",
        "hello-",
        "--log",
        &env.p("log"),
        "--log-key",
        &log_vkey(&env.dir),
        "--witness",
        &w1,
        "--witness",
        &w2,
    ]);
    for who in ["alice", "bob"] {
        env.ok(&["trust", "add", who, "--yes"]);
    }
    env.ok(&["trust", "threshold", "2"]);
    env
}

#[test]
fn logged_and_cosigned_passes() {
    let env = setup("pass");
    let (code, out) = env.check();
    assert_eq!(code, Some(0), "{out}");
    assert!(
        out.contains("log     example.org/hello-log: 2 entries, cosigned by w1, w2"),
        "{out}"
    );
}

#[test]
fn an_unlogged_attestation_doesnt_count() {
    let env = setup("unlogged");
    // bob signs a new attestation (another file listed too) without logging it.
    let extra = env.write("dl/notes.txt", b"notes\n");
    env.attest("bob", &[&env.p("dl/hello-1.0.exe"), &extra]);
    let (code, out) = env.check();
    assert_eq!(code, Some(1), "{out}");
    let bob = out
        .lines()
        .find(|l| l.trim_start().starts_with("bob"))
        .unwrap();
    assert!(bob.contains("NOT LOGGED"), "{out}");
}

#[test]
fn a_checkpoint_without_the_witnesses_is_refused() {
    let env = setup("uncosigned");
    let extra = env.write("dl/notes.txt", b"notes\n");
    env.attest("bob", &[&env.p("dl/hello-1.0.exe"), &extra]);
    env.log_add("log", &["bob"], false).unwrap(); // a new checkpoint, not cosigned
    let (code, out) = env.check();
    assert_eq!(code, Some(1), "{out}");
    assert!(
        out.contains("cosigned by 0 of the witnesses you pinned; 2 needed"),
        "{out}"
    );
    // The next entry is witnessed: the witnesses check it extends what they saw.
    env.attest("alice", &[&env.p("dl/hello-1.0.exe"), &extra]);
    env.log_add("log", &["alice"], true).unwrap();
    let (code, out) = env.check();
    assert_eq!(code, Some(0), "{out}");
    assert!(out.contains("4 entries, cosigned by w1, w2"), "{out}");
}

#[test]
fn rewritten_history_is_a_fork() {
    let mut env = setup("fork");
    assert_eq!(env.check().0, Some(0)); // the client has seen 2 entries
    // The operator rebuilds the log with bob first, then alice: the same
    // entries, another history. The witnesses remember and refuse it...
    let err = env.log_add("log2", &["bob", "alice"], true).unwrap_err();
    assert!(err.contains("witness policy was not satisfied"), "{err}");
    assert!(!env.dir.join("log2/checkpoint").exists(), "{err}");
    // ...but new or colluding witnesses (same keys, no memory) would cosign it,
    // and the client still remembers what it saw.
    std::fs::remove_dir_all(env.dir.join("log2")).unwrap();
    for w in &mut env.witnesses {
        w.reset();
    }
    env.log_add("log2", &["bob", "alice"], true).unwrap();
    std::fs::remove_dir_all(env.dir.join("log")).unwrap();
    std::fs::rename(env.dir.join("log2"), env.dir.join("log")).unwrap();
    let (code, out) = env.check();
    assert_eq!(code, Some(1), "{out}");
    assert!(
        out.contains("FORK: the log's first 2 entries aren't the ones you saw before"),
        "{out}"
    );
}

#[test]
fn leaves_that_dont_match_the_signed_root_are_refused() {
    let env = setup("leaves");
    let tile = env.dir.join("log/tile/0/000.p/2");
    let mut leaves = std::fs::read(&tile).unwrap();
    leaves[0] ^= 1;
    std::fs::write(&tile, leaves).unwrap();
    let (code, out) = env.check();
    assert_eq!(code, Some(1), "{out}");
    assert!(out.contains("don't add up to its signed root"), "{out}");
}

#[test]
fn the_monitor_finds_equivocation() {
    let env = setup("monitor");
    let s = env.ok(&["log", "monitor"]);
    assert!(s.contains("OK: no conflicting hashes"), "{s}");
    // alice also signs a different hello-1.0.exe for some audience, and it's logged.
    let evil = env.write("evil/hello-1.0.exe", b"MZ hello 1.0, special edition\n");
    env.attest("alice", &[&evil]);
    env.log_add("log", &["alice"], true).unwrap();
    let o = env.q(&["log", "monitor"]);
    let s = String::from_utf8_lossy(&o.stdout);
    assert_eq!(o.status.code(), Some(1), "{s}");
    assert!(
        s.contains("EQUIVOCATION: alice signed 2 different hashes for 1.0/hello-1.0.exe"),
        "{s}"
    );
    assert!(s.contains("DISAGREEMENT: 1.0/hello-1.0.exe"), "{s}");
}

#[test]
fn role_keys_cant_be_swapped() {
    let env = setup("roles");
    let add = |log_key: &str, witness: &str| {
        env.q(&[
            "project",
            "add",
            "hello2",
            "--feed",
            "in-toto",
            "--source",
            &env.p("feed"),
            "--log",
            &env.p("log"),
            "--log-key",
            log_key,
            "--witness",
            witness,
        ])
    };
    let w1 = &env.witnesses[0].vkey;
    let o = add(w1, w1);
    assert_eq!(o.status.code(), Some(2));
    assert!(String::from_utf8_lossy(&o.stderr).contains("is a witness key"));
    let o = add(&log_vkey(&env.dir), &log_vkey(&env.dir));
    assert_eq!(o.status.code(), Some(2));
    assert!(String::from_utf8_lossy(&o.stderr).contains("is a log key"));
}