use serde_json::{json, Map, Value};
use crate::data_integrity::{self, BuildProofOptions};
use crate::error::{CoreError, Result};
use crate::time::{check_clock_skew, parse_protocol_time_ns, window_state_ns, WindowState};
pub const VC_CONTEXT_V2: &str = "https://www.w3.org/ns/credentials/v2";
pub const VOUCH_CONTEXT_V1: &str = "https://vouch-protocol.com/contexts/v1";
pub const VC_TYPE: &str = "VerifiableCredential";
pub const VOUCH_CREDENTIAL_TYPE: &str = "VouchCredential";
pub const PROTOCOL_VERSION: &str = "1.0";
#[derive(Debug, Clone)]
pub struct BuildCredentialOptions {
pub issuer_did: String,
pub credential_id: String,
pub intent: Value,
pub valid_from: String,
pub valid_until: String,
pub reputation_score: Option<i64>,
pub delegation_chain: Option<Value>,
pub credential_status: Option<Value>,
}
pub fn validate_intent(intent: &Value) -> Result<()> {
let obj = intent
.as_object()
.ok_or_else(|| CoreError::Json("intent must be an object".into()))?;
for req in ["action", "target", "resource"] {
match obj.get(req).and_then(|v| v.as_str()) {
Some(s) if !s.is_empty() => {}
_ => {
return Err(CoreError::Json(format!(
"intent.{req} is REQUIRED and must be a non-empty string"
)))
}
}
}
Ok(())
}
pub fn build_vouch_credential(opts: &BuildCredentialOptions) -> Result<Value> {
validate_intent(&opts.intent)?;
let mut subject = Map::new();
subject.insert("id".into(), json!(opts.issuer_did));
subject.insert("vouchVersion".into(), json!(PROTOCOL_VERSION));
subject.insert("intent".into(), opts.intent.clone());
if let Some(r) = opts.reputation_score {
subject.insert("reputationScore".into(), json!(r.clamp(0, 100)));
}
if let Some(chain) = &opts.delegation_chain {
if chain.as_array().map(|a| !a.is_empty()).unwrap_or(false) {
subject.insert("delegationChain".into(), chain.clone());
}
}
let mut vc = Map::new();
vc.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
vc.insert("id".into(), json!(opts.credential_id));
vc.insert("type".into(), json!([VC_TYPE, VOUCH_CREDENTIAL_TYPE]));
vc.insert("issuer".into(), json!(opts.issuer_did));
vc.insert("validFrom".into(), json!(opts.valid_from));
vc.insert("validUntil".into(), json!(opts.valid_until));
vc.insert("credentialSubject".into(), Value::Object(subject));
if let Some(status) = &opts.credential_status {
vc.insert("credentialStatus".into(), status.clone());
}
Ok(Value::Object(vc))
}
pub fn sign_vouch_credential(
opts: &BuildCredentialOptions,
raw_private_seed: &[u8],
proof_opts: &BuildProofOptions,
) -> Result<Value> {
let cred = build_vouch_credential(opts)?;
data_integrity::sign(&cred, raw_private_seed, proof_opts)
}
pub const SUPPORTED_VOUCH_VERSIONS: &[&str] = &[PROTOCOL_VERSION];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VerifyResult {
pub proof_valid: bool,
pub time_valid: bool,
pub chain_valid: bool,
}
impl VerifyResult {
pub fn is_valid(&self) -> bool {
self.proof_valid && self.time_valid && self.chain_valid
}
}
pub fn issuer_did(credential: &Value) -> Option<&str> {
match credential.get("issuer") {
Some(Value::String(s)) if !s.is_empty() => Some(s.as_str()),
Some(Value::Object(o)) => o
.get("id")
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty()),
_ => None,
}
}
pub fn proof_bound_to_issuer(proof: &Value, issuer: &str) -> bool {
let Some(p) = proof.as_object() else {
return false;
};
if p.get("proofPurpose").and_then(|v| v.as_str()) != Some("assertionMethod") {
return false;
}
match p.get("verificationMethod").and_then(|v| v.as_str()) {
Some(vm) if !vm.is_empty() => vm.split('#').next() == Some(issuer),
_ => false,
}
}
pub fn check_vouch_version(credential: &Value) -> Result<()> {
let version = credential
.get("credentialSubject")
.and_then(|s| s.get("vouchVersion"));
match version.and_then(|v| v.as_str()) {
Some(v) if SUPPORTED_VOUCH_VERSIONS.contains(&v) => Ok(()),
Some(v) => Err(CoreError::Json(format!(
"unsupported vouchVersion {:?}",
v.chars().take(32).collect::<String>()
))),
None => Err(CoreError::Json(
"credentialSubject.vouchVersion is required".into(),
)),
}
}
pub fn check_intent_resource(credential: &Value) -> Result<()> {
let resource = credential
.get("credentialSubject")
.and_then(|s| s.get("intent"))
.and_then(|i| i.get("resource"));
match resource.and_then(|r| r.as_str()) {
Some(r) if !r.is_empty() => Ok(()),
_ => Err(CoreError::Json(
"intent.resource is REQUIRED and must be a non-empty string".into(),
)),
}
}
pub fn check_envelope(credential: &Value) -> Result<()> {
let ctx_ok = credential
.get("@context")
.and_then(|c| c.as_array())
.and_then(|c| c.first())
.and_then(|c| c.as_str())
== Some(VC_CONTEXT_V2);
if !ctx_ok {
return Err(CoreError::Json(
"the credential's @context must start with the VC 2.0 context".into(),
));
}
let types_ok = credential
.get("type")
.and_then(|t| t.as_array())
.map(|t| {
[VC_TYPE, VOUCH_CREDENTIAL_TYPE]
.iter()
.all(|want| t.iter().any(|x| x.as_str() == Some(want)))
})
.unwrap_or(false);
if !types_ok {
return Err(CoreError::Json(
"the credential's type must include VerifiableCredential and VouchCredential".into(),
));
}
let subject_ok = credential
.get("credentialSubject")
.map(|s| s.is_object() && s.get("intent").map(|i| i.is_object()).unwrap_or(false))
.unwrap_or(false);
if !subject_ok {
return Err(CoreError::Json(
"credentialSubject and its intent must be objects".into(),
));
}
Ok(())
}
fn proof_fields_ok(proof: &Value, issuer: &str) -> Result<bool> {
let Some(p) = proof.as_object() else {
return Ok(false);
};
if p.get("type").and_then(|v| v.as_str()) != Some(data_integrity::PROOF_TYPE) {
return Ok(false);
}
let known = matches!(
p.get("cryptosuite").and_then(|v| v.as_str()),
Some(
crate::hybrid::EDDSA_CRYPTOSUITE_ID
| crate::hybrid::MLDSA44_CRYPTOSUITE_ID
| crate::hybrid::MLDSA44_LEGACY_CRYPTOSUITE_ID
| crate::hybrid::HYBRID_COMPOSITE_CRYPTOSUITE_ID
)
);
if !known || !proof_bound_to_issuer(proof, issuer) {
return Ok(false);
}
let has_value = p
.get("proofValue")
.and_then(|v| v.as_str())
.is_some_and(|v| !v.is_empty());
if !has_value {
return Ok(false);
}
if let Some(created) = p.get("created") {
match created.as_str() {
Some(c) => {
parse_protocol_time_ns(c)?;
}
None => {
return Err(CoreError::Json(
"proof.created must be a time string".into(),
))
}
}
}
Ok(true)
}
pub fn replay_key(issuer: &str, proof_value: &str) -> Result<String> {
use sha2::{Digest, Sha256};
if issuer.is_empty() || proof_value.is_empty() {
return Err(CoreError::Json(
"issuer and proofValue must be non-empty strings".into(),
));
}
let inner = Sha256::digest(proof_value.as_bytes());
let mut h = Sha256::new();
h.update(issuer.as_bytes());
h.update([0u8]);
h.update(inner);
Ok(h.finalize().iter().map(|b| format!("{b:02x}")).collect())
}
pub(crate) fn proof_member_ok(proof: &Value, issuer: &str, now: i128, skew: i128) -> bool {
if !matches!(proof_fields_ok(proof, issuer), Ok(true)) {
return false;
}
match proof.get("expires") {
None => true,
Some(Value::String(e)) => match parse_protocol_time_ns(e) {
Ok(t) => window_state_ns(now, None, Some(t), skew) == WindowState::Ok,
Err(_) => false,
},
Some(_) => false,
}
}
fn key_matches_issuer(issuer: &str, raw_public_key: &[u8]) -> bool {
if issuer.starts_with("did:key:") {
return match crate::keys::did_key_to_ed25519(issuer) {
Ok(k) => k.as_slice() == raw_public_key,
Err(_) => false,
};
}
true
}
pub fn verify(
credential: &Value,
raw_public_key: &[u8],
now_iso: &str,
clock_skew_seconds: i64,
) -> Result<VerifyResult> {
let opts = crate::delegation::ChainOptions::default();
Ok(verify_explained(
credential,
raw_public_key,
now_iso,
clock_skew_seconds,
&opts,
)?
.0)
}
pub fn verify_with_roots(
credential: &Value,
raw_public_key: &[u8],
now_iso: &str,
clock_skew_seconds: i64,
trusted_roots: &[String],
) -> Result<VerifyResult> {
let opts = crate::delegation::ChainOptions {
trusted_roots: Some(trusted_roots),
..Default::default()
};
Ok(verify_explained(
credential,
raw_public_key,
now_iso,
clock_skew_seconds,
&opts,
)?
.0)
}
pub fn verify_explained(
credential: &Value,
raw_public_key: &[u8],
now_iso: &str,
clock_skew_seconds: i64,
opts: &crate::delegation::ChainOptions,
) -> Result<(VerifyResult, Option<String>)> {
verify_with_keys(
credential,
raw_public_key,
None,
now_iso,
clock_skew_seconds,
opts,
)
}
pub fn verify_with_keys(
credential: &Value,
ed25519_key: &[u8],
mldsa44_key: Option<&[u8]>,
now_iso: &str,
clock_skew_seconds: i64,
opts: &crate::delegation::ChainOptions,
) -> Result<(VerifyResult, Option<String>)> {
check_clock_skew(clock_skew_seconds)?;
if let Some(ml) = mldsa44_key {
if ml.len() != crate::pq::MLDSA44_PUBLIC_LEN {
return Err(CoreError::InvalidKeyLength {
expected: crate::pq::MLDSA44_PUBLIC_LEN,
got: ml.len(),
});
}
}
if let Some(roots) = opts.trusted_roots {
for r in roots {
crate::did_web::normalize_root(r)?;
}
}
if !credential.is_object() {
return Err(CoreError::Json("credential must be an object".into()));
}
check_envelope(credential)?;
check_vouch_version(credential)?;
check_intent_resource(credential)?;
let issuer = issuer_did(credential).filter(|i| i.starts_with("did:") && i.len() > 4);
let proof_valid = match (issuer, credential.get("proof")) {
(Some(issuer), Some(proof)) => {
let members: Vec<&Value> = match proof {
Value::Array(items) => items.iter().collect(),
other => vec![other],
};
let mut fields_ok = !members.is_empty();
for m in &members {
fields_ok = fields_ok && proof_fields_ok(m, issuer)?;
}
fields_ok
&& key_matches_issuer(issuer, ed25519_key)
&& proof_shape_verifies(credential, proof, ed25519_key, mldsa44_key, opts)?
}
_ => false,
};
let time_valid = verify_temporal(credential, now_iso, clock_skew_seconds)?;
let chain_reason = crate::delegation::verify_delegation_chain_with(
credential,
now_iso,
clock_skew_seconds,
opts,
);
Ok((
VerifyResult {
proof_valid,
time_valid,
chain_valid: chain_reason.is_none(),
},
chain_reason,
))
}
fn proof_shape_verifies(
credential: &Value,
proof: &Value,
ed25519_key: &[u8],
mldsa44_key: Option<&[u8]>,
opts: &crate::delegation::ChainOptions,
) -> Result<bool> {
let suite = |p: &Value| {
p.get("cryptosuite")
.and_then(|v| v.as_str())
.unwrap_or_default()
.to_string()
};
match proof {
Value::Object(_) => match suite(proof).as_str() {
crate::hybrid::EDDSA_CRYPTOSUITE_ID => {
if opts.require_pq || mldsa44_key.is_some() {
return Ok(false);
}
data_integrity::verify_proof(credential, ed25519_key)
}
crate::hybrid::HYBRID_COMPOSITE_CRYPTOSUITE_ID => match mldsa44_key {
Some(ml) => crate::hybrid::verify_composite(credential, ed25519_key, ml),
None => Ok(false),
},
_ => Ok(false),
},
Value::Array(items) => {
let mut suites: Vec<String> = items
.iter()
.map(|p| {
let s = suite(p);
if s == crate::hybrid::MLDSA44_LEGACY_CRYPTOSUITE_ID {
crate::hybrid::MLDSA44_CRYPTOSUITE_ID.to_string()
} else {
s
}
})
.collect();
suites.sort();
if suites
!= [
crate::hybrid::EDDSA_CRYPTOSUITE_ID,
crate::hybrid::MLDSA44_CRYPTOSUITE_ID,
]
{
return Ok(false); }
match mldsa44_key {
Some(ml) => crate::hybrid::verify_dual(credential, ed25519_key, ml),
None => Ok(false),
}
}
_ => Ok(false),
}
}
pub fn verify_temporal(credential: &Value, now_iso: &str, clock_skew_seconds: i64) -> Result<bool> {
let skew = check_clock_skew(clock_skew_seconds)?;
let obj = credential
.as_object()
.ok_or_else(|| CoreError::Json("credential must be an object".into()))?;
let vf = obj
.get("validFrom")
.and_then(|v| v.as_str())
.ok_or_else(|| CoreError::Json("credential missing validFrom".into()))?;
let vu = obj
.get("validUntil")
.and_then(|v| v.as_str())
.ok_or_else(|| CoreError::Json("credential missing validUntil".into()))?;
let now = parse_protocol_time_ns(now_iso)?;
let from = parse_protocol_time_ns(vf)?;
let until = parse_protocol_time_ns(vu)?;
if window_state_ns(now, Some(from), Some(until), skew) != WindowState::Ok {
return Ok(false);
}
let proofs: Vec<&Value> = match obj.get("proof") {
Some(Value::Array(items)) => items.iter().collect(),
Some(p) => vec![p],
None => Vec::new(),
};
for p in proofs {
match p.get("expires") {
None => {}
Some(Value::String(e)) => {
let expires = parse_protocol_time_ns(e)?;
if window_state_ns(now, None, Some(expires), skew) != WindowState::Ok {
return Ok(false);
}
}
Some(_) => {
return Err(CoreError::Json(
"proof.expires must be a time string".into(),
))
}
}
}
Ok(true)
}
#[cfg(test)]
mod tests {
use super::*;
fn opts() -> BuildCredentialOptions {
BuildCredentialOptions {
issuer_did: "did:web:agent.example.com".into(),
credential_id: "urn:uuid:00000000-0000-4000-8000-000000000000".into(),
intent: json!({
"action": "read_database",
"target": "users_table",
"resource": "https://api.example.com/v1/users"
}),
valid_from: "2026-04-26T10:00:00Z".into(),
valid_until: "2026-04-26T10:05:00Z".into(),
reputation_score: Some(150),
delegation_chain: None,
credential_status: None,
}
}
#[test]
fn builds_expected_shape() {
let vc = build_vouch_credential(&opts()).unwrap();
assert_eq!(
vc["type"],
json!(["VerifiableCredential", "VouchCredential"])
);
assert_eq!(vc["credentialSubject"]["vouchVersion"], json!("1.0"));
assert_eq!(vc["credentialSubject"]["reputationScore"], json!(100));
}
#[test]
fn rejects_missing_intent_fields() {
let mut o = opts();
o.intent = json!({ "action": "read", "target": "t" }); assert!(build_vouch_credential(&o).is_err());
}
#[test]
fn sign_and_verify_within_window() {
let seed = [5u8; 32];
let proof_opts =
BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
let signed = sign_vouch_credential(&opts(), &seed, &proof_opts).unwrap();
let pk = crate::keys::Ed25519KeyPair::from_seed(&seed).public_key();
let r = verify(&signed, &pk, "2026-04-26T10:02:00Z", 30).unwrap();
assert!(r.is_valid());
let r2 = verify(&signed, &pk, "2026-04-26T11:00:00Z", 30).unwrap();
assert!(r2.proof_valid && !r2.time_valid);
}
fn signed_with(purpose: &str, vm: &str) -> Value {
let seed = [5u8; 32];
let mut proof_opts = BuildProofOptions::new(vm, "2026-04-26T10:00:00Z");
proof_opts.proof_purpose = purpose.into();
sign_vouch_credential(&opts(), &seed, &proof_opts).unwrap()
}
fn pk() -> [u8; 32] {
crate::keys::Ed25519KeyPair::from_seed(&[5u8; 32]).public_key()
}
const NOW: &str = "2026-04-26T10:02:00Z";
#[test]
fn proof_must_be_an_assertion_by_the_issuer() {
let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
assert!(verify(&ok, &pk(), NOW, 30).unwrap().is_valid());
let auth = signed_with("authentication", "did:web:agent.example.com#key-1");
assert!(!verify(&auth, &pk(), NOW, 30).unwrap().proof_valid);
let other = signed_with("assertionMethod", "did:web:other.example.com#key-1");
assert!(!verify(&other, &pk(), NOW, 30).unwrap().proof_valid);
let prefix = signed_with("assertionMethod", "did:web:agent.example.com.evil#key-1");
assert!(!verify(&prefix, &pk(), NOW, 30).unwrap().proof_valid);
}
#[test]
fn did_key_issuer_must_be_the_signing_key() {
let seed = [6u8; 32];
let kp = crate::keys::Ed25519KeyPair::from_seed(&seed);
let did = kp.did_key();
let mut o = opts();
o.issuer_did = did.clone();
let vm = format!("{did}#{}", did.trim_start_matches("did:key:"));
let signed = sign_vouch_credential(
&o,
&seed,
&BuildProofOptions::new(vm, "2026-04-26T10:00:00Z"),
)
.unwrap();
assert!(verify(&signed, &kp.public_key(), NOW, 30)
.unwrap()
.is_valid());
let other = [7u8; 32];
let vm = format!("{did}#{}", did.trim_start_matches("did:key:"));
let impostor = sign_vouch_credential(
&o,
&other,
&BuildProofOptions::new(vm, "2026-04-26T10:00:00Z"),
)
.unwrap();
let other_pk = crate::keys::Ed25519KeyPair::from_seed(&other).public_key();
assert!(!verify(&impostor, &other_pk, NOW, 30).unwrap().proof_valid);
}
#[test]
fn vouch_version_and_resource_are_required() {
let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
for (path, value) in [
("vouchVersion", Value::Null),
("vouchVersion", json!("2.0")),
("vouchVersion", json!(1.0)),
] {
let mut c = ok.clone();
if value.is_null() {
c["credentialSubject"].as_object_mut().unwrap().remove(path);
} else {
c["credentialSubject"][path] = value;
}
assert!(verify(&c, &pk(), NOW, 30).is_err(), "{path}");
}
for bad in [json!(""), json!(42), Value::Null, json!(["https://x"])] {
let mut c = ok.clone();
c["credentialSubject"]["intent"]["resource"] = bad.clone();
assert!(verify(&c, &pk(), NOW, 30).is_err(), "{bad}");
}
let mut o = opts();
o.intent["resource"] = json!("reports/q3.txt");
let signed = sign_vouch_credential(
&o,
&[5u8; 32],
&BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z"),
)
.unwrap();
assert!(verify(&signed, &pk(), NOW, 30).unwrap().is_valid());
}
#[test]
fn window_rules() {
let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
for skew in [-1, 121, i64::MAX, i64::MIN] {
assert!(verify(&ok, &pk(), NOW, skew).is_err(), "{skew}");
assert!(verify_temporal(&ok, NOW, skew).is_err(), "{skew}");
}
for now in [
"2026-04-26T10:02:00",
"2026-04-26 10:02:00Z",
"2026-04-26t10:02:00z",
] {
assert!(verify_temporal(&ok, now, 30).is_err(), "{now}");
}
assert!(verify_temporal(&ok, "2026-04-26T10:05:00Z", 0).unwrap());
assert!(!verify_temporal(&ok, "2026-04-26T10:05:00.000000001Z", 0).unwrap());
let inverted =
json!({"validFrom": "2026-04-26T10:05:00Z", "validUntil": "2026-04-26T10:00:00Z"});
assert!(!verify_temporal(&inverted, "2026-04-26T10:02:00Z", 120).unwrap());
let mut c = json!({"validFrom": "2026-04-26T10:00:00Z", "validUntil": "2026-04-26T10:05:00Z",
"proof": {"expires": "2026-04-26T10:01:00Z"}});
assert!(!verify_temporal(&c, NOW, 30).unwrap());
c["proof"]["expires"] = json!("2026-04-26T10:03:00Z");
assert!(verify_temporal(&c, NOW, 30).unwrap());
c["proof"]["expires"] = json!(5);
assert!(verify_temporal(&c, NOW, 30).is_err());
}
#[test]
fn proof_context_must_match_the_document() {
let mut c = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
c["proof"]["@context"] = json!(["https://example.com/other"]);
assert!(!verify(&c, &pk(), NOW, 30).unwrap().proof_valid);
}
#[test]
fn issuer_object_is_bound_by_its_id() {
let mut o = opts();
o.issuer_did = "did:web:agent.example.com".into();
let mut cred = build_vouch_credential(&o).unwrap();
cred["issuer"] = json!({"id": "did:web:agent.example.com", "name": "Agent"});
let signed = data_integrity::sign(
&cred,
&[5u8; 32],
&BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z"),
)
.unwrap();
assert!(verify(&signed, &pk(), NOW, 30).unwrap().is_valid());
let mut bad = cred.clone();
bad["issuer"] = json!(["did:web:agent.example.com"]);
let signed = data_integrity::sign(
&bad,
&[5u8; 32],
&BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z"),
)
.unwrap();
assert!(!verify(&signed, &pk(), NOW, 30).unwrap().proof_valid);
}
#[test]
fn envelope_must_be_a_vouch_credential() {
let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
for (key, value) in [
("@context", Value::Null),
("@context", json!("https://www.w3.org/ns/credentials/v2")),
("@context", json!(["https://example.com/other"])),
("type", json!(["VerifiableCredential"])),
("type", json!("VouchCredential")),
] {
let mut c = ok.clone();
if value.is_null() {
c.as_object_mut().unwrap().remove(key);
} else {
c[key] = value.clone();
}
assert!(verify(&c, &pk(), NOW, 30).is_err(), "{key} = {value}");
}
let mut o = opts();
o.issuer_did = "agent.example.com".into();
let signed = sign_vouch_credential(
&o,
&[5u8; 32],
&BuildProofOptions::new("agent.example.com#key-1", "2026-04-26T10:00:00Z"),
)
.unwrap();
assert!(!verify(&signed, &pk(), NOW, 30).unwrap().proof_valid);
let mut c = ok.clone();
c["proof"]["created"] = json!("yesterday");
assert!(verify(&c, &pk(), NOW, 30).is_err());
}
#[test]
fn every_proof_shape_through_one_verifier() {
use crate::delegation::ChainOptions;
let seed = [5u8; 32];
let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
let unsigned = build_vouch_credential(&opts()).unwrap();
let dual = crate::hybrid::sign_dual(
&unsigned,
&seed,
&ml,
"did:web:agent.example.com#key-1",
"did:web:agent.example.com#key-2",
"2026-04-26T10:00:00Z",
)
.unwrap();
let none = ChainOptions::default();
let pq = ChainOptions {
require_pq: true,
..Default::default()
};
let mlk = ml.public_key();
let run = |c: &Value, ml: Option<&[u8]>, o: &ChainOptions| {
verify_with_keys(c, &pk(), ml, NOW, 30, o).unwrap().0
};
assert!(run(&dual, Some(&mlk), &none).is_valid());
assert!(run(&dual, Some(&mlk), &pq).is_valid());
assert!(!run(&dual, None, &none).proof_valid);
assert!(!verify(&dual, &pk(), NOW, 30).unwrap().proof_valid);
let single = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
assert!(run(&single, None, &none).is_valid());
assert!(!run(&single, None, &pq).proof_valid);
assert!(!run(&single, Some(&mlk), &none).proof_valid);
assert!(verify_with_keys(&dual, &pk(), Some(&mlk[..1311]), NOW, 30, &none).is_err());
let bad_roots = vec!["127.0.0.1".to_string()];
let with_bad = ChainOptions {
trusted_roots: Some(&bad_roots),
..Default::default()
};
assert!(verify_with_keys(&single, &pk(), None, NOW, 30, &with_bad).is_err());
let mut lone = dual.clone();
lone["proof"] = dual["proof"][1].clone();
assert!(!run(&lone, Some(&mlk), &none).proof_valid);
let mut extra = dual.clone();
extra["proof"]
.as_array_mut()
.unwrap()
.push(dual["proof"][0].clone());
assert!(!run(&extra, Some(&mlk), &none).proof_valid);
let mut unknown = dual.clone();
let mut odd = dual["proof"][0].clone();
odd["cryptosuite"] = json!("some-unregistered-suite-2030");
unknown["proof"].as_array_mut().unwrap().push(odd);
assert!(!run(&unknown, Some(&mlk), &none).proof_valid);
}
#[test]
fn replay_key_is_issuer_nul_and_proof_digest() {
use sha2::{Digest, Sha256};
let k = replay_key("did:web:a.example", "z3abc").unwrap();
let mut h = Sha256::new();
h.update(b"did:web:a.example\x00");
h.update(Sha256::digest(b"z3abc"));
let want: String = h.finalize().iter().map(|b| format!("{b:02x}")).collect();
assert_eq!(k, want);
assert_eq!(k.len(), 64);
assert!(replay_key("", "z3abc").is_err());
assert!(replay_key("did:web:a.example", "").is_err());
assert_ne!(
replay_key("did:web:a", "bc").unwrap(),
replay_key("did:web:ab", "c").unwrap()
);
}
}