OXYGENHUB

Coverage / src/cli/tlog.rs 0.0%

0 of 150 lines run, 0 of 36 functions · run #337 on main · run missed

1
//! `oxy tlog verify` (spec §14.8, oxygenhub#238): audit a hub's whole
2
//! transparency log and list the entries that concern you.
3
4
use super::json;
5
use super::open;
6
use super::ui;
7
use anyhow::{anyhow, Result};
8
use oxy_core::hash::KeyId;
9
use std::path::{Path, PathBuf};
10
110×
pub fn verify(hub: Option<&str>, key: Option<&str>, all: bool, as_json: bool) -> Result<i32> {
120×
    let repo = open()?;
130×
    let remote = repo.default_remote();
140×
    let url = match hub {
150×
        Some(h) if h.contains("://") => h.to_string(),
160×
        Some(h) => format!("https://{h}"),
170×
        None => repo.config.remotes.get(&remote).cloned().ok_or_else(|| {
180×
            anyhow!("name the hub to check (this checkout has no remote {remote})")
190×
        })?,
20
    };
210×
    let ca = repo
220×
        .config
230×
        .remote_cas
240×
        .get(&remote)
250×
        .map(Path::new)
260×
        .filter(|_| hub.is_none());
270×
    let audit = repo.audit_log(&url, ca).map_err(|e| anyhow!("{e}"))?;
280×
    let key = match key {
290×
        Some(k) => Some(
300×
            KeyId::from_hex(k)
310×
                .ok_or_else(|| anyhow!("--key takes a full KeyId (64 hex digits)"))?,
32
        ),
330×
        None => None,
34
    };
350×
    let rid = repo.id().ok();
360×
    let listed: Vec<(usize, &oxy_core::tlog::Entry)> = audit
370×
        .entries
380×
        .iter()
390×
        .enumerate()
400×
        .filter(|(_, e)| match (&key, all) {
410×
            (_, true) => true,
420×
            (Some(k), _) => e.signers.contains(k),
430×
            (None, _) => Some(e.repo) == rid,
440×
        })
450×
        .collect();
460×
    let what = match (&key, all) {
470×
        (_, true) => "every entry".to_string(),
480×
        (Some(k), _) => format!("entries signed by {}", k.short(12)),
490×
        (None, _) => "this repository's entries".to_string(),
50
    };
510×
    if as_json {
520×
        println!(
53
            "{}",
540×
            json::obj([
550×
                ("hub", json::s(&audit.hub)),
560×
                ("origin", json::s(&audit.checkpoint.origin)),
570×
                ("size", json::n(audit.checkpoint.size)),
580×
                (
590×
                    "root",
600×
                    json::s(&oxy_core::hash::ObjectRef(audit.checkpoint.root).to_hex())
610×
                ),
62
                (
630×
                    "entries",
640×
                    json::arr(listed.iter().map(|(i, e)| {
650×
                        json::obj([
660×
                            ("index", json::n(*i)),
670×
                            ("kind", json::s(&e.kind)),
68
                            (
690×
                                "repo",
700×
                                json::s(
710×
                                    &e.repo
720×
                                        .iter()
730×
                                        .map(|b| format!("{b:02x}"))
740×
                                        .collect::<String>(),
75
                                ),
76
                            ),
770×
                            ("object", json::s(&e.object.to_hex())),
78
                            (
790×
                                "signers",
800×
                                json::arr(e.signers.iter().map(|k| json::s(&k.to_hex()))),
81
                            ),
820×
                            ("received_ms", json::n(e.received)),
83
                        ])
840×
                    })),
85
                ),
86
            ])
87
        );
880×
        return Ok(0);
890×
    }
900×
    for n in &audit.notes {
910×
        eprintln!("{} {n}", ui::caution());
920×
    }
930×
    println!(
94
        "{} {}: {} entries make the root its log key signed, and extend what you saw before",
950×
        ui::done("Verified"),
960×
        ui::path(&audit.checkpoint.origin),
97
        audit.checkpoint.size
98
    );
990×
    if listed.is_empty() {
1000×
        println!("  {} {}", ui::note(), ui::dim(format!("no {what} in it")));
1010×
        return Ok(0);
1020×
    }
1030×
    println!(
104
        "  {} {}",
1050×
        ui::note(),
1060×
        ui::dim(format!("{} of {what}:", listed.len()))
107
    );
1080×
    for (i, e) in listed {
1090×
        let signers: Vec<String> = e.signers.iter().map(|k| k.short(12)).collect();
1100×
        println!(
111
            "  #{i:<6} {:<11} {} {} {}",
112
            e.kind,
1130×
            ui::hash(e.object.short(12)),
1140×
            ui::dim(if signers.is_empty() {
1150×
                "unsigned".to_string()
116
            } else {
1170×
                format!("by {}", signers.join(", "))
118
            }),
1190×
            ui::dim(ui::ago(e.received))
120
        );
121
    }
1220×
    Ok(0)
1230×
}
124
125
/// `oxy witness serve`: cosign the named logs' checkpoints.
1260×
pub fn witness_serve(
1270×
    name: &str,
1280×
    logs: &[String],
1290×
    state: PathBuf,
1300×
    bind: &str,
1310×
    tls: Option<(PathBuf, PathBuf)>,
1320×
) -> Result<i32> {
1330×
    let home = oxy_core::repo::default_home();
1340×
    let (identity, sk) = oxy_core::repo::home_key(&home)
1350×
        .map_err(|e| anyhow!("{e}"))?
1360×
        .ok_or_else(|| anyhow!("{} names no key (author.key) with its secret: a witness signs with it; oxy identity create", home.display()))?;
1370×
    let mut parsed = Vec::new();
1380×
    for l in logs {
1390×
        let (origin, file) = l
1400×
            .split_once('=')
1410×
            .ok_or_else(|| anyhow!("--log takes ORIGIN=FILE, as oxygenhub.io/log=hub.identity"))?;
1420×
        let bytes = std::fs::read(file).map_err(|e| anyhow!("{file}: {e}"))?;
1430×
        let key =
1440×
            oxy_core::identity::Identity::decode(&bytes).map_err(|e| anyhow!("{file}: {e}"))?;
1450×
        parsed.push((origin.to_string(), key));
146
    }
1470×
    let listener = std::net::TcpListener::bind(bind).map_err(|e| anyhow!("binding {bind}: {e}"))?;
1480×
    println!(
149
        "{} {} logs as {} with key {} on {}://{bind}/add-checkpoint",
1500×
        ui::done("Witnessing"),
1510×
        parsed.len(),
1520×
        ui::path(name),
1530×
        identity.hash().short(12),
1540×
        if tls.is_some() { "https" } else { "http" }
155
    );
1560×
    for (o, k) in &parsed {
1570×
        println!(
1580×
            "  {} {} {}",
1590×
            ui::note(),
1600×
            o,
1610×
            ui::dim(format!("signed by {}", k.hash().short(12)))
1620×
        );
1630×
    }
1640×
    oxy_server::witness::run_blocking(
1650×
        listener,
166
        oxy_server::witness::WitnessConfig {
1670×
            name: name.to_string(),
1680×
            identity,
1690×
            sk,
1700×
            logs: parsed,
1710×
            state,
1720×
            tls: tls.map(|(cert, key)| oxy_server::TlsFiles { cert, key }),
173
        },
1740×
    )?;
1750×
    Ok(0)
1760×
}