1use serde_json::{json, Map, Value};
9
10use crate::data_integrity::{self, BuildProofOptions};
11use crate::error::{CoreError, Result};
12use crate::time::{check_clock_skew, parse_protocol_time_ns, window_state_ns, WindowState};
13
14pub const VC_CONTEXT_V2: &str = "https://www.w3.org/ns/credentials/v2";
15pub const VOUCH_CONTEXT_V1: &str = "https://vouch-protocol.com/contexts/v1";
16pub const VC_TYPE: &str = "VerifiableCredential";
17pub const VOUCH_CREDENTIAL_TYPE: &str = "VouchCredential";
18pub const PROTOCOL_VERSION: &str = "1.0";
19
20#[derive(Debug, Clone)]
22pub struct BuildCredentialOptions {
23 pub issuer_did: String,
24 pub credential_id: String,
25 pub intent: Value,
26 pub valid_from: String,
27 pub valid_until: String,
28 pub reputation_score: Option<i64>,
29 pub delegation_chain: Option<Value>,
30 pub credential_status: Option<Value>,
31}
32
33pub fn validate_intent(intent: &Value) -> Result<()> {
36 let obj = intent
37 .as_object()
38 .ok_or_else(|| CoreError::Json("intent must be an object".into()))?;
39 for req in ["action", "target", "resource"] {
40 match obj.get(req).and_then(|v| v.as_str()) {
41 Some(s) if !s.is_empty() => {}
42 _ => {
43 return Err(CoreError::Json(format!(
44 "intent.{req} is REQUIRED and must be a non-empty string"
45 )))
46 }
47 }
48 }
49 Ok(())
50}
51
52pub fn build_vouch_credential(opts: &BuildCredentialOptions) -> Result<Value> {
54 validate_intent(&opts.intent)?;
55
56 let mut subject = Map::new();
57 subject.insert("id".into(), json!(opts.issuer_did));
58 subject.insert("vouchVersion".into(), json!(PROTOCOL_VERSION));
59 subject.insert("intent".into(), opts.intent.clone());
60 if let Some(r) = opts.reputation_score {
61 subject.insert("reputationScore".into(), json!(r.clamp(0, 100)));
62 }
63 if let Some(chain) = &opts.delegation_chain {
64 if chain.as_array().map(|a| !a.is_empty()).unwrap_or(false) {
65 subject.insert("delegationChain".into(), chain.clone());
66 }
67 }
68
69 let mut vc = Map::new();
70 vc.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
71 vc.insert("id".into(), json!(opts.credential_id));
72 vc.insert("type".into(), json!([VC_TYPE, VOUCH_CREDENTIAL_TYPE]));
73 vc.insert("issuer".into(), json!(opts.issuer_did));
74 vc.insert("validFrom".into(), json!(opts.valid_from));
75 vc.insert("validUntil".into(), json!(opts.valid_until));
76 vc.insert("credentialSubject".into(), Value::Object(subject));
77 if let Some(status) = &opts.credential_status {
78 vc.insert("credentialStatus".into(), status.clone());
79 }
80 Ok(Value::Object(vc))
81}
82
83pub fn sign_vouch_credential(
85 opts: &BuildCredentialOptions,
86 raw_private_seed: &[u8],
87 proof_opts: &BuildProofOptions,
88) -> Result<Value> {
89 let cred = build_vouch_credential(opts)?;
90 data_integrity::sign(&cred, raw_private_seed, proof_opts)
91}
92
93pub const SUPPORTED_VOUCH_VERSIONS: &[&str] = &[PROTOCOL_VERSION];
96
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub struct VerifyResult {
102 pub proof_valid: bool,
107 pub time_valid: bool,
110 pub chain_valid: bool,
114}
115
116impl VerifyResult {
117 pub fn is_valid(&self) -> bool {
118 self.proof_valid && self.time_valid && self.chain_valid
119 }
120}
121
122pub fn issuer_did(credential: &Value) -> Option<&str> {
125 match credential.get("issuer") {
126 Some(Value::String(s)) if !s.is_empty() => Some(s.as_str()),
127 Some(Value::Object(o)) => o
128 .get("id")
129 .and_then(|v| v.as_str())
130 .filter(|s| !s.is_empty()),
131 _ => None,
132 }
133}
134
135pub fn proof_bound_to_issuer(proof: &Value, issuer: &str) -> bool {
140 let Some(p) = proof.as_object() else {
141 return false;
142 };
143 if p.get("proofPurpose").and_then(|v| v.as_str()) != Some("assertionMethod") {
144 return false;
145 }
146 match p.get("verificationMethod").and_then(|v| v.as_str()) {
147 Some(vm) if !vm.is_empty() => vm.split('#').next() == Some(issuer),
148 _ => false,
149 }
150}
151
152pub fn check_vouch_version(credential: &Value) -> Result<()> {
155 let version = credential
156 .get("credentialSubject")
157 .and_then(|s| s.get("vouchVersion"));
158 match version.and_then(|v| v.as_str()) {
159 Some(v) if SUPPORTED_VOUCH_VERSIONS.contains(&v) => Ok(()),
160 Some(v) => Err(CoreError::Json(format!(
161 "unsupported vouchVersion {:?}",
162 v.chars().take(32).collect::<String>()
163 ))),
164 None => Err(CoreError::Json(
165 "credentialSubject.vouchVersion is required".into(),
166 )),
167 }
168}
169
170pub fn check_intent_resource(credential: &Value) -> Result<()> {
175 let resource = credential
176 .get("credentialSubject")
177 .and_then(|s| s.get("intent"))
178 .and_then(|i| i.get("resource"));
179 match resource.and_then(|r| r.as_str()) {
180 Some(r) if !r.is_empty() => Ok(()),
181 _ => Err(CoreError::Json(
182 "intent.resource is REQUIRED and must be a non-empty string".into(),
183 )),
184 }
185}
186
187pub fn check_envelope(credential: &Value) -> Result<()> {
192 let ctx_ok = credential
193 .get("@context")
194 .and_then(|c| c.as_array())
195 .and_then(|c| c.first())
196 .and_then(|c| c.as_str())
197 == Some(VC_CONTEXT_V2);
198 if !ctx_ok {
199 return Err(CoreError::Json(
200 "the credential's @context must start with the VC 2.0 context".into(),
201 ));
202 }
203 let types_ok = credential
204 .get("type")
205 .and_then(|t| t.as_array())
206 .map(|t| {
207 [VC_TYPE, VOUCH_CREDENTIAL_TYPE]
208 .iter()
209 .all(|want| t.iter().any(|x| x.as_str() == Some(want)))
210 })
211 .unwrap_or(false);
212 if !types_ok {
213 return Err(CoreError::Json(
214 "the credential's type must include VerifiableCredential and VouchCredential".into(),
215 ));
216 }
217 let subject_ok = credential
218 .get("credentialSubject")
219 .map(|s| s.is_object() && s.get("intent").map(|i| i.is_object()).unwrap_or(false))
220 .unwrap_or(false);
221 if !subject_ok {
222 return Err(CoreError::Json(
223 "credentialSubject and its intent must be objects".into(),
224 ));
225 }
226 Ok(())
227}
228
229fn proof_fields_ok(proof: &Value, issuer: &str) -> Result<bool> {
235 let Some(p) = proof.as_object() else {
236 return Ok(false);
237 };
238 if p.get("type").and_then(|v| v.as_str()) != Some(data_integrity::PROOF_TYPE) {
239 return Ok(false);
240 }
241 let known = matches!(
242 p.get("cryptosuite").and_then(|v| v.as_str()),
243 Some(
244 crate::hybrid::EDDSA_CRYPTOSUITE_ID
245 | crate::hybrid::MLDSA44_CRYPTOSUITE_ID
246 | crate::hybrid::MLDSA44_LEGACY_CRYPTOSUITE_ID
247 | crate::hybrid::HYBRID_COMPOSITE_CRYPTOSUITE_ID
248 )
249 );
250 if !known || !proof_bound_to_issuer(proof, issuer) {
251 return Ok(false);
252 }
253 let has_value = p
254 .get("proofValue")
255 .and_then(|v| v.as_str())
256 .is_some_and(|v| !v.is_empty());
257 if !has_value {
258 return Ok(false);
259 }
260 if let Some(created) = p.get("created") {
261 match created.as_str() {
262 Some(c) => {
263 parse_protocol_time_ns(c)?;
264 }
265 None => {
266 return Err(CoreError::Json(
267 "proof.created must be a time string".into(),
268 ))
269 }
270 }
271 }
272 Ok(true)
273}
274
275pub fn replay_key(issuer: &str, proof_value: &str) -> Result<String> {
282 use sha2::{Digest, Sha256};
283 if issuer.is_empty() || proof_value.is_empty() {
284 return Err(CoreError::Json(
285 "issuer and proofValue must be non-empty strings".into(),
286 ));
287 }
288 let inner = Sha256::digest(proof_value.as_bytes());
289 let mut h = Sha256::new();
290 h.update(issuer.as_bytes());
291 h.update([0u8]);
292 h.update(inner);
293 Ok(h.finalize().iter().map(|b| format!("{b:02x}")).collect())
294}
295
296pub(crate) fn proof_member_ok(proof: &Value, issuer: &str, now: i128, skew: i128) -> bool {
300 if !matches!(proof_fields_ok(proof, issuer), Ok(true)) {
301 return false;
302 }
303 match proof.get("expires") {
304 None => true,
305 Some(Value::String(e)) => match parse_protocol_time_ns(e) {
306 Ok(t) => window_state_ns(now, None, Some(t), skew) == WindowState::Ok,
307 Err(_) => false,
308 },
309 Some(_) => false,
310 }
311}
312
313fn key_matches_issuer(issuer: &str, raw_public_key: &[u8]) -> bool {
318 if issuer.starts_with("did:key:") {
319 return match crate::keys::did_key_to_ed25519(issuer) {
320 Ok(k) => k.as_slice() == raw_public_key,
321 Err(_) => false,
322 };
323 }
324 true
325}
326
327pub fn verify(
342 credential: &Value,
343 raw_public_key: &[u8],
344 now_iso: &str,
345 clock_skew_seconds: i64,
346) -> Result<VerifyResult> {
347 let opts = crate::delegation::ChainOptions::default();
348 Ok(verify_explained(
349 credential,
350 raw_public_key,
351 now_iso,
352 clock_skew_seconds,
353 &opts,
354 )?
355 .0)
356}
357
358pub fn verify_with_roots(
362 credential: &Value,
363 raw_public_key: &[u8],
364 now_iso: &str,
365 clock_skew_seconds: i64,
366 trusted_roots: &[String],
367) -> Result<VerifyResult> {
368 let opts = crate::delegation::ChainOptions {
369 trusted_roots: Some(trusted_roots),
370 ..Default::default()
371 };
372 Ok(verify_explained(
373 credential,
374 raw_public_key,
375 now_iso,
376 clock_skew_seconds,
377 &opts,
378 )?
379 .0)
380}
381
382pub fn verify_explained(
389 credential: &Value,
390 raw_public_key: &[u8],
391 now_iso: &str,
392 clock_skew_seconds: i64,
393 opts: &crate::delegation::ChainOptions,
394) -> Result<(VerifyResult, Option<String>)> {
395 verify_with_keys(
396 credential,
397 raw_public_key,
398 None,
399 now_iso,
400 clock_skew_seconds,
401 opts,
402 )
403}
404
405pub fn verify_with_keys(
429 credential: &Value,
430 ed25519_key: &[u8],
431 mldsa44_key: Option<&[u8]>,
432 now_iso: &str,
433 clock_skew_seconds: i64,
434 opts: &crate::delegation::ChainOptions,
435) -> Result<(VerifyResult, Option<String>)> {
436 check_clock_skew(clock_skew_seconds)?;
437 if let Some(ml) = mldsa44_key {
438 if ml.len() != crate::pq::MLDSA44_PUBLIC_LEN {
439 return Err(CoreError::InvalidKeyLength {
440 expected: crate::pq::MLDSA44_PUBLIC_LEN,
441 got: ml.len(),
442 });
443 }
444 }
445 if let Some(roots) = opts.trusted_roots {
446 for r in roots {
447 crate::did_web::normalize_root(r)?;
448 }
449 }
450 if !credential.is_object() {
451 return Err(CoreError::Json("credential must be an object".into()));
452 }
453 check_envelope(credential)?;
454 check_vouch_version(credential)?;
455 check_intent_resource(credential)?;
456
457 let issuer = issuer_did(credential).filter(|i| i.starts_with("did:") && i.len() > 4);
458 let proof_valid = match (issuer, credential.get("proof")) {
459 (Some(issuer), Some(proof)) => {
460 let members: Vec<&Value> = match proof {
461 Value::Array(items) => items.iter().collect(),
462 other => vec![other],
463 };
464 let mut fields_ok = !members.is_empty();
465 for m in &members {
466 fields_ok = fields_ok && proof_fields_ok(m, issuer)?;
467 }
468 fields_ok
469 && key_matches_issuer(issuer, ed25519_key)
470 && proof_shape_verifies(credential, proof, ed25519_key, mldsa44_key, opts)?
471 }
472 _ => false,
474 };
475 let time_valid = verify_temporal(credential, now_iso, clock_skew_seconds)?;
476 let chain_reason = crate::delegation::verify_delegation_chain_with(
477 credential,
478 now_iso,
479 clock_skew_seconds,
480 opts,
481 );
482 Ok((
483 VerifyResult {
484 proof_valid,
485 time_valid,
486 chain_valid: chain_reason.is_none(),
487 },
488 chain_reason,
489 ))
490}
491
492fn proof_shape_verifies(
494 credential: &Value,
495 proof: &Value,
496 ed25519_key: &[u8],
497 mldsa44_key: Option<&[u8]>,
498 opts: &crate::delegation::ChainOptions,
499) -> Result<bool> {
500 let suite = |p: &Value| {
501 p.get("cryptosuite")
502 .and_then(|v| v.as_str())
503 .unwrap_or_default()
504 .to_string()
505 };
506 match proof {
507 Value::Object(_) => match suite(proof).as_str() {
508 crate::hybrid::EDDSA_CRYPTOSUITE_ID => {
509 if opts.require_pq || mldsa44_key.is_some() {
511 return Ok(false);
512 }
513 data_integrity::verify_proof(credential, ed25519_key)
514 }
515 crate::hybrid::HYBRID_COMPOSITE_CRYPTOSUITE_ID => match mldsa44_key {
516 Some(ml) => crate::hybrid::verify_composite(credential, ed25519_key, ml),
517 None => Ok(false),
518 },
519 _ => Ok(false),
521 },
522 Value::Array(items) => {
523 let mut suites: Vec<String> = items
524 .iter()
525 .map(|p| {
526 let s = suite(p);
527 if s == crate::hybrid::MLDSA44_LEGACY_CRYPTOSUITE_ID {
528 crate::hybrid::MLDSA44_CRYPTOSUITE_ID.to_string()
529 } else {
530 s
531 }
532 })
533 .collect();
534 suites.sort();
535 if suites
536 != [
537 crate::hybrid::EDDSA_CRYPTOSUITE_ID,
538 crate::hybrid::MLDSA44_CRYPTOSUITE_ID,
539 ]
540 {
541 return Ok(false); }
543 match mldsa44_key {
544 Some(ml) => crate::hybrid::verify_dual(credential, ed25519_key, ml),
545 None => Ok(false),
546 }
547 }
548 _ => Ok(false),
549 }
550}
551
552pub fn verify_temporal(credential: &Value, now_iso: &str, clock_skew_seconds: i64) -> Result<bool> {
558 let skew = check_clock_skew(clock_skew_seconds)?;
559 let obj = credential
560 .as_object()
561 .ok_or_else(|| CoreError::Json("credential must be an object".into()))?;
562 let vf = obj
563 .get("validFrom")
564 .and_then(|v| v.as_str())
565 .ok_or_else(|| CoreError::Json("credential missing validFrom".into()))?;
566 let vu = obj
567 .get("validUntil")
568 .and_then(|v| v.as_str())
569 .ok_or_else(|| CoreError::Json("credential missing validUntil".into()))?;
570 let now = parse_protocol_time_ns(now_iso)?;
571 let from = parse_protocol_time_ns(vf)?;
572 let until = parse_protocol_time_ns(vu)?;
573 if window_state_ns(now, Some(from), Some(until), skew) != WindowState::Ok {
574 return Ok(false);
575 }
576 let proofs: Vec<&Value> = match obj.get("proof") {
579 Some(Value::Array(items)) => items.iter().collect(),
580 Some(p) => vec![p],
581 None => Vec::new(),
582 };
583 for p in proofs {
584 match p.get("expires") {
585 None => {}
586 Some(Value::String(e)) => {
587 let expires = parse_protocol_time_ns(e)?;
588 if window_state_ns(now, None, Some(expires), skew) != WindowState::Ok {
589 return Ok(false);
590 }
591 }
592 Some(_) => {
593 return Err(CoreError::Json(
594 "proof.expires must be a time string".into(),
595 ))
596 }
597 }
598 }
599 Ok(true)
600}
601
602#[cfg(test)]
603mod tests {
604 use super::*;
605
606 fn opts() -> BuildCredentialOptions {
607 BuildCredentialOptions {
608 issuer_did: "did:web:agent.example.com".into(),
609 credential_id: "urn:uuid:00000000-0000-4000-8000-000000000000".into(),
610 intent: json!({
611 "action": "read_database",
612 "target": "users_table",
613 "resource": "https://api.example.com/v1/users"
614 }),
615 valid_from: "2026-04-26T10:00:00Z".into(),
616 valid_until: "2026-04-26T10:05:00Z".into(),
617 reputation_score: Some(150),
618 delegation_chain: None,
619 credential_status: None,
620 }
621 }
622
623 #[test]
624 fn builds_expected_shape() {
625 let vc = build_vouch_credential(&opts()).unwrap();
626 assert_eq!(
627 vc["type"],
628 json!(["VerifiableCredential", "VouchCredential"])
629 );
630 assert_eq!(vc["credentialSubject"]["vouchVersion"], json!("1.0"));
631 assert_eq!(vc["credentialSubject"]["reputationScore"], json!(100));
633 }
634
635 #[test]
636 fn rejects_missing_intent_fields() {
637 let mut o = opts();
638 o.intent = json!({ "action": "read", "target": "t" }); assert!(build_vouch_credential(&o).is_err());
640 }
641
642 #[test]
643 fn sign_and_verify_within_window() {
644 let seed = [5u8; 32];
645 let proof_opts =
646 BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
647 let signed = sign_vouch_credential(&opts(), &seed, &proof_opts).unwrap();
648 let pk = crate::keys::Ed25519KeyPair::from_seed(&seed).public_key();
649 let r = verify(&signed, &pk, "2026-04-26T10:02:00Z", 30).unwrap();
650 assert!(r.is_valid());
651 let r2 = verify(&signed, &pk, "2026-04-26T11:00:00Z", 30).unwrap();
653 assert!(r2.proof_valid && !r2.time_valid);
654 }
655
656 fn signed_with(purpose: &str, vm: &str) -> Value {
657 let seed = [5u8; 32];
658 let mut proof_opts = BuildProofOptions::new(vm, "2026-04-26T10:00:00Z");
659 proof_opts.proof_purpose = purpose.into();
660 sign_vouch_credential(&opts(), &seed, &proof_opts).unwrap()
661 }
662
663 fn pk() -> [u8; 32] {
664 crate::keys::Ed25519KeyPair::from_seed(&[5u8; 32]).public_key()
665 }
666
667 const NOW: &str = "2026-04-26T10:02:00Z";
668
669 #[test]
670 fn proof_must_be_an_assertion_by_the_issuer() {
671 let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
672 assert!(verify(&ok, &pk(), NOW, 30).unwrap().is_valid());
673 let auth = signed_with("authentication", "did:web:agent.example.com#key-1");
674 assert!(!verify(&auth, &pk(), NOW, 30).unwrap().proof_valid);
675 let other = signed_with("assertionMethod", "did:web:other.example.com#key-1");
676 assert!(!verify(&other, &pk(), NOW, 30).unwrap().proof_valid);
677 let prefix = signed_with("assertionMethod", "did:web:agent.example.com.evil#key-1");
678 assert!(!verify(&prefix, &pk(), NOW, 30).unwrap().proof_valid);
679 }
680
681 #[test]
682 fn did_key_issuer_must_be_the_signing_key() {
683 let seed = [6u8; 32];
684 let kp = crate::keys::Ed25519KeyPair::from_seed(&seed);
685 let did = kp.did_key();
686 let mut o = opts();
687 o.issuer_did = did.clone();
688 let vm = format!("{did}#{}", did.trim_start_matches("did:key:"));
689 let signed = sign_vouch_credential(
690 &o,
691 &seed,
692 &BuildProofOptions::new(vm, "2026-04-26T10:00:00Z"),
693 )
694 .unwrap();
695 assert!(verify(&signed, &kp.public_key(), NOW, 30)
696 .unwrap()
697 .is_valid());
698 let other = [7u8; 32];
700 let vm = format!("{did}#{}", did.trim_start_matches("did:key:"));
701 let impostor = sign_vouch_credential(
702 &o,
703 &other,
704 &BuildProofOptions::new(vm, "2026-04-26T10:00:00Z"),
705 )
706 .unwrap();
707 let other_pk = crate::keys::Ed25519KeyPair::from_seed(&other).public_key();
708 assert!(!verify(&impostor, &other_pk, NOW, 30).unwrap().proof_valid);
709 }
710
711 #[test]
712 fn vouch_version_and_resource_are_required() {
713 let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
714 for (path, value) in [
715 ("vouchVersion", Value::Null),
716 ("vouchVersion", json!("2.0")),
717 ("vouchVersion", json!(1.0)),
718 ] {
719 let mut c = ok.clone();
720 if value.is_null() {
721 c["credentialSubject"].as_object_mut().unwrap().remove(path);
722 } else {
723 c["credentialSubject"][path] = value;
724 }
725 assert!(verify(&c, &pk(), NOW, 30).is_err(), "{path}");
726 }
727 for bad in [json!(""), json!(42), Value::Null, json!(["https://x"])] {
728 let mut c = ok.clone();
729 c["credentialSubject"]["intent"]["resource"] = bad.clone();
730 assert!(verify(&c, &pk(), NOW, 30).is_err(), "{bad}");
731 }
732 let mut o = opts();
734 o.intent["resource"] = json!("reports/q3.txt");
735 let signed = sign_vouch_credential(
736 &o,
737 &[5u8; 32],
738 &BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z"),
739 )
740 .unwrap();
741 assert!(verify(&signed, &pk(), NOW, 30).unwrap().is_valid());
742 }
743
744 #[test]
745 fn window_rules() {
746 let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
747 for skew in [-1, 121, i64::MAX, i64::MIN] {
749 assert!(verify(&ok, &pk(), NOW, skew).is_err(), "{skew}");
750 assert!(verify_temporal(&ok, NOW, skew).is_err(), "{skew}");
751 }
752 for now in [
754 "2026-04-26T10:02:00",
755 "2026-04-26 10:02:00Z",
756 "2026-04-26t10:02:00z",
757 ] {
758 assert!(verify_temporal(&ok, now, 30).is_err(), "{now}");
759 }
760 assert!(verify_temporal(&ok, "2026-04-26T10:05:00Z", 0).unwrap());
762 assert!(!verify_temporal(&ok, "2026-04-26T10:05:00.000000001Z", 0).unwrap());
763 let inverted =
765 json!({"validFrom": "2026-04-26T10:05:00Z", "validUntil": "2026-04-26T10:00:00Z"});
766 assert!(!verify_temporal(&inverted, "2026-04-26T10:02:00Z", 120).unwrap());
767 let mut c = json!({"validFrom": "2026-04-26T10:00:00Z", "validUntil": "2026-04-26T10:05:00Z",
769 "proof": {"expires": "2026-04-26T10:01:00Z"}});
770 assert!(!verify_temporal(&c, NOW, 30).unwrap());
771 c["proof"]["expires"] = json!("2026-04-26T10:03:00Z");
772 assert!(verify_temporal(&c, NOW, 30).unwrap());
773 c["proof"]["expires"] = json!(5);
774 assert!(verify_temporal(&c, NOW, 30).is_err());
775 }
776
777 #[test]
778 fn proof_context_must_match_the_document() {
779 let mut c = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
780 c["proof"]["@context"] = json!(["https://example.com/other"]);
781 assert!(!verify(&c, &pk(), NOW, 30).unwrap().proof_valid);
782 }
783
784 #[test]
785 fn issuer_object_is_bound_by_its_id() {
786 let mut o = opts();
787 o.issuer_did = "did:web:agent.example.com".into();
788 let mut cred = build_vouch_credential(&o).unwrap();
789 cred["issuer"] = json!({"id": "did:web:agent.example.com", "name": "Agent"});
790 let signed = data_integrity::sign(
791 &cred,
792 &[5u8; 32],
793 &BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z"),
794 )
795 .unwrap();
796 assert!(verify(&signed, &pk(), NOW, 30).unwrap().is_valid());
797 let mut bad = cred.clone();
798 bad["issuer"] = json!(["did:web:agent.example.com"]);
799 let signed = data_integrity::sign(
800 &bad,
801 &[5u8; 32],
802 &BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z"),
803 )
804 .unwrap();
805 assert!(!verify(&signed, &pk(), NOW, 30).unwrap().proof_valid);
806 }
807
808 #[test]
809 fn envelope_must_be_a_vouch_credential() {
810 let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
811 for (key, value) in [
812 ("@context", Value::Null),
813 ("@context", json!("https://www.w3.org/ns/credentials/v2")),
814 ("@context", json!(["https://example.com/other"])),
815 ("type", json!(["VerifiableCredential"])),
816 ("type", json!("VouchCredential")),
817 ] {
818 let mut c = ok.clone();
819 if value.is_null() {
820 c.as_object_mut().unwrap().remove(key);
821 } else {
822 c[key] = value.clone();
823 }
824 assert!(verify(&c, &pk(), NOW, 30).is_err(), "{key} = {value}");
825 }
826 let mut o = opts();
828 o.issuer_did = "agent.example.com".into();
829 let signed = sign_vouch_credential(
830 &o,
831 &[5u8; 32],
832 &BuildProofOptions::new("agent.example.com#key-1", "2026-04-26T10:00:00Z"),
833 )
834 .unwrap();
835 assert!(!verify(&signed, &pk(), NOW, 30).unwrap().proof_valid);
836 let mut c = ok.clone();
838 c["proof"]["created"] = json!("yesterday");
839 assert!(verify(&c, &pk(), NOW, 30).is_err());
840 }
841
842 #[test]
843 fn every_proof_shape_through_one_verifier() {
844 use crate::delegation::ChainOptions;
845 let seed = [5u8; 32];
846 let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
847 let unsigned = build_vouch_credential(&opts()).unwrap();
848 let dual = crate::hybrid::sign_dual(
849 &unsigned,
850 &seed,
851 &ml,
852 "did:web:agent.example.com#key-1",
853 "did:web:agent.example.com#key-2",
854 "2026-04-26T10:00:00Z",
855 )
856 .unwrap();
857 let none = ChainOptions::default();
858 let pq = ChainOptions {
859 require_pq: true,
860 ..Default::default()
861 };
862 let mlk = ml.public_key();
863 let run = |c: &Value, ml: Option<&[u8]>, o: &ChainOptions| {
864 verify_with_keys(c, &pk(), ml, NOW, 30, o).unwrap().0
865 };
866 assert!(run(&dual, Some(&mlk), &none).is_valid());
867 assert!(run(&dual, Some(&mlk), &pq).is_valid());
868 assert!(!run(&dual, None, &none).proof_valid);
870 assert!(!verify(&dual, &pk(), NOW, 30).unwrap().proof_valid);
871 let single = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
874 assert!(run(&single, None, &none).is_valid());
875 assert!(!run(&single, None, &pq).proof_valid);
876 assert!(!run(&single, Some(&mlk), &none).proof_valid);
877 assert!(verify_with_keys(&dual, &pk(), Some(&mlk[..1311]), NOW, 30, &none).is_err());
879 let bad_roots = vec!["127.0.0.1".to_string()];
881 let with_bad = ChainOptions {
882 trusted_roots: Some(&bad_roots),
883 ..Default::default()
884 };
885 assert!(verify_with_keys(&single, &pk(), None, NOW, 30, &with_bad).is_err());
886 let mut lone = dual.clone();
888 lone["proof"] = dual["proof"][1].clone();
889 assert!(!run(&lone, Some(&mlk), &none).proof_valid);
890 let mut extra = dual.clone();
891 extra["proof"]
892 .as_array_mut()
893 .unwrap()
894 .push(dual["proof"][0].clone());
895 assert!(!run(&extra, Some(&mlk), &none).proof_valid);
896 let mut unknown = dual.clone();
898 let mut odd = dual["proof"][0].clone();
899 odd["cryptosuite"] = json!("some-unregistered-suite-2030");
900 unknown["proof"].as_array_mut().unwrap().push(odd);
901 assert!(!run(&unknown, Some(&mlk), &none).proof_valid);
902 }
903
904 #[test]
905 fn replay_key_is_issuer_nul_and_proof_digest() {
906 use sha2::{Digest, Sha256};
907 let k = replay_key("did:web:a.example", "z3abc").unwrap();
908 let mut h = Sha256::new();
909 h.update(b"did:web:a.example\x00");
910 h.update(Sha256::digest(b"z3abc"));
911 let want: String = h.finalize().iter().map(|b| format!("{b:02x}")).collect();
912 assert_eq!(k, want);
913 assert_eq!(k.len(), 64);
914 assert!(replay_key("", "z3abc").is_err());
915 assert!(replay_key("did:web:a.example", "").is_err());
916 assert_ne!(
918 replay_key("did:web:a", "bc").unwrap(),
919 replay_key("did:web:ab", "c").unwrap()
920 );
921 }
922}