use base64::engine::general_purpose::STANDARD as B64;
use base64::Engine;
use ring::digest::{digest, SHA256};
use ring::signature::{UnparsedPublicKey, ED25519};
use serde_json::Value;
use std::io::Read;
use std::time::Duration;
pub const DOMAIN: &[u8] = b"zakuro-receipt:v1\n";
const SCHEMA: &str = "zakuro.job_receipt";
pub const MAX_RECEIPT_BYTES: usize = 256_000;
const FETCH_TIMEOUT: Duration = Duration::from_secs(15);
pub fn sha256_hex(bytes: &[u8]) -> String {
hex::encode(digest(&SHA256, bytes).as_ref())
}
#[derive(Debug, Clone, PartialEq)]
pub struct TrustedKey {
pub raw: Vec<u8>,
pub kid: String,
}
impl TrustedKey {
pub fn from_raw(raw: Vec<u8>) -> Result<Self, String> {
if raw.len() != 32 {
return Err(format!(
"an Ed25519 public key is 32 bytes, this one is {}",
raw.len()
));
}
let kid = hex::encode(&digest(&SHA256, &raw).as_ref()[..8]);
Ok(Self { raw, kid })
}
pub fn parse(s: &str) -> Result<Self, String> {
let s = s.trim();
if s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit()) {
return Self::from_raw(hex::decode(s).map_err(|e| e.to_string())?);
}
let raw = B64
.decode(s)
.map_err(|_| "a public key is 64 hex characters or base64 of 32 bytes".to_string())?;
Self::from_raw(raw)
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum KeySource {
Given,
Fetched(String),
}
impl KeySource {
pub fn label(&self) -> String {
match self {
KeySource::Given => "given with --pubkey".into(),
KeySource::Fetched(url) => {
format!("fetched from {url} (not pinned: this trusts the hub to name its own key)")
}
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Signed {
pub receipt_json: String,
pub signature: String,
}
#[derive(Debug, Clone, PartialEq)]
pub enum VerifyError {
Input(String),
UnknownKey(String),
BadSignature,
Schema(String),
}
impl std::fmt::Display for VerifyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
VerifyError::Input(m) => write!(f, "{m}"),
VerifyError::UnknownKey(kid) => write!(
f,
"the receipt was signed by key {kid}, which is not in the key set used"
),
VerifyError::BadSignature => write!(f, "bad signature"),
VerifyError::Schema(m) => write!(f, "{m}"),
}
}
}
#[derive(Debug, Clone)]
pub struct Verified {
pub receipt_hash: String,
pub legacy: bool,
pub kid: String,
pub body: Value,
}
pub fn verify(signed: &Signed, keys: &[TrustedKey]) -> Result<Verified, VerifyError> {
if signed.receipt_json.len() > MAX_RECEIPT_BYTES {
return Err(VerifyError::Input("receipt is too large".into()));
}
if signed.signature.len() > 256 {
return Err(VerifyError::Input("signature is too long".into()));
}
let sig = B64
.decode(signed.signature.trim())
.map_err(|_| VerifyError::Input("signature is not base64".into()))?;
let bytes = signed.receipt_json.as_bytes();
let body: Value = serde_json::from_slice(bytes)
.map_err(|_| VerifyError::Input("receipt is not JSON".into()))?;
let kid = body
.get("signer")
.and_then(|s| s.get("kid"))
.and_then(Value::as_str)
.ok_or_else(|| VerifyError::Input("receipt has no signer".into()))?
.to_string();
let key = keys
.iter()
.find(|k| k.kid == kid)
.ok_or_else(|| VerifyError::UnknownKey(kid.clone()))?;
let pk = UnparsedPublicKey::new(&ED25519, &key.raw);
let mut message = DOMAIN.to_vec();
message.extend_from_slice(bytes);
let legacy = if pk.verify(&message, &sig).is_ok() {
false
} else if pk.verify(bytes, &sig).is_ok() {
true
} else {
return Err(VerifyError::BadSignature);
};
if body.get("schema").and_then(Value::as_str) != Some(SCHEMA) {
return Err(VerifyError::Schema(
"unknown receipt schema or version".into(),
));
}
let want_v = if legacy { 1 } else { 2 };
if body.get("v").and_then(Value::as_u64) != Some(want_v) {
return Err(if legacy {
VerifyError::BadSignature
} else {
VerifyError::Schema("unknown receipt schema or version".into())
});
}
Ok(Verified {
receipt_hash: sha256_hex(bytes),
legacy,
kid,
body,
})
}
pub fn signed_output_hashes(body: &Value) -> Option<Vec<String>> {
let hashes = body.get("outputs")?.get("hashes")?.as_array()?;
let mut v: Vec<String> = hashes
.iter()
.filter_map(|h| h.as_str().map(str::to_string))
.collect();
v.sort();
Some(v)
}
pub fn check_output_digests(body: &Value, local: &[String]) -> Result<(), String> {
let Some(signed) = signed_output_hashes(body) else {
return Err("the receipt carries no output digests to compare with".into());
};
let count = body["outputs"]["count"].as_u64();
if count.is_some_and(|c| c as usize != signed.len()) {
return Err(
"the receipt names more outputs than it carries valid digests for (hub flagged them invalid)"
.into(),
);
}
let mut local: Vec<String> = local.iter().map(|d| d.to_ascii_lowercase()).collect();
local.sort();
if local != signed {
return Err(format!(
"the outputs on disk ({} file(s)) do not match the digests the receipt signs ({})",
local.len(),
signed.len()
));
}
Ok(())
}
pub fn parse_signed(text: &str) -> Result<Signed, String> {
let v: Value =
serde_json::from_str(text).map_err(|e| format!("not a receipt document: {e}"))?;
let receipt_json = v
.get("receipt_json")
.and_then(Value::as_str)
.ok_or("no `receipt_json` string in the document")?;
let signature = v
.get("signature")
.and_then(Value::as_str)
.ok_or("no `signature` string in the document")?;
Ok(Signed {
receipt_json: receipt_json.to_string(),
signature: signature.to_string(),
})
}
pub fn check_hub_url(base: &str) -> Result<String, String> {
let base = base.trim().trim_end_matches('/');
let rest = if let Some(r) = base.strip_prefix("https://") {
r
} else if let Some(r) = base.strip_prefix("http://") {
let host = r.split(['/', ':']).next().unwrap_or("");
if !matches!(host, "127.0.0.1" | "localhost" | "[::1]") {
return Err(format!(
"{base}: receipts and keys are fetched over HTTPS only"
));
}
r
} else {
return Err(format!("{base}: not an http(s) URL"));
};
if rest.is_empty() {
return Err("empty hub URL".into());
}
Ok(base.to_string())
}
fn http(timeout: Duration) -> ureq::Agent {
ureq::Agent::new_with_config(
ureq::Agent::config_builder()
.http_status_as_error(false)
.timeout_global(Some(timeout))
.build(),
)
}
#[derive(Debug, Clone, PartialEq)]
pub struct FetchError {
pub status: Option<u16>,
pub message: String,
}
impl FetchError {
fn io(message: String) -> Self {
Self {
status: None,
message,
}
}
pub fn permanent(&self) -> bool {
matches!(self.status, Some(s) if (400..500).contains(&s) && s != 408 && s != 429)
}
}
impl std::fmt::Display for FetchError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.message)
}
}
fn get_text(url: &str, timeout: Duration) -> Result<String, FetchError> {
let resp = http(timeout)
.get(url)
.call()
.map_err(|e| FetchError::io(format!("{url}: {e}")))?;
let status = resp.status().as_u16();
let mut body = String::new();
resp.into_body()
.into_reader()
.take(MAX_RECEIPT_BYTES as u64 * 4)
.read_to_string(&mut body)
.map_err(|e| FetchError::io(format!("{url}: {e}")))?;
if status != 200 {
return Err(FetchError {
status: Some(status),
message: format!("{url} answered HTTP {status}"),
});
}
Ok(body)
}
pub fn fetch_pubkeys(base: &str) -> Result<(Vec<TrustedKey>, KeySource), FetchError> {
fetch_pubkeys_within(base, FETCH_TIMEOUT)
}
pub fn fetch_pubkeys_within(
base: &str,
timeout: Duration,
) -> Result<(Vec<TrustedKey>, KeySource), FetchError> {
let base = check_hub_url(base).map_err(FetchError::io)?;
let url = format!("{base}/api/receipts/pubkeys");
let v: Value = serde_json::from_str(&get_text(&url, timeout)?)
.map_err(|e| FetchError::io(format!("{url}: unreadable answer: {e}")))?;
let mut keys = Vec::new();
for k in v
.get("keys")
.and_then(Value::as_array)
.into_iter()
.flatten()
{
if let Some(key) = k
.get("pubkey")
.and_then(Value::as_str)
.and_then(|s| TrustedKey::parse(s).ok())
{
if !keys.contains(&key) {
keys.push(key);
}
}
}
if keys.is_empty() {
return Err(FetchError::io(format!(
"{url}: no usable key in the answer"
)));
}
Ok((keys, KeySource::Fetched(url)))
}
pub fn fetch_receipt(base: &str, hash: &str) -> Result<Signed, FetchError> {
fetch_receipt_within(base, hash, FETCH_TIMEOUT)
}
pub fn fetch_receipt_within(
base: &str,
hash: &str,
timeout: Duration,
) -> Result<Signed, FetchError> {
let base = check_hub_url(base).map_err(FetchError::io)?;
let hash = hash.trim().to_ascii_lowercase();
let url = format!("{base}/api/receipts/{hash}");
let signed = parse_signed(&get_text(&url, timeout)?)
.map_err(|e| FetchError::io(format!("{url}: {e}")))?;
if sha256_hex(signed.receipt_json.as_bytes()) != hash {
return Err(FetchError::io(format!(
"{url}: the receipt served does not hash to {hash}; refusing it"
)));
}
Ok(signed)
}
fn s(v: &Value, path: &[&str]) -> Option<String> {
let mut cur = v;
for p in path {
cur = cur.get(p)?;
}
match cur {
Value::Null => None,
Value::String(x) => Some(x.clone()),
other => Some(other.to_string()),
}
}
pub fn binds(body: &Value) -> Vec<(String, String)> {
let mut out = Vec::new();
let mut add = |label: &str, v: Option<String>| {
if let Some(v) = v {
out.push((label.to_string(), v));
}
};
add("kind", s(body, &["kind"]));
add("issued", s(body, &["issued_at"]));
add(
"payer (commitment, opens with the owner view)",
s(body, &["requester"]),
);
add("executor node", s(body, &["executor", "node"]));
add("executor worker", s(body, &["executor", "worker"]));
add(
"node receipt digest",
s(body, &["executor", "receipt_digest"]),
);
let cost = s(body, &["settlement", "amount"]).map(|a| {
format!(
"{a} {}",
s(body, &["settlement", "currency"]).unwrap_or_default()
)
.trim()
.to_string()
});
add("cost", cost);
add("settlement", s(body, &["settlement", "status"]));
add("settled", s(body, &["settlement", "settled_at"]));
add("started", s(body, &["usage", "started_at"]));
add("finished", s(body, &["usage", "finished_at"]));
add("exit code", s(body, &["usage", "exit_code"]));
if let Some(hashes) = signed_output_hashes(body) {
add("outputs", Some(format!("{} file(s)", hashes.len())));
for h in hashes {
add(" output sha256", Some(h));
}
}
add("trust level (the hub's word)", s(body, &["trust_level"]));
out
}
fn invalid_fields(body: &Value) -> Vec<String> {
body.get("invalid_fields")
.and_then(Value::as_array)
.map(|a| {
a.iter()
.filter_map(|x| x.as_str().map(String::from))
.collect()
})
.unwrap_or_default()
}
const USAGE: &str =
"usage: zc verify <receipt-file | receipt-hash | -> [--pubkey <hex|base64>]... [--json]";
#[derive(Debug, Default, PartialEq)]
pub struct Args {
pub target: Option<String>,
pub pubkeys: Vec<String>,
pub json: bool,
pub help: bool,
}
pub fn parse_args(args: &[String], json: bool) -> Result<Args, String> {
let mut out = Args {
json,
..Args::default()
};
let mut it = args.iter();
while let Some(a) = it.next() {
match a.as_str() {
"-h" | "--help" => out.help = true,
"--json" => out.json = true,
"--pubkey" => out
.pubkeys
.push(it.next().ok_or("--pubkey needs a key")?.clone()),
s if s.starts_with("--pubkey=") => out.pubkeys.push(s["--pubkey=".len()..].to_string()),
"-" => set_target(&mut out, "-")?,
s if s.starts_with('-') => return Err(format!("unknown argument '{s}'")),
s => set_target(&mut out, s)?,
}
}
Ok(out)
}
fn set_target(out: &mut Args, t: &str) -> Result<(), String> {
if out.target.is_some() {
return Err("one receipt at a time".into());
}
out.target = Some(t.to_string());
Ok(())
}
fn is_hash(s: &str) -> bool {
s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit())
}
pub struct Outcome {
pub ok: bool,
pub error: Option<String>,
pub verified: Option<Verified>,
pub source: Option<KeySource>,
pub warnings: Vec<String>,
}
pub fn check(
args: &Args,
stdin: impl FnOnce() -> std::io::Result<String>,
hub_base: impl Fn() -> String,
) -> Outcome {
let fail = |e: String, source: Option<KeySource>| Outcome {
ok: false,
error: Some(e),
verified: None,
source,
warnings: vec![],
};
let Some(target) = args.target.as_deref() else {
return fail("no receipt given".into(), None);
};
let mut hash_asked: Option<String> = None;
let signed = if target == "-" {
stdin()
.map_err(|e| e.to_string())
.and_then(|t| parse_signed(&t))
} else if is_hash(target) {
hash_asked = Some(target.to_ascii_lowercase());
fetch_receipt(&hub_base(), target).map_err(|e| e.to_string())
} else {
std::fs::read_to_string(target)
.map_err(|e| format!("{target}: {e}"))
.and_then(|t| parse_signed(&t))
};
let signed = match signed {
Ok(s) => s,
Err(e) => return fail(e, None),
};
let (keys, source) = if args.pubkeys.is_empty() {
match fetch_pubkeys(&hub_base()) {
Ok(x) => x,
Err(e) => return fail(format!("could not get the hub's receipt keys: {e}"), None),
}
} else {
let mut keys = Vec::new();
for k in &args.pubkeys {
match TrustedKey::parse(k) {
Ok(k) => keys.push(k),
Err(e) => return fail(format!("--pubkey: {e}"), None),
}
}
(keys, KeySource::Given)
};
match verify(&signed, &keys) {
Ok(v) => {
let mut ok = true;
let mut error = None;
if let Some(h) = &hash_asked {
if &v.receipt_hash != h {
ok = false;
error = Some("the receipt does not hash to the hash given".into());
}
}
let mut warnings = Vec::new();
if v.legacy {
warnings.push(
"legacy v1 receipt: signed before domain separation (still valid)".into(),
);
}
let bad = invalid_fields(&v.body);
if !bad.is_empty() {
warnings.push(format!(
"the hub signed these fields as null because the node's report was malformed: {}",
bad.join(", ")
));
}
Outcome {
ok,
error,
verified: Some(v),
source: Some(source),
warnings,
}
}
Err(e) => fail(e.to_string(), Some(source)),
}
}
pub fn render_json(o: &Outcome) -> Value {
serde_json::json!({
"valid": o.ok,
"error": o.error,
"receipt_hash": o.verified.as_ref().map(|v| v.receipt_hash.clone()),
"legacy": o.verified.as_ref().map(|v| v.legacy),
"signer_kid": o.verified.as_ref().map(|v| v.kid.clone()),
"key_source": o.source.as_ref().map(|s| match s {
KeySource::Given => "given".to_string(),
KeySource::Fetched(_) => "fetched".to_string(),
}),
"key_source_detail": o.source.as_ref().map(KeySource::label),
"trust_level": o.verified.as_ref().and_then(|v| s(&v.body, &["trust_level"])),
"warnings": o.warnings,
"receipt": o.verified.as_ref().map(|v| v.body.clone()),
})
}
pub fn render_text(o: &Outcome) -> String {
let mut out = String::new();
match (&o.verified, o.ok) {
(Some(v), true) => {
out.push_str(&format!("VALID receipt {}\n", v.receipt_hash));
out.push_str(&format!(
"signer key {} ({})\n",
v.kid,
o.source.as_ref().map(KeySource::label).unwrap_or_default()
));
for (k, val) in binds(&v.body) {
out.push_str(&format!(" {k}: {val}\n"));
}
}
_ => {
out.push_str(&format!(
"INVALID {}\n",
o.error.as_deref().unwrap_or("not verified")
));
if let Some(src) = &o.source {
out.push_str(&format!(" keys: {}\n", src.label()));
}
}
}
for w in &o.warnings {
out.push_str(&format!(" warning: {w}\n"));
}
out
}
pub fn run_cli(args: &[String], json: bool) -> i32 {
let a = match parse_args(args, json) {
Ok(a) => a,
Err(e) => {
eprintln!("zc verify: {e}\n{USAGE}");
return 2;
}
};
if a.help || a.target.is_none() {
println!(
"{USAGE}\n\nVerify a hub receipt offline: the Ed25519 signature over the exact bytes, then what\n\
it binds. A hash is fetched from the hub; keys come from --pubkey, else from the hub\n\
(labelled as fetched, not pinned). Exit 0 only when everything verifies."
);
return if a.help { 0 } else { 2 };
}
let o = check(
&a,
|| {
let mut t = String::new();
std::io::stdin().read_to_string(&mut t)?;
Ok(t)
},
crate::credentials::default_api_url,
);
if a.json {
println!(
"{}",
serde_json::to_string_pretty(&render_json(&o)).unwrap_or_default()
);
} else if o.ok {
print!("{}", render_text(&o));
} else {
eprint!("{}", render_text(&o));
}
if o.ok {
0
} else {
1
}
}
#[cfg(test)]
pub(crate) mod testkit {
use super::*;
use crate::broker::node_identity::NodeKey;
pub struct Hub {
pub key: NodeKey,
}
impl Hub {
pub fn new() -> Self {
Self {
key: NodeKey::generate(),
}
}
pub fn trusted(&self) -> TrustedKey {
TrustedKey::parse(&self.key.public_b64()).unwrap()
}
pub fn kid(&self) -> String {
self.key.fingerprint()
}
pub fn batch_receipt(&self, hashes: &[String], amount: &str) -> Signed {
let mut sorted = hashes.to_vec();
sorted.sort();
let receipt_json = format!(
concat!(
r#"{{"environment":{{"image_digest_commitment":"aa"}},"#,
r#""executor":{{"node":"{node}","receipt_digest":"bb","receipt_signature":"cc"}},"#,
r#""inputs":{{"count":1}},"invalid_fields":[],"issued_at":"2026-11-10T00:00:00Z","#,
r#""issuer":"zakuro-hub","job":{{"attempts":1,"ref":"dd","space":"ee"}},"#,
r#""kind":"space_batch","outputs":{{"count":{n},"hashes":{hashes}}},"#,
r#""requester":"ff","schema":"zakuro.job_receipt","#,
r#""settlement":{{"amount":"{amount}","currency":"JPY","settled_at":"2026-11-10T00:00:05Z","status":"succeeded"}},"#,
r#""signer":{{"alg":"ed25519","kid":"{kid}"}},"trust_level":"unattested","#,
r#""usage":{{"exit_code":0,"finished_at":"2026-11-10T00:00:04Z","started_at":"2026-11-10T00:00:01Z"}},"v":2}}"#
),
node = "0123456789abcdef",
n = sorted.len(),
hashes = serde_json::to_string(&sorted).unwrap(),
amount = amount,
kid = self.kid(),
);
self.sign(&receipt_json)
}
pub fn transaction_receipt(
&self,
worker_name: Option<&str>,
amount: &str,
status: &str,
) -> Signed {
self.transaction_receipt_on(None, worker_name, amount, status)
}
pub fn transaction_receipt_on(
&self,
node_key: Option<&str>,
worker_name: Option<&str>,
amount: &str,
status: &str,
) -> Signed {
let node_key = match node_key {
Some(k) => format!(r#""node_key":"{k}","#),
None => String::new(),
};
let worker = match worker_name {
Some(n) => format!("\"{}\"", crate::broker::earn_receipt::worker_fingerprint(n)),
None => "null".to_string(),
};
let receipt_json = format!(
concat!(
r#"{{"executor":{{"node":"0123456789abcdef0123456789abcdef",{node_key}"worker":{worker}}},"#,
r#""issued_at":"2026-11-10T00:00:00Z","issuer":"zakuro-hub","#,
r#""job":{{"ref":"dd","route":"batch-sync","type":"job_execution"}},"#,
r#""kind":"transaction","requester":"ff","schema":"zakuro.job_receipt","#,
r#""settlement":{{"amount":"{amount}","currency":"JPY","settled_at":"2026-11-10T00:00:05Z","status":"{status}"}},"#,
r#""signer":{{"alg":"ed25519","kid":"{kid}"}},"trust_level":"unattested","#,
r#""usage":{{"compute_hours":null,"duration_ms":"1000.0000"}},"#,
r#""v":2,"voucher":{{"nonce_digest":null}}}}"#
),
node_key = node_key,
worker = worker,
amount = amount,
status = status,
kid = self.kid(),
);
self.sign(&receipt_json)
}
pub fn sign(&self, receipt_json: &str) -> Signed {
let mut msg = DOMAIN.to_vec();
msg.extend_from_slice(receipt_json.as_bytes());
Signed {
receipt_json: receipt_json.to_string(),
signature: self.key.sign(&msg),
}
}
pub fn public_view(&self, s: &Signed) -> Value {
serde_json::json!({
"receipt_hash": sha256_hex(s.receipt_json.as_bytes()),
"receipt_json": s.receipt_json,
"signature": s.signature,
})
}
pub fn pubkeys_doc(&self) -> Value {
serde_json::json!({"alg": "ed25519", "keys": [
{"kid": self.kid(), "alg": "ed25519", "pubkey": self.key.public_b64(), "current": true}
]})
}
}
}
#[cfg(test)]
mod tests {
use super::testkit::Hub;
use super::*;
fn h(c: char) -> String {
c.to_string().repeat(64)
}
#[test]
fn a_hub_receipt_verifies_and_says_what_it_binds() {
let hub = Hub::new();
let r = hub.batch_receipt(&[h('b'), h('a')], "50.000000");
let v = verify(&r, &[hub.trusted()]).unwrap();
assert!(!v.legacy);
assert_eq!(v.receipt_hash, sha256_hex(r.receipt_json.as_bytes()));
let lines = binds(&v.body);
let get = |k: &str| {
lines
.iter()
.find(|(l, _)| l == k)
.map(|(_, v)| v.clone())
.unwrap()
};
assert_eq!(get("cost"), "50.000000 JPY");
assert_eq!(get("trust level (the hub's word)"), "unattested");
assert_eq!(get("outputs"), "2 file(s)");
assert_eq!(get("executor node"), "0123456789abcdef");
}
#[test]
fn tampering_with_one_byte_breaks_the_signature() {
let hub = Hub::new();
let mut r = hub.batch_receipt(&[h('a')], "50.000000");
r.receipt_json = r.receipt_json.replace("50.000000", "51.000000");
assert_eq!(
verify(&r, &[hub.trusted()]).unwrap_err(),
VerifyError::BadSignature
);
}
#[test]
fn a_key_outside_the_set_is_named_not_guessed() {
let hub = Hub::new();
let other = Hub::new();
let r = hub.batch_receipt(&[h('a')], "1.000000");
let e = verify(&r, &[other.trusted()]).unwrap_err();
assert!(matches!(e, VerifyError::UnknownKey(k) if k == hub.kid()));
assert!(verify(&r, &[]).is_err());
}
#[test]
fn a_receipt_signed_without_the_domain_prefix_is_only_a_legacy_v1() {
let hub = Hub::new();
let body = hub.batch_receipt(&[h('a')], "1.000000").receipt_json;
let bare = Signed {
signature: hub.key.sign(body.as_bytes()),
receipt_json: body.clone(),
};
assert_eq!(
verify(&bare, &[hub.trusted()]).unwrap_err(),
VerifyError::BadSignature
);
let v1 = body.replace(r#""v":2"#, r#""v":1"#);
let legacy = Signed {
signature: hub.key.sign(v1.as_bytes()),
receipt_json: v1,
};
assert!(verify(&legacy, &[hub.trusted()]).unwrap().legacy);
}
#[test]
fn a_voucher_signature_cannot_pass_as_a_receipt() {
let hub = Hub::new();
let body = hub.batch_receipt(&[], "1.000000").receipt_json;
let as_voucher = Signed {
signature: hub.key.sign(body.as_bytes()), receipt_json: body,
};
assert!(verify(&as_voucher, &[hub.trusted()]).is_err());
}
#[test]
fn output_digests_are_compared_with_the_signed_list() {
let hub = Hub::new();
let r = hub.batch_receipt(&[h('b'), h('a')], "1.000000");
let v = verify(&r, &[hub.trusted()]).unwrap();
check_output_digests(&v.body, &[h('a'), h('b')]).unwrap();
assert!(check_output_digests(&v.body, &[h('a')]).is_err(), "missing");
assert!(
check_output_digests(&v.body, &[h('a'), h('b'), h('c')]).is_err(),
"extra"
);
assert!(check_output_digests(&v.body, &[h('a'), h('c')]).is_err());
}
#[test]
fn keys_parse_from_hex_and_base64_and_reject_other_lengths() {
let hub = Hub::new();
let raw = TrustedKey::parse(&hub.key.public_b64()).unwrap();
assert_eq!(TrustedKey::parse(&hex::encode(&raw.raw)).unwrap(), raw);
assert_eq!(raw.kid, hub.kid());
assert!(TrustedKey::parse("abcd").is_err());
assert!(TrustedKey::parse(&B64.encode([1u8; 31])).is_err());
}
#[test]
fn plain_http_is_for_loopback_only() {
assert!(check_hub_url("https://hub.example/").is_ok());
assert!(check_hub_url("http://127.0.0.1:9").is_ok());
assert!(check_hub_url("http://hub.example").is_err());
assert!(check_hub_url("ftp://x").is_err());
}
#[test]
fn args_parse_the_documented_shapes() {
let v = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();
let a = parse_args(
&v(&["r.json", "--pubkey", "k1", "--pubkey=k2", "--json"]),
false,
)
.unwrap();
assert_eq!(a.target.as_deref(), Some("r.json"));
assert_eq!(a.pubkeys, vec!["k1", "k2"]);
assert!(a.json);
assert_eq!(
parse_args(&v(&["-"]), false).unwrap().target.as_deref(),
Some("-")
);
assert!(parse_args(&v(&["a", "b"]), false).is_err());
assert!(parse_args(&v(&["--nope"]), false).is_err());
}
#[test]
fn check_reads_a_file_and_a_pubkey_and_exits_ok_only_when_valid() {
let hub = Hub::new();
let r = hub.batch_receipt(&[h('a')], "5.000000");
let dir = std::env::temp_dir().join(format!("zc-verify-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("r.json");
std::fs::write(&file, hub.public_view(&r).to_string()).unwrap();
let args = Args {
target: Some(file.display().to_string()),
pubkeys: vec![hex::encode(&hub.trusted().raw)],
..Args::default()
};
let o = check(&args, || unreachable!(), || unreachable!("no hub needed"));
assert!(o.ok, "{:?}", o.error);
assert!(render_text(&o).starts_with("VALID"));
assert_eq!(render_json(&o)["key_source"], "given");
let other = Hub::new();
let args = Args {
pubkeys: vec![hex::encode(&other.trusted().raw)],
..args
};
let o = check(&args, || unreachable!(), || unreachable!());
assert!(!o.ok);
assert!(render_text(&o).starts_with("INVALID"));
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn check_reads_stdin() {
let hub = Hub::new();
let r = hub.batch_receipt(&[], "1.000000");
let doc = hub.public_view(&r).to_string();
let args = Args {
target: Some("-".into()),
pubkeys: vec![hub.key.public_b64()],
..Args::default()
};
let o = check(&args, || Ok(doc), || unreachable!());
assert!(o.ok, "{:?}", o.error);
}
fn serve(routes: Vec<(String, String)>) -> (String, std::thread::JoinHandle<()>) {
let server = tiny_http::Server::http("127.0.0.1:0").unwrap();
let base = format!("http://{}", server.server_addr().to_ip().unwrap());
let n = routes.len();
let t = std::thread::spawn(move || {
for _ in 0..n {
let req = server.recv().unwrap();
let body = routes
.iter()
.find(|(p, _)| p == req.url())
.map(|(_, b)| b.clone());
match body {
Some(b) => req.respond(tiny_http::Response::from_string(b)).unwrap(),
None => req
.respond(tiny_http::Response::from_string("no").with_status_code(404))
.unwrap(),
}
}
});
(base, t)
}
#[test]
fn a_hash_is_fetched_with_keys_from_the_hub_and_labelled_fetched() {
let hub = Hub::new();
let r = hub.batch_receipt(&[h('a')], "5.000000");
let hash = sha256_hex(r.receipt_json.as_bytes());
let (base, t) = serve(vec![
(
format!("/api/receipts/{hash}"),
hub.public_view(&r).to_string(),
),
(
"/api/receipts/pubkeys".into(),
hub.pubkeys_doc().to_string(),
),
]);
let args = Args {
target: Some(hash.clone()),
..Args::default()
};
let o = check(&args, || unreachable!(), || base.clone());
t.join().unwrap();
assert!(o.ok, "{:?}", o.error);
assert_eq!(render_json(&o)["key_source"], "fetched");
assert!(render_text(&o).contains("not pinned"));
}
#[test]
fn a_hub_answering_with_another_receipt_is_refused() {
let hub = Hub::new();
let asked = hub.batch_receipt(&[h('a')], "5.000000");
let served = hub.batch_receipt(&[h('b')], "5.000000");
let hash = sha256_hex(asked.receipt_json.as_bytes());
let (base, t) = serve(vec![(
format!("/api/receipts/{hash}"),
hub.public_view(&served).to_string(),
)]);
let args = Args {
target: Some(hash),
..Args::default()
};
let o = check(&args, || unreachable!(), || base.clone());
t.join().unwrap();
assert!(!o.ok);
assert!(o.error.unwrap().contains("does not hash to"));
}
}