OXYGENHUB

Coverage / src/cli/receipt.rs 85.0%

147 of 173 lines run, 16 of 38 functions · run #290 on main · run missed

1
//! Execution receipts (spec §14.6): list, show, verify and import the
2
//! signed receipts runners make.
3
4
use super::json;
5
use super::open;
6
use super::ui;
7
use anyhow::{bail, Result};
8
use oxy_core::receipt::SignedReceipt;
9
use oxy_core::repo::ReceiptInfo;
10
111×
fn status(problem: Option<&str>, revoked: bool) -> String {
121×
    match (problem, revoked) {
131×
        (Some(p), _) => ui::err(format!("{} {p}", ui::glyph("✘", "x"))),
140×
        (None, true) => ui::warn(format!("{} runner key revoked", ui::glyph("!", "!"))),
150×
        (None, false) => ui::ok(format!("{} signed", ui::glyph("✔", "v"))),
16
    }
171×
}
18
191×
fn line(sr: &SignedReceipt, problem: Option<&str>, revoked: bool) -> String {
201×
    let r = &sr.receipt;
211×
    let result = if r.passed() {
220×
        ui::ok(format!("{} passed", ui::glyph("●", "*")))
23
    } else {
241×
        ui::err(format!("{} exit {}", ui::glyph("●", "*"), r.exit_code))
25
    };
261×
    format!(
27
        "{} {}{}{}{}{}",
28
        result,
291×
        ui::subject(&r.job_name),
301×
        ui::sep() + &ui::dim(format!("{:.1} s", r.duration_ms as f64 / 1000.0)),
311×
        ui::sep() + &ui::author(&sr.runner.name),
321×
        ui::sep() + &status(problem, revoked),
331×
        ui::sep() + &ui::dim(ui::ago(sr.attest.hlc.wall_ms)),
34
    )
351×
}
36
373×
fn to_json(
383×
    attest: Option<String>,
393×
    sr: &SignedReceipt,
403×
    problem: Option<&str>,
413×
    revoked: bool,
423×
) -> String {
433×
    let r = &sr.receipt;
446×
    let refs = |v: &[oxy_core::hash::ObjectRef]| json::arr(v.iter().map(|h| json::s(&h.to_hex())));
453×
    json::obj([
463×
        ("attest", json::opt(attest.as_ref(), |a| json::s(a))),
473×
        ("receipt", json::s(&r.hash().to_hex())),
483×
        ("state", json::s(&sr.state().to_hex())),
493×
        ("run", json::s(sr.run())),
503×
        ("job", json::s(&r.job_name)),
513×
        ("exit_code", json::n(r.exit_code)),
523×
        ("duration_ms", json::n(r.duration_ms)),
533×
        ("pipeline", json::s(&r.pipeline_hash.to_hex())),
543×
        ("scope", json::s(&r.scope_tree_hash.to_hex())),
553×
        ("environment", json::s(&r.environment.to_hex())),
563×
        ("inputs", refs(&r.inputs)),
573×
        ("outputs", refs(&r.outputs)),
583×
        ("runner", json::s(&sr.runner.hash().to_hex())),
593×
        ("runner_name", json::s(&sr.runner.name)),
603×
        ("made_ms", json::n(sr.attest.hlc.wall_ms)),
613×
        ("valid", json::b(problem.is_none())),
623×
        ("problem", json::opt(problem, json::s)),
633×
        ("revoked", json::b(revoked)),
64
    ])
653×
}
66
671×
fn detail(sr: &SignedReceipt, problem: Option<&str>, revoked: bool) {
681×
    let r = &sr.receipt;
691×
    println!("{}", line(sr, problem, revoked));
701×
    println!(
71
        "{}",
721×
        ui::kv("run", if sr.run().is_empty() { "-" } else { sr.run() })
73
    );
741×
    println!(
75
        "{}",
761×
        ui::kv("state", ui::hash(format!("#{}", sr.state().short(12))))
77
    );
781×
    println!(
79
        "{}",
801×
        ui::kv("receipt", ui::hash(format!("#{}", r.hash().short(12))))
81
    );
821×
    println!(
83
        "{}",
841×
        ui::kv("pipeline", ui::hash(r.pipeline_hash.short(12)))
85
    );
861×
    println!("{}", ui::kv("scope", ui::hash(r.scope_tree_hash.short(12))));
871×
    println!(
88
        "{}",
891×
        ui::kv("environment", ui::hash(r.environment.short(12)))
90
    );
911×
    println!(
92
        "{}",
931×
        ui::kv(
941×
            "runner",
951×
            format!("{} {}", sr.runner.name, ui::dim(sr.runner.hash().short(12)))
96
        )
97
    );
982×
    for (what, v) in [("input", &r.inputs), ("output", &r.outputs)] {
992×
        for h in v.iter() {
1000×
            println!("{}", ui::kv(what, ui::hash(h.short(12))));
1010×
        }
102
    }
1031×
}
104
105
/// `oxy receipt list [REV]`: the receipts kept for a state.
1062×
pub fn list(rev: Option<&str>, as_json: bool) -> Result<i32> {
1072×
    let repo = open()?;
1082×
    let heads = match rev {
1090×
        Some(r) => repo.resolve_heads(r)?,
1102×
        None => repo.bookmark_heads()?,
111
    };
1122×
    let found = repo.receipts(&heads)?;
1132×
    if as_json {
1142×
        println!(
115
            "{}",
1162×
            json::arr(found.iter().map(|i| to_json(
1171×
                Some(i.attest.to_hex()),
1181×
                &i.signed,
1191×
                i.problem.as_deref(),
1201×
                i.revoked
121
            )))
122
        );
1232×
        return Ok(0);
1240×
    }
1250×
    if found.is_empty() {
1260×
        println!("{}", ui::dim("No receipts for this state."));
1270×
    }
1280×
    for i in &found {
1290×
        println!(
1300×
            "{} {}",
1310×
            ui::hash(format!("#{}", i.attest.short(12))),
1320×
            line(&i.signed, i.problem.as_deref(), i.revoked)
1330×
        );
1340×
    }
1350×
    Ok(0)
1362×
}
137
1382×
fn find(repo: &oxy_core::repo::Repo, prefix: &str, rev: Option<&str>) -> Result<ReceiptInfo> {
1392×
    let heads = match rev {
1400×
        Some(r) => repo.resolve_heads(r)?,
1412×
        None => repo.bookmark_heads()?,
142
    };
1432×
    let p = prefix.trim_start_matches('#').to_ascii_lowercase();
1442×
    let mut hits: Vec<ReceiptInfo> = repo
1452×
        .receipts(&heads)?
1462×
        .into_iter()
1472×
        .filter(|i| i.attest.to_hex().starts_with(&p))
1482×
        .collect();
1492×
    match hits.len() {
1502×
        1 => Ok(hits.remove(0)),
1510×
        0 => bail!("no receipt #{p} for this state; `oxy receipt list` shows them"),
1520×
        n => bail!("#{p} matches {n} receipts; give more of the hash"),
153
    }
1542×
}
155
156
/// `oxy receipt show HASH [--rev REV]`.
1571×
pub fn show(prefix: &str, rev: Option<&str>, as_json: bool) -> Result<i32> {
1581×
    let repo = open()?;
1591×
    let i = find(&repo, prefix, rev)?;
1601×
    if as_json {
1611×
        println!(
1621×
            "{}",
1631×
            to_json(
1641×
                Some(i.attest.to_hex()),
1651×
                &i.signed,
1661×
                i.problem.as_deref(),
1671×
                i.revoked
1681×
            )
1691×
        );
1701×
    } else {
1710×
        detail(&i.signed, i.problem.as_deref(), i.revoked);
1720×
    }
1731×
    Ok(if i.problem.is_some() { 1 } else { 0 })
1741×
}
175
176
/// `oxy receipt export HASH FILE`: the signed receipt, to hand to anyone.
1771×
pub fn export(prefix: &str, file: &str, rev: Option<&str>) -> Result<i32> {
1781×
    let repo = open()?;
1791×
    let i = find(&repo, prefix, rev)?;
1801×
    std::fs::write(file, i.signed.encode())?;
1811×
    println!(
182
        "{} {} {}",
1831×
        ui::done("Exported receipt"),
1841×
        ui::hash(format!("#{}", i.attest.short(12))),
1851×
        ui::path(file)
186
    );
1871×
    Ok(0)
1881×
}
189
1904×
fn read(file: &str) -> Result<SignedReceipt> {
1914×
    let bytes = std::fs::read(file).map_err(|e| anyhow::anyhow!("{file}: {e}"))?;
1924×
    SignedReceipt::decode(&bytes).map_err(|e| anyhow::anyhow!("{file}: not a signed receipt: {e}"))
1934×
}
194
195
/// `oxy receipt verify FILE`: check a signed receipt without keeping it.
1962×
pub fn verify(file: &str, as_json: bool) -> Result<i32> {
1972×
    let sr = read(file)?;
1982×
    let problem = sr.verify().err().map(|e| e.to_string());
1992×
    if as_json {
2001×
        println!("{}", to_json(None, &sr, problem.as_deref(), false));
2011×
    } else {
2021×
        detail(&sr, problem.as_deref(), false);
2031×
    }
2042×
    Ok(if problem.is_some() { 1 } else { 0 })
2052×
}
206
207
/// `oxy receipt import FILE`: verify a signed receipt and keep it.
2082×
pub fn import(file: &str) -> Result<i32> {
2092×
    let repo = open()?;
2102×
    let sr = read(file)?;
2112×
    let r = repo.add_receipt(&sr)?;
2121×
    println!(
213
        "{} {} {} {} {}",
2141×
        ui::done("Kept receipt"),
2151×
        ui::hash(format!("#{}", r.short(12))),
2161×
        ui::subject(&sr.receipt.job_name),
2171×
        ui::dim("by"),
2181×
        ui::author(&sr.runner.name)
219
    );
2201×
    Ok(0)
2212×
}