OXYGENHUB
# 47ce8b8e2d4b oxygen / src / cli / receipt.rs
6.9 KiB · Rust · last changed Execution receipts: the receipt object and attestation 1 month ago source blame history raw
fc1a466a Andy McCall ↶ 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
11
fn status(problem: Option<&str>, revoked: bool) -> String {
12
    match (problem, revoked) {
13
        (Some(p), _) => ui::err(format!("{} {p}", ui::glyph("✘", "x"))),
14
        (None, true) => ui::warn(format!("{} runner key revoked", ui::glyph("!", "!"))),
15
        (None, false) => ui::ok(format!("{} signed", ui::glyph("✔", "v"))),
16
    }
17
}
18
19
fn line(sr: &SignedReceipt, problem: Option<&str>, revoked: bool) -> String {
20
    let r = &sr.receipt;
21
    let result = if r.passed() {
22
        ui::ok(format!("{} passed", ui::glyph("●", "*")))
23
    } else {
24
        ui::err(format!("{} exit {}", ui::glyph("●", "*"), r.exit_code))
25
    };
26
    format!(
27
        "{} {}{}{}{}{}",
28
        result,
29
        ui::subject(&r.job_name),
30
        ui::sep() + &ui::dim(format!("{:.1} s", r.duration_ms as f64 / 1000.0)),
31
        ui::sep() + &ui::author(&sr.runner.name),
32
        ui::sep() + &status(problem, revoked),
33
        ui::sep() + &ui::dim(ui::ago(sr.attest.hlc.wall_ms)),
34
    )
35
}
36
37
fn to_json(
38
    attest: Option<String>,
39
    sr: &SignedReceipt,
40
    problem: Option<&str>,
41
    revoked: bool,
42
) -> String {
43
    let r = &sr.receipt;
44
    let refs = |v: &[oxy_core::hash::ObjectRef]| json::arr(v.iter().map(|h| json::s(&h.to_hex())));
45
    json::obj([
46
        ("attest", json::opt(attest.as_ref(), |a| json::s(a))),
47
        ("receipt", json::s(&r.hash().to_hex())),
48
        ("state", json::s(&sr.state().to_hex())),
49
        ("run", json::s(sr.run())),
50
        ("job", json::s(&r.job_name)),
51
        ("exit_code", json::n(r.exit_code)),
52
        ("duration_ms", json::n(r.duration_ms)),
53
        ("pipeline", json::s(&r.pipeline_hash.to_hex())),
54
        ("scope", json::s(&r.scope_tree_hash.to_hex())),
55
        ("environment", json::s(&r.environment.to_hex())),
56
        ("inputs", refs(&r.inputs)),
57
        ("outputs", refs(&r.outputs)),
58
        ("runner", json::s(&sr.runner.hash().to_hex())),
59
        ("runner_name", json::s(&sr.runner.name)),
60
        ("made_ms", json::n(sr.attest.hlc.wall_ms)),
61
        ("valid", json::b(problem.is_none())),
62
        ("problem", json::opt(problem, json::s)),
63
        ("revoked", json::b(revoked)),
64
    ])
65
}
66
67
fn detail(sr: &SignedReceipt, problem: Option<&str>, revoked: bool) {
68
    let r = &sr.receipt;
69
    println!("{}", line(sr, problem, revoked));
70
    println!(
71
        "{}",
72
        ui::kv("run", if sr.run().is_empty() { "-" } else { sr.run() })
73
    );
74
    println!(
75
        "{}",
76
        ui::kv("state", ui::hash(format!("#{}", sr.state().short(12))))
77
    );
78
    println!(
79
        "{}",
80
        ui::kv("receipt", ui::hash(format!("#{}", r.hash().short(12))))
81
    );
82
    println!(
83
        "{}",
84
        ui::kv("pipeline", ui::hash(r.pipeline_hash.short(12)))
85
    );
86
    println!("{}", ui::kv("scope", ui::hash(r.scope_tree_hash.short(12))));
87
    println!(
88
        "{}",
89
        ui::kv("environment", ui::hash(r.environment.short(12)))
90
    );
91
    println!(
92
        "{}",
93
        ui::kv(
94
            "runner",
95
            format!("{} {}", sr.runner.name, ui::dim(sr.runner.hash().short(12)))
96
        )
97
    );
98
    for (what, v) in [("input", &r.inputs), ("output", &r.outputs)] {
99
        for h in v.iter() {
100
            println!("{}", ui::kv(what, ui::hash(h.short(12))));
101
        }
102
    }
103
}
104
105
/// `oxy receipt list [REV]`: the receipts kept for a state.
106
pub fn list(rev: Option<&str>, as_json: bool) -> Result<i32> {
107
    let repo = open()?;
108
    let heads = match rev {
109
        Some(r) => repo.resolve_heads(r)?,
110
        None => repo.bookmark_heads()?,
111
    };
112
    let found = repo.receipts(&heads)?;
113
    if as_json {
114
        println!(
115
            "{}",
116
            json::arr(found.iter().map(|i| to_json(
117
                Some(i.attest.to_hex()),
118
                &i.signed,
119
                i.problem.as_deref(),
120
                i.revoked
121
            )))
122
        );
123
        return Ok(0);
124
    }
125
    if found.is_empty() {
126
        println!("{}", ui::dim("No receipts for this state."));
127
    }
128
    for i in &found {
129
        println!(
130
            "{} {}",
131
            ui::hash(format!("#{}", i.attest.short(12))),
132
            line(&i.signed, i.problem.as_deref(), i.revoked)
133
        );
134
    }
135
    Ok(0)
136
}
137
138
fn find(repo: &oxy_core::repo::Repo, prefix: &str, rev: Option<&str>) -> Result<ReceiptInfo> {
139
    let heads = match rev {
140
        Some(r) => repo.resolve_heads(r)?,
141
        None => repo.bookmark_heads()?,
142
    };
143
    let p = prefix.trim_start_matches('#').to_ascii_lowercase();
144
    let mut hits: Vec<ReceiptInfo> = repo
145
        .receipts(&heads)?
146
        .into_iter()
147
        .filter(|i| i.attest.to_hex().starts_with(&p))
148
        .collect();
149
    match hits.len() {
150
        1 => Ok(hits.remove(0)),
151
        0 => bail!("no receipt #{p} for this state; `oxy receipt list` shows them"),
152
        n => bail!("#{p} matches {n} receipts; give more of the hash"),
153
    }
154
}
155
156
/// `oxy receipt show HASH [--rev REV]`.
157
pub fn show(prefix: &str, rev: Option<&str>, as_json: bool) -> Result<i32> {
158
    let repo = open()?;
159
    let i = find(&repo, prefix, rev)?;
160
    if as_json {
161
        println!(
162
            "{}",
163
            to_json(
164
                Some(i.attest.to_hex()),
165
                &i.signed,
166
                i.problem.as_deref(),
167
                i.revoked
168
            )
169
        );
170
    } else {
171
        detail(&i.signed, i.problem.as_deref(), i.revoked);
172
    }
173
    Ok(if i.problem.is_some() { 1 } else { 0 })
174
}
175
176
/// `oxy receipt export HASH FILE`: the signed receipt, to hand to anyone.
177
pub fn export(prefix: &str, file: &str, rev: Option<&str>) -> Result<i32> {
178
    let repo = open()?;
179
    let i = find(&repo, prefix, rev)?;
180
    std::fs::write(file, i.signed.encode())?;
181
    println!(
182
        "{} {} {}",
183
        ui::done("Exported receipt"),
184
        ui::hash(format!("#{}", i.attest.short(12))),
185
        ui::path(file)
186
    );
187
    Ok(0)
188
}
189
190
fn read(file: &str) -> Result<SignedReceipt> {
191
    let bytes = std::fs::read(file).map_err(|e| anyhow::anyhow!("{file}: {e}"))?;
192
    SignedReceipt::decode(&bytes).map_err(|e| anyhow::anyhow!("{file}: not a signed receipt: {e}"))
193
}
194
195
/// `oxy receipt verify FILE`: check a signed receipt without keeping it.
196
pub fn verify(file: &str, as_json: bool) -> Result<i32> {
197
    let sr = read(file)?;
198
    let problem = sr.verify().err().map(|e| e.to_string());
199
    if as_json {
200
        println!("{}", to_json(None, &sr, problem.as_deref(), false));
201
    } else {
202
        detail(&sr, problem.as_deref(), false);
203
    }
204
    Ok(if problem.is_some() { 1 } else { 0 })
205
}
206
207
/// `oxy receipt import FILE`: verify a signed receipt and keep it.
208
pub fn import(file: &str) -> Result<i32> {
209
    let repo = open()?;
210
    let sr = read(file)?;
211
    let r = repo.add_receipt(&sr)?;
212
    println!(
213
        "{} {} {} {} {}",
214
        ui::done("Kept receipt"),
215
        ui::hash(format!("#{}", r.short(12))),
216
        ui::subject(&sr.receipt.job_name),
217
        ui::dim("by"),
218
        ui::author(&sr.runner.name)
219
    );
220
    Ok(0)
221
}