Skip to main content

proof_cli/
artifact.rs

1// Copyright 2026 Proof Engine Contributors
2// SPDX-License-Identifier: MIT OR Apache-2.0
3//! Artifact files: JSON wrappers around canonical CBOR bytes (hex).
4//! JSON is transport-only; the canonical CBOR is the artifact of record
5//! (FORMAT ยง7). Every load re-verifies bytes against schema and recomputes
6//! the id โ€” a file whose bytes do not match its id is rejected, never used.
7
8use crate::Cli;
9use proof_core::model::{AttestationContent, EventContent, Evidence, Relationship};
10use proof_core::{Limits, ProofError};
11use proof_crypto::CreatedAttestation;
12use serde_json::json;
13
14fn write_json(path: &str, value: serde_json::Value) -> Result<(), String> {
15    let text = serde_json::to_string_pretty(&value).map_err(|e| e.to_string())?;
16    std::fs::write(
17        path,
18        text + "
19",
20    )
21    .map_err(|e| format!("write {path}: {e}"))
22}
23
24fn read_json(path: &str) -> Result<serde_json::Value, String> {
25    let text = crate::read_input_file(path)?;
26    serde_json::from_str(&text).map_err(|e| format!("parse {path}: {e}"))
27}
28
29pub fn cbor_to_hex(bytes: &[u8]) -> String {
30    hex::encode(bytes)
31}
32
33/// Required comma/colon-separated list flag โ†’ owned strings.
34fn list(cli: &Cli, name: &str) -> Result<Vec<String>, String> {
35    let mut out = vec![];
36    for item in cli.many(name) {
37        for f in item.split([',', ':']) {
38            if f.is_empty() {
39                return Err(format!("--{name} has an empty entry"));
40            }
41            out.push(f.to_string());
42        }
43    }
44    if out.is_empty() {
45        return Err(format!("missing required flag --{name}"));
46    }
47    Ok(out)
48}
49
50fn req_str(v: &serde_json::Value, file: &str, key: &str) -> Result<String, String> {
51    v.get(key)
52        .and_then(|x| x.as_str())
53        .map(str::to_string)
54        .ok_or_else(|| format!("{file}: missing `{key}`"))
55}
56
57fn opt_str(v: &serde_json::Value, file: &str, key: &str) -> Result<Option<String>, String> {
58    match v.get(key) {
59        None | Some(serde_json::Value::Null) => Ok(None),
60        Some(x) => Ok(Some(
61            x.as_str()
62                .ok_or_else(|| format!("{file}: `{key}` must be a string"))?
63                .to_string(),
64        )),
65    }
66}
67
68// ---------------------------------------------------------------- writers
69
70/// `create-event`: validate, canonicalize, id, write event artifact.
71pub fn write_event(cli: &Cli) -> Result<String, String> {
72    let content = EventContent {
73        v: 1,
74        event_type: proof_core::model::EventType::new(cli.req("type")?),
75        subject: cli.req("subject")?,
76        effective_at: cli.req_u64("effective-at")?,
77        payload_ref: hash_ref_from_hex(&cli.req("payload-hex")?)?,
78        metadata: crate::parse_fields(cli.opt("meta"))?,
79    };
80    let created = proof_crypto::build::create_event(content, &crate::limits())
81        .map_err(|e| format!("create-event: {e}"))?;
82    let out = cli.req("out")?;
83    write_json(
84        &out,
85        json!({
86            "kind": "event",
87            "id": created.id,
88            "cbor": cbor_to_hex(&created.canonical),
89        }),
90    )?;
91    crate::progress(cli.quiet(), &format!("event   {} -> {out}", created.id));
92    Ok(created.id)
93}
94
95/// `attest`: bind issuer to the signing key, sign, write attestation artifact.
96pub fn write_attestation(cli: &Cli) -> Result<String, String> {
97    let key = crate::load_key_opt(cli)?;
98    let content = AttestationContent {
99        v: 1,
100        issuer: key.key_ref(),
101        subject: cli.req("subject")?,
102        claim: proof_core::model::Claim {
103            claim_type: cli.req("claim-type")?,
104            fields: crate::parse_fields(cli.opt("claim"))?,
105        },
106        issued_at: cli.req_u64("issued-at")?,
107        expires_at: cli.opt_u64("expires-at")?,
108        evidence_ref: cli.opt("evidence-ref"),
109    };
110    let created = proof_crypto::build::attest(content, &key, &crate::limits())
111        .map_err(|e| format!("attest: {e}"))?;
112    let out = cli.req("out")?;
113    write_json(
114        &out,
115        json!({
116            "kind": "attestation",
117            "id": created.id,
118            "issuer": created.content.issuer,
119            "cbor": cbor_to_hex(&created.canonical),
120            "sign1_b64": proof_crypto::id::b64u_nopad(&created.sign1),
121        }),
122    )?;
123    crate::progress(
124        cli.quiet(),
125        &format!(
126            "attest  {} (issuer {}) -> {out}",
127            created.id, created.content.issuer
128        ),
129    );
130    Ok(created.id)
131}
132
133/// `add-evidence`: evidence is id-bound only (no signature of its own).
134pub fn write_evidence(cli: &Cli) -> Result<String, String> {
135    let digest = hash_ref_from_hex(&cli.req("digest-hex")?)?;
136    let created = proof_crypto::build::make_evidence(
137        proof_core::model::EvidenceKind::new(cli.req("kind")?),
138        digest,
139        cli.opt("attestation-ref"),
140        cli.opt("hint"),
141        &crate::limits(),
142    )
143    .map_err(|e| format!("add-evidence: {e}"))?;
144    let out = cli.req("out")?;
145    write_json(
146        &out,
147        json!({
148            "kind": "evidence",
149            "id": created.id,
150            "cbor": cbor_to_hex(&created.canonical),
151        }),
152    )?;
153    crate::progress(cli.quiet(), &format!("evidence {} -> {out}", created.id));
154    Ok(created.id)
155}
156
157/// `relate`: bind a relationship edge to its id (grounding is checked later,
158/// at proof build time, by proof-graph).
159pub fn write_relationship(cli: &Cli) -> Result<String, String> {
160    let content = Relationship {
161        v: 1,
162        rel_type: proof_core::model::RelType::new(cli.req("type")?),
163        from: cli.req("from")?,
164        to: cli.req("to")?,
165        evidence_ref: cli.opt("evidence-ref"),
166        attestation_ref: cli.opt("attestation-ref"),
167    };
168    let created = proof_crypto::build::make_relationship(content, &crate::limits())
169        .map_err(|e| format!("relate: {e}"))?;
170    let out = cli.req("out")?;
171    write_json(
172        &out,
173        json!({
174            "kind": "relationship",
175            "id": created.id,
176            "cbor": cbor_to_hex(&created.canonical),
177        }),
178    )?;
179    crate::progress(cli.quiet(), &format!("relate  {} -> {out}", created.id));
180    Ok(created.id)
181}
182
183/// `revoke` / `supersede`: signed lifecycle status objects.
184pub fn write_status_object(cli: &Cli, kind: &str) -> Result<String, String> {
185    let key = crate::load_key_opt(cli)?;
186    let at = cli.req_u64("at")?;
187    let created = if kind == "revoke" {
188        proof_crypto::build::revoke_attestation(
189            &cli.req("target")?,
190            cli.opt("reason").as_deref(),
191            &key,
192            at,
193            &crate::limits(),
194        )
195    } else {
196        proof_crypto::build::supersede_attestation(
197            &cli.req("old")?,
198            &cli.req("new")?,
199            &key,
200            at,
201            &crate::limits(),
202        )
203    }
204    .map_err(|e| format!("{kind}: {e}"))?;
205    let out = cli.req("out")?;
206    write_json(
207        &out,
208        json!({
209            "kind": "status",
210            "id": created.id,
211            "issuer": created.content.issuer,
212            "claim_type": created.content.claim.claim_type,
213            "cbor": cbor_to_hex(&created.canonical),
214            "sign1_b64": proof_crypto::id::b64u_nopad(&created.sign1),
215        }),
216    )?;
217    crate::progress(
218        cli.quiet(),
219        &format!("status  {} ({}) -> {out}", created.id, kind),
220    );
221    Ok(created.id)
222}
223
224/// Write a proof artifact: the whole canonical proof CBOR plus its id.
225pub fn write_proof_file(path: &str, id: &str, canonical: &[u8]) -> Result<(), String> {
226    write_json(
227        path,
228        json!({
229            "kind": "proof",
230            "id": id,
231            "cbor": cbor_to_hex(canonical),
232        }),
233    )
234}
235
236// ---------------------------------------------------------------- loaders
237
238/// Digest hex (64 chars = SHA-256, 96 = SHA-384) โ†’ HashRef.
239pub fn hash_ref_from_hex(s: &str) -> Result<proof_core::HashRef, String> {
240    let d = hex::decode(s).map_err(|e| format!("bad digest hex: {e}"))?;
241    let alg = match d.len() {
242        32 => proof_core::HashAlgorithm::Sha256,
243        48 => proof_core::HashAlgorithm::Sha384,
244        _ => return Err("digest must be 64 (SHA-256) or 96 (SHA-384) hex chars".into()),
245    };
246    proof_core::HashRef::new(alg, d).map_err(|e| e.to_string())
247}
248
249/// Load + fully re-verify an event artifact. The file's `id`, if present,
250/// must match the id recomputed from the bytes.
251// PE-CLI-002: re-verify on load; files are transport, never authority.
252pub fn load_event(path: &str, limits: &Limits) -> Result<EventContent, String> {
253    let v = read_json(path)?;
254    let bytes =
255        hex::decode(req_str(&v, path, "cbor")?).map_err(|e| format!("{path}: bad hex: {e}"))?;
256    let expect = opt_str(&v, path, "id")?;
257    let (_, id) = proof_crypto::build::verify_event(&bytes, expect.as_deref(), limits)
258        .map_err(|e: ProofError| format!("{path}: {e}"))?;
259    let content = proof_format::schema::cbor_to_event(
260        &proof_format::cbor::decode_strict(&bytes, limits).map_err(|e| format!("{path}: {e}"))?,
261        limits,
262    )
263    .map_err(|e| format!("{path}: {e}"))?;
264    eprintln!("loaded event {id} ({path})");
265    Ok(content)
266}
267
268/// Load + fully re-verify a signed attestation artifact: COSE envelope,
269/// issuer binding, canonical bytes, payload agreement, and id binding.
270pub fn load_attestation(path: &str, limits: &Limits) -> Result<CreatedAttestation, String> {
271    let v = read_json(path)?;
272    let bytes =
273        hex::decode(req_str(&v, path, "cbor")?).map_err(|e| format!("{path}: bad hex: {e}"))?;
274    let sign1 = proof_crypto::id::b64u_decode(&req_str(&v, path, "sign1_b64")?)
275        .map_err(|e| format!("{path}: bad sign1_b64: {e}"))?;
276    let issuer = opt_str(&v, path, "issuer")?.ok_or_else(|| format!("{path}: missing `issuer`"))?;
277    let (content, id) = proof_crypto::build::verify_attestation(
278        &sign1,
279        &issuer,
280        &proof_crypto::AllowedAlgs::default(),
281        limits,
282    )
283    .map_err(|e: ProofError| format!("{path}: {e}"))?;
284    if let Some(expect) = opt_str(&v, path, "id")? {
285        if expect != id {
286            return Err(format!(
287                "{path}: id mismatch (file says {expect}, bytes are {id})"
288            ));
289        }
290    }
291    // The standalone `cbor` field must be canonical and must describe the
292    // same attestation the envelope authenticates.
293    let value =
294        proof_format::cbor::decode_strict(&bytes, limits).map_err(|e| format!("{path}: {e}"))?;
295    if proof_format::cbor::encode_canonical(&value) != bytes {
296        return Err(format!("{path}: attestation CBOR is not canonical"));
297    }
298    let content2 = proof_format::schema::cbor_to_attestation(&value, limits)
299        .map_err(|e| format!("{path}: {e}"))?;
300    if content2 != content {
301        return Err(format!(
302            "{path}: envelope payload does not match CBOR bytes"
303        ));
304    }
305    eprintln!("loaded attestation {id} ({path})");
306    Ok(CreatedAttestation {
307        content,
308        canonical: bytes,
309        id,
310        sign1,
311    })
312}
313
314/// Load + fully re-verify an evidence artifact.
315pub fn load_evidence(path: &str, limits: &Limits) -> Result<Evidence, String> {
316    let v = read_json(path)?;
317    let bytes =
318        hex::decode(req_str(&v, path, "cbor")?).map_err(|e| format!("{path}: bad hex: {e}"))?;
319    let expect = opt_str(&v, path, "id")?;
320    let (_, id) = proof_crypto::build::verify_evidence(&bytes, expect.as_deref(), limits)
321        .map_err(|e: ProofError| format!("{path}: {e}"))?;
322    let content = proof_format::schema::cbor_to_evidence(
323        &proof_format::cbor::decode_strict(&bytes, limits).map_err(|e| format!("{path}: {e}"))?,
324        limits,
325    )
326    .map_err(|e| format!("{path}: {e}"))?;
327    eprintln!("loaded evidence {id} ({path})");
328    Ok(content)
329}
330
331/// Load + fully re-verify a relationship artifact.
332pub fn load_relationship(path: &str, limits: &Limits) -> Result<Relationship, String> {
333    let v = read_json(path)?;
334    let bytes =
335        hex::decode(req_str(&v, path, "cbor")?).map_err(|e| format!("{path}: bad hex: {e}"))?;
336    let expect = opt_str(&v, path, "id")?;
337    let (_, id) = proof_crypto::build::verify_relationship(&bytes, expect.as_deref(), limits)
338        .map_err(|e: ProofError| format!("{path}: {e}"))?;
339    let content = proof_format::schema::cbor_to_relationship(
340        &proof_format::cbor::decode_strict(&bytes, limits).map_err(|e| format!("{path}: {e}"))?,
341        limits,
342    )
343    .map_err(|e| format!("{path}: {e}"))?;
344    eprintln!("loaded relationship {id} ({path})");
345    Ok(content)
346}
347
348/// Load a status artifact as a signed object (signature is verified here;
349/// authority/trust decisions happen later in the pipeline).
350pub fn load_status(path: &str, limits: &Limits) -> Result<proof_crypto::SignedStatus, String> {
351    let v = read_json(path)?;
352    let sign1 = proof_crypto::id::b64u_decode(&req_str(&v, path, "sign1_b64")?)
353        .map_err(|e| format!("{path}: bad sign1_b64: {e}"))?;
354    let issuer = req_str(&v, path, "issuer")?;
355    // The file states who must have signed; the signature, the kid binding,
356    // and the payload issuer are all checked against it inside (a mismatch
357    // fails closed here, and authority is decided later by the pipeline).
358    let content = proof_crypto::build::verify_status_object(
359        &sign1,
360        &issuer,
361        &proof_crypto::AllowedAlgs::default(),
362        limits,
363    )
364    .map_err(|e: ProofError| format!("{path}: {e}"))?;
365    eprintln!("loaded status {} ({path})", content.subject);
366    Ok(proof_crypto::SignedStatus { content, sign1 })
367}
368
369/// Comma/colon list helper for `build` inputs.
370pub fn input_list(cli: &Cli, name: &str) -> Result<Vec<String>, String> {
371    list(cli, name)
372}