use crate::Cli;
use proof_core::model::{AttestationContent, EventContent, Evidence, Relationship};
use proof_core::{Limits, ProofError};
use proof_crypto::CreatedAttestation;
use serde_json::json;
fn write_json(path: &str, value: serde_json::Value) -> Result<(), String> {
let text = serde_json::to_string_pretty(&value).map_err(|e| e.to_string())?;
std::fs::write(
path,
text + "
",
)
.map_err(|e| format!("write {path}: {e}"))
}
fn read_json(path: &str) -> Result<serde_json::Value, String> {
let text = crate::read_input_file(path)?;
serde_json::from_str(&text).map_err(|e| format!("parse {path}: {e}"))
}
pub fn cbor_to_hex(bytes: &[u8]) -> String {
hex::encode(bytes)
}
fn list(cli: &Cli, name: &str) -> Result<Vec<String>, String> {
let mut out = vec![];
for item in cli.many(name) {
for f in item.split([',', ':']) {
if f.is_empty() {
return Err(format!("--{name} has an empty entry"));
}
out.push(f.to_string());
}
}
if out.is_empty() {
return Err(format!("missing required flag --{name}"));
}
Ok(out)
}
fn req_str(v: &serde_json::Value, file: &str, key: &str) -> Result<String, String> {
v.get(key)
.and_then(|x| x.as_str())
.map(str::to_string)
.ok_or_else(|| format!("{file}: missing `{key}`"))
}
fn opt_str(v: &serde_json::Value, file: &str, key: &str) -> Result<Option<String>, String> {
match v.get(key) {
None | Some(serde_json::Value::Null) => Ok(None),
Some(x) => Ok(Some(
x.as_str()
.ok_or_else(|| format!("{file}: `{key}` must be a string"))?
.to_string(),
)),
}
}
pub fn write_event(cli: &Cli) -> Result<String, String> {
let content = EventContent {
v: 1,
event_type: proof_core::model::EventType::new(cli.req("type")?),
subject: cli.req("subject")?,
effective_at: cli.req_u64("effective-at")?,
payload_ref: hash_ref_from_hex(&cli.req("payload-hex")?)?,
metadata: crate::parse_fields(cli.opt("meta"))?,
};
let created = proof_crypto::build::create_event(content, &crate::limits())
.map_err(|e| format!("create-event: {e}"))?;
let out = cli.req("out")?;
write_json(
&out,
json!({
"kind": "event",
"id": created.id,
"cbor": cbor_to_hex(&created.canonical),
}),
)?;
crate::progress(cli.quiet(), &format!("event {} -> {out}", created.id));
Ok(created.id)
}
pub fn write_attestation(cli: &Cli) -> Result<String, String> {
let key = crate::load_key_opt(cli)?;
let content = AttestationContent {
v: 1,
issuer: key.key_ref(),
subject: cli.req("subject")?,
claim: proof_core::model::Claim {
claim_type: cli.req("claim-type")?,
fields: crate::parse_fields(cli.opt("claim"))?,
},
issued_at: cli.req_u64("issued-at")?,
expires_at: cli.opt_u64("expires-at")?,
evidence_ref: cli.opt("evidence-ref"),
};
let created = proof_crypto::build::attest(content, &key, &crate::limits())
.map_err(|e| format!("attest: {e}"))?;
let out = cli.req("out")?;
write_json(
&out,
json!({
"kind": "attestation",
"id": created.id,
"issuer": created.content.issuer,
"cbor": cbor_to_hex(&created.canonical),
"sign1_b64": proof_crypto::id::b64u_nopad(&created.sign1),
}),
)?;
crate::progress(
cli.quiet(),
&format!(
"attest {} (issuer {}) -> {out}",
created.id, created.content.issuer
),
);
Ok(created.id)
}
pub fn write_evidence(cli: &Cli) -> Result<String, String> {
let digest = hash_ref_from_hex(&cli.req("digest-hex")?)?;
let created = proof_crypto::build::make_evidence(
proof_core::model::EvidenceKind::new(cli.req("kind")?),
digest,
cli.opt("attestation-ref"),
cli.opt("hint"),
&crate::limits(),
)
.map_err(|e| format!("add-evidence: {e}"))?;
let out = cli.req("out")?;
write_json(
&out,
json!({
"kind": "evidence",
"id": created.id,
"cbor": cbor_to_hex(&created.canonical),
}),
)?;
crate::progress(cli.quiet(), &format!("evidence {} -> {out}", created.id));
Ok(created.id)
}
pub fn write_relationship(cli: &Cli) -> Result<String, String> {
let content = Relationship {
v: 1,
rel_type: proof_core::model::RelType::new(cli.req("type")?),
from: cli.req("from")?,
to: cli.req("to")?,
evidence_ref: cli.opt("evidence-ref"),
attestation_ref: cli.opt("attestation-ref"),
};
let created = proof_crypto::build::make_relationship(content, &crate::limits())
.map_err(|e| format!("relate: {e}"))?;
let out = cli.req("out")?;
write_json(
&out,
json!({
"kind": "relationship",
"id": created.id,
"cbor": cbor_to_hex(&created.canonical),
}),
)?;
crate::progress(cli.quiet(), &format!("relate {} -> {out}", created.id));
Ok(created.id)
}
pub fn write_status_object(cli: &Cli, kind: &str) -> Result<String, String> {
let key = crate::load_key_opt(cli)?;
let at = cli.req_u64("at")?;
let created = if kind == "revoke" {
proof_crypto::build::revoke_attestation(
&cli.req("target")?,
cli.opt("reason").as_deref(),
&key,
at,
&crate::limits(),
)
} else {
proof_crypto::build::supersede_attestation(
&cli.req("old")?,
&cli.req("new")?,
&key,
at,
&crate::limits(),
)
}
.map_err(|e| format!("{kind}: {e}"))?;
let out = cli.req("out")?;
write_json(
&out,
json!({
"kind": "status",
"id": created.id,
"issuer": created.content.issuer,
"claim_type": created.content.claim.claim_type,
"cbor": cbor_to_hex(&created.canonical),
"sign1_b64": proof_crypto::id::b64u_nopad(&created.sign1),
}),
)?;
crate::progress(
cli.quiet(),
&format!("status {} ({}) -> {out}", created.id, kind),
);
Ok(created.id)
}
pub fn write_proof_file(path: &str, id: &str, canonical: &[u8]) -> Result<(), String> {
write_json(
path,
json!({
"kind": "proof",
"id": id,
"cbor": cbor_to_hex(canonical),
}),
)
}
pub fn hash_ref_from_hex(s: &str) -> Result<proof_core::HashRef, String> {
let d = hex::decode(s).map_err(|e| format!("bad digest hex: {e}"))?;
let alg = match d.len() {
32 => proof_core::HashAlgorithm::Sha256,
48 => proof_core::HashAlgorithm::Sha384,
_ => return Err("digest must be 64 (SHA-256) or 96 (SHA-384) hex chars".into()),
};
proof_core::HashRef::new(alg, d).map_err(|e| e.to_string())
}
pub fn load_event(path: &str, limits: &Limits) -> Result<EventContent, String> {
let v = read_json(path)?;
let bytes =
hex::decode(req_str(&v, path, "cbor")?).map_err(|e| format!("{path}: bad hex: {e}"))?;
let expect = opt_str(&v, path, "id")?;
let (_, id) = proof_crypto::build::verify_event(&bytes, expect.as_deref(), limits)
.map_err(|e: ProofError| format!("{path}: {e}"))?;
let content = proof_format::schema::cbor_to_event(
&proof_format::cbor::decode_strict(&bytes, limits).map_err(|e| format!("{path}: {e}"))?,
limits,
)
.map_err(|e| format!("{path}: {e}"))?;
eprintln!("loaded event {id} ({path})");
Ok(content)
}
pub fn load_attestation(path: &str, limits: &Limits) -> Result<CreatedAttestation, String> {
let v = read_json(path)?;
let bytes =
hex::decode(req_str(&v, path, "cbor")?).map_err(|e| format!("{path}: bad hex: {e}"))?;
let sign1 = proof_crypto::id::b64u_decode(&req_str(&v, path, "sign1_b64")?)
.map_err(|e| format!("{path}: bad sign1_b64: {e}"))?;
let issuer = opt_str(&v, path, "issuer")?.ok_or_else(|| format!("{path}: missing `issuer`"))?;
let (content, id) = proof_crypto::build::verify_attestation(
&sign1,
&issuer,
&proof_crypto::AllowedAlgs::default(),
limits,
)
.map_err(|e: ProofError| format!("{path}: {e}"))?;
if let Some(expect) = opt_str(&v, path, "id")? {
if expect != id {
return Err(format!(
"{path}: id mismatch (file says {expect}, bytes are {id})"
));
}
}
let value =
proof_format::cbor::decode_strict(&bytes, limits).map_err(|e| format!("{path}: {e}"))?;
if proof_format::cbor::encode_canonical(&value) != bytes {
return Err(format!("{path}: attestation CBOR is not canonical"));
}
let content2 = proof_format::schema::cbor_to_attestation(&value, limits)
.map_err(|e| format!("{path}: {e}"))?;
if content2 != content {
return Err(format!(
"{path}: envelope payload does not match CBOR bytes"
));
}
eprintln!("loaded attestation {id} ({path})");
Ok(CreatedAttestation {
content,
canonical: bytes,
id,
sign1,
})
}
pub fn load_evidence(path: &str, limits: &Limits) -> Result<Evidence, String> {
let v = read_json(path)?;
let bytes =
hex::decode(req_str(&v, path, "cbor")?).map_err(|e| format!("{path}: bad hex: {e}"))?;
let expect = opt_str(&v, path, "id")?;
let (_, id) = proof_crypto::build::verify_evidence(&bytes, expect.as_deref(), limits)
.map_err(|e: ProofError| format!("{path}: {e}"))?;
let content = proof_format::schema::cbor_to_evidence(
&proof_format::cbor::decode_strict(&bytes, limits).map_err(|e| format!("{path}: {e}"))?,
limits,
)
.map_err(|e| format!("{path}: {e}"))?;
eprintln!("loaded evidence {id} ({path})");
Ok(content)
}
pub fn load_relationship(path: &str, limits: &Limits) -> Result<Relationship, String> {
let v = read_json(path)?;
let bytes =
hex::decode(req_str(&v, path, "cbor")?).map_err(|e| format!("{path}: bad hex: {e}"))?;
let expect = opt_str(&v, path, "id")?;
let (_, id) = proof_crypto::build::verify_relationship(&bytes, expect.as_deref(), limits)
.map_err(|e: ProofError| format!("{path}: {e}"))?;
let content = proof_format::schema::cbor_to_relationship(
&proof_format::cbor::decode_strict(&bytes, limits).map_err(|e| format!("{path}: {e}"))?,
limits,
)
.map_err(|e| format!("{path}: {e}"))?;
eprintln!("loaded relationship {id} ({path})");
Ok(content)
}
pub fn load_status(path: &str, limits: &Limits) -> Result<proof_crypto::SignedStatus, String> {
let v = read_json(path)?;
let sign1 = proof_crypto::id::b64u_decode(&req_str(&v, path, "sign1_b64")?)
.map_err(|e| format!("{path}: bad sign1_b64: {e}"))?;
let issuer = req_str(&v, path, "issuer")?;
let content = proof_crypto::build::verify_status_object(
&sign1,
&issuer,
&proof_crypto::AllowedAlgs::default(),
limits,
)
.map_err(|e: ProofError| format!("{path}: {e}"))?;
eprintln!("loaded status {} ({path})", content.subject);
Ok(proof_crypto::SignedStatus { content, sign1 })
}
pub fn input_list(cli: &Cli, name: &str) -> Result<Vec<String>, String> {
list(cli, name)
}