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 build_credential(opts, None)
55}
56
57pub fn build_sub_grant(opts: &BuildCredentialOptions, parent_grant_digest: &str) -> Result<Value> {
68 build_credential(opts, Some(parent_grant_digest))
69}
70
71pub fn sign_sub_grant(
74 opts: &BuildCredentialOptions,
75 parent_grant_digest: &str,
76 raw_private_seed: &[u8],
77 proof_opts: &BuildProofOptions,
78) -> Result<Value> {
79 let cred = build_sub_grant(opts, parent_grant_digest)?;
80 data_integrity::sign(&cred, raw_private_seed, proof_opts)
81}
82
83fn build_credential(opts: &BuildCredentialOptions, parent_digest: Option<&str>) -> Result<Value> {
84 validate_intent(&opts.intent)?;
85 let has_chain = opts
86 .delegation_chain
87 .as_ref()
88 .and_then(|c| c.as_array())
89 .is_some_and(|a| !a.is_empty());
90 if let Some(digest) = parent_digest {
91 if digest.is_empty() {
92 return Err(CoreError::Json(
93 "parent_grant_digest must be a grant digest string".into(),
94 ));
95 }
96 if has_chain {
97 return Err(CoreError::Json(
98 "a credential carries parentGrantDigest or a delegationChain, never both".into(),
99 ));
100 }
101 }
102
103 let mut subject = Map::new();
104 subject.insert("id".into(), json!(opts.issuer_did));
105 subject.insert("vouchVersion".into(), json!(PROTOCOL_VERSION));
106 subject.insert("intent".into(), opts.intent.clone());
107 if let Some(r) = opts.reputation_score {
108 subject.insert("reputationScore".into(), json!(r.clamp(0, 100)));
109 }
110 if let Some(digest) = parent_digest {
111 subject.insert(
112 crate::grant_chain::PARENT_GRANT_DIGEST.into(),
113 json!(digest),
114 );
115 }
116 if let Some(chain) = &opts.delegation_chain {
117 if chain.as_array().map(|a| !a.is_empty()).unwrap_or(false) {
118 subject.insert("delegationChain".into(), chain.clone());
119 }
120 }
121
122 let mut vc = Map::new();
123 vc.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
124 vc.insert("id".into(), json!(opts.credential_id));
125 vc.insert("type".into(), json!([VC_TYPE, VOUCH_CREDENTIAL_TYPE]));
126 vc.insert("issuer".into(), json!(opts.issuer_did));
127 vc.insert("validFrom".into(), json!(opts.valid_from));
128 vc.insert("validUntil".into(), json!(opts.valid_until));
129 vc.insert("credentialSubject".into(), Value::Object(subject));
130 if let Some(status) = &opts.credential_status {
131 vc.insert("credentialStatus".into(), status.clone());
132 }
133 Ok(Value::Object(vc))
134}
135
136pub fn sign_vouch_credential(
138 opts: &BuildCredentialOptions,
139 raw_private_seed: &[u8],
140 proof_opts: &BuildProofOptions,
141) -> Result<Value> {
142 let cred = build_vouch_credential(opts)?;
143 data_integrity::sign(&cred, raw_private_seed, proof_opts)
144}
145
146pub const SUPPORTED_VOUCH_VERSIONS: &[&str] = &[PROTOCOL_VERSION];
149
150#[derive(Debug, Clone, Copy, PartialEq, Eq)]
154pub struct VerifyResult {
155 pub proof_valid: bool,
160 pub time_valid: bool,
163 pub chain_valid: bool,
167}
168
169impl VerifyResult {
170 pub fn is_valid(&self) -> bool {
171 self.proof_valid && self.time_valid && self.chain_valid
172 }
173}
174
175pub fn issuer_did(credential: &Value) -> Option<&str> {
178 match credential.get("issuer") {
179 Some(Value::String(s)) if !s.is_empty() => Some(s.as_str()),
180 Some(Value::Object(o)) => o
181 .get("id")
182 .and_then(|v| v.as_str())
183 .filter(|s| !s.is_empty()),
184 _ => None,
185 }
186}
187
188pub fn proof_bound_to_issuer(proof: &Value, issuer: &str) -> bool {
193 let Some(p) = proof.as_object() else {
194 return false;
195 };
196 if p.get("proofPurpose").and_then(|v| v.as_str()) != Some("assertionMethod") {
197 return false;
198 }
199 match p.get("verificationMethod").and_then(|v| v.as_str()) {
200 Some(vm) if !vm.is_empty() => vm.split('#').next() == Some(issuer),
201 _ => false,
202 }
203}
204
205pub fn check_vouch_version(credential: &Value) -> Result<()> {
208 let version = credential
209 .get("credentialSubject")
210 .and_then(|s| s.get("vouchVersion"));
211 match version.and_then(|v| v.as_str()) {
212 Some(v) if SUPPORTED_VOUCH_VERSIONS.contains(&v) => Ok(()),
213 Some(v) => Err(CoreError::Json(format!(
214 "unsupported vouchVersion {:?}",
215 v.chars().take(32).collect::<String>()
216 ))),
217 None => Err(CoreError::Json(
218 "credentialSubject.vouchVersion is required".into(),
219 )),
220 }
221}
222
223pub fn check_intent_resource(credential: &Value) -> Result<()> {
228 let resource = credential
229 .get("credentialSubject")
230 .and_then(|s| s.get("intent"))
231 .and_then(|i| i.get("resource"));
232 match resource.and_then(|r| r.as_str()) {
233 Some(r) if !r.is_empty() => Ok(()),
234 _ => Err(CoreError::Json(
235 "intent.resource is REQUIRED and must be a non-empty string".into(),
236 )),
237 }
238}
239
240pub fn check_envelope(credential: &Value) -> Result<()> {
245 let ctx_ok = credential
246 .get("@context")
247 .and_then(|c| c.as_array())
248 .and_then(|c| c.first())
249 .and_then(|c| c.as_str())
250 == Some(VC_CONTEXT_V2);
251 if !ctx_ok {
252 return Err(CoreError::Json(
253 "the credential's @context must start with the VC 2.0 context".into(),
254 ));
255 }
256 let types_ok = credential
257 .get("type")
258 .and_then(|t| t.as_array())
259 .map(|t| {
260 [VC_TYPE, VOUCH_CREDENTIAL_TYPE]
261 .iter()
262 .all(|want| t.iter().any(|x| x.as_str() == Some(want)))
263 })
264 .unwrap_or(false);
265 if !types_ok {
266 return Err(CoreError::Json(
267 "the credential's type must include VerifiableCredential and VouchCredential".into(),
268 ));
269 }
270 let subject_ok = credential
271 .get("credentialSubject")
272 .map(|s| s.is_object() && s.get("intent").map(|i| i.is_object()).unwrap_or(false))
273 .unwrap_or(false);
274 if !subject_ok {
275 return Err(CoreError::Json(
276 "credentialSubject and its intent must be objects".into(),
277 ));
278 }
279 Ok(())
280}
281
282fn proof_fields_ok(proof: &Value, issuer: &str) -> Result<bool> {
288 let Some(p) = proof.as_object() else {
289 return Ok(false);
290 };
291 if p.get("type").and_then(|v| v.as_str()) != Some(data_integrity::PROOF_TYPE) {
292 return Ok(false);
293 }
294 let known = matches!(
295 p.get("cryptosuite").and_then(|v| v.as_str()),
296 Some(
297 crate::hybrid::EDDSA_CRYPTOSUITE_ID
298 | crate::hybrid::MLDSA44_CRYPTOSUITE_ID
299 | crate::hybrid::MLDSA44_LEGACY_CRYPTOSUITE_ID
300 | crate::hybrid::HYBRID_COMPOSITE_CRYPTOSUITE_ID
301 )
302 );
303 if !known || !proof_bound_to_issuer(proof, issuer) {
304 return Ok(false);
305 }
306 let has_value = p
307 .get("proofValue")
308 .and_then(|v| v.as_str())
309 .is_some_and(|v| !v.is_empty());
310 if !has_value {
311 return Ok(false);
312 }
313 if let Some(created) = p.get("created") {
314 match created.as_str() {
315 Some(c) => {
316 parse_protocol_time_ns(c)?;
317 }
318 None => {
319 return Err(CoreError::Json(
320 "proof.created must be a time string".into(),
321 ))
322 }
323 }
324 }
325 Ok(true)
326}
327
328pub fn replay_key(issuer: &str, proof_value: &str) -> Result<String> {
335 use sha2::{Digest, Sha256};
336 if issuer.is_empty() || proof_value.is_empty() {
337 return Err(CoreError::Json(
338 "issuer and proofValue must be non-empty strings".into(),
339 ));
340 }
341 let inner = Sha256::digest(proof_value.as_bytes());
342 let mut h = Sha256::new();
343 h.update(issuer.as_bytes());
344 h.update([0u8]);
345 h.update(inner);
346 Ok(h.finalize().iter().map(|b| format!("{b:02x}")).collect())
347}
348
349pub(crate) fn proof_member_ok(proof: &Value, issuer: &str, now: i128, skew: i128) -> bool {
353 if !matches!(proof_fields_ok(proof, issuer), Ok(true)) {
354 return false;
355 }
356 match proof.get("expires") {
357 None => true,
358 Some(Value::String(e)) => match parse_protocol_time_ns(e) {
359 Ok(t) => window_state_ns(now, None, Some(t), skew) == WindowState::Ok,
360 Err(_) => false,
361 },
362 Some(_) => false,
363 }
364}
365
366fn key_matches_issuer(issuer: &str, raw_public_key: &[u8]) -> bool {
371 if issuer.starts_with("did:key:") {
372 return match crate::keys::did_key_to_ed25519(issuer) {
373 Ok(k) => k.as_slice() == raw_public_key,
374 Err(_) => false,
375 };
376 }
377 true
378}
379
380pub fn verify(
395 credential: &Value,
396 raw_public_key: &[u8],
397 now_iso: &str,
398 clock_skew_seconds: i64,
399) -> Result<VerifyResult> {
400 let opts = crate::delegation::ChainOptions::default();
401 Ok(verify_explained(
402 credential,
403 raw_public_key,
404 now_iso,
405 clock_skew_seconds,
406 &opts,
407 )?
408 .0)
409}
410
411pub fn verify_with_roots(
415 credential: &Value,
416 raw_public_key: &[u8],
417 now_iso: &str,
418 clock_skew_seconds: i64,
419 trusted_roots: &[String],
420) -> Result<VerifyResult> {
421 let opts = crate::delegation::ChainOptions {
422 trusted_roots: Some(trusted_roots),
423 ..Default::default()
424 };
425 Ok(verify_explained(
426 credential,
427 raw_public_key,
428 now_iso,
429 clock_skew_seconds,
430 &opts,
431 )?
432 .0)
433}
434
435pub fn verify_explained(
442 credential: &Value,
443 raw_public_key: &[u8],
444 now_iso: &str,
445 clock_skew_seconds: i64,
446 opts: &crate::delegation::ChainOptions,
447) -> Result<(VerifyResult, Option<String>)> {
448 verify_with_keys(
449 credential,
450 raw_public_key,
451 None,
452 now_iso,
453 clock_skew_seconds,
454 opts,
455 )
456}
457
458pub fn verify_with_keys(
489 credential: &Value,
490 ed25519_key: &[u8],
491 mldsa44_key: Option<&[u8]>,
492 now_iso: &str,
493 clock_skew_seconds: i64,
494 opts: &crate::delegation::ChainOptions,
495) -> Result<(VerifyResult, Option<String>)> {
496 check_clock_skew(clock_skew_seconds)?;
497 if let Some(ml) = mldsa44_key {
498 if ml.len() != crate::pq::MLDSA44_PUBLIC_LEN {
499 return Err(CoreError::InvalidKeyLength {
500 expected: crate::pq::MLDSA44_PUBLIC_LEN,
501 got: ml.len(),
502 });
503 }
504 }
505 if let Some(roots) = opts.trusted_roots {
506 for r in roots {
507 crate::did_web::normalize_root(r)?;
508 }
509 }
510 if !credential.is_object() {
511 return Err(CoreError::Json("credential must be an object".into()));
512 }
513 check_envelope(credential)?;
514 check_vouch_version(credential)?;
515 check_intent_resource(credential)?;
516
517 let issuer = issuer_did(credential).filter(|i| i.starts_with("did:") && i.len() > 4);
518 let proof_valid = match (issuer, credential.get("proof")) {
519 (Some(issuer), Some(proof)) => {
520 let members: Vec<&Value> = match proof {
521 Value::Array(items) => items.iter().collect(),
522 other => vec![other],
523 };
524 let mut fields_ok = !members.is_empty();
525 for m in &members {
526 fields_ok = fields_ok && proof_fields_ok(m, issuer)?;
527 }
528 fields_ok
529 && key_matches_issuer(issuer, ed25519_key)
530 && proof_shape_verifies(credential, proof, ed25519_key, mldsa44_key, opts)?
531 }
532 _ => false,
534 };
535 let time_valid = verify_temporal(credential, now_iso, clock_skew_seconds)?;
536 let chain_reason = crate::delegation::verify_delegation_chain_with(
537 credential,
538 now_iso,
539 clock_skew_seconds,
540 opts,
541 );
542 Ok((
543 VerifyResult {
544 proof_valid,
545 time_valid,
546 chain_valid: chain_reason.is_none(),
547 },
548 chain_reason,
549 ))
550}
551
552fn proof_shape_verifies(
554 credential: &Value,
555 proof: &Value,
556 ed25519_key: &[u8],
557 mldsa44_key: Option<&[u8]>,
558 opts: &crate::delegation::ChainOptions,
559) -> Result<bool> {
560 let suite = |p: &Value| {
561 p.get("cryptosuite")
562 .and_then(|v| v.as_str())
563 .unwrap_or_default()
564 .to_string()
565 };
566 match proof {
567 Value::Object(_) => match suite(proof).as_str() {
568 crate::hybrid::EDDSA_CRYPTOSUITE_ID => {
569 if opts.require_pq || mldsa44_key.is_some() {
571 return Ok(false);
572 }
573 data_integrity::verify_proof(credential, ed25519_key)
574 }
575 crate::hybrid::HYBRID_COMPOSITE_CRYPTOSUITE_ID => match mldsa44_key {
576 Some(ml) => crate::hybrid::verify_composite(credential, ed25519_key, ml),
577 None => Ok(false),
578 },
579 _ => Ok(false),
581 },
582 Value::Array(items) => {
583 let mut suites: Vec<String> = items
584 .iter()
585 .map(|p| {
586 let s = suite(p);
587 if s == crate::hybrid::MLDSA44_LEGACY_CRYPTOSUITE_ID {
588 crate::hybrid::MLDSA44_CRYPTOSUITE_ID.to_string()
589 } else {
590 s
591 }
592 })
593 .collect();
594 suites.sort();
595 if suites
596 != [
597 crate::hybrid::EDDSA_CRYPTOSUITE_ID,
598 crate::hybrid::MLDSA44_CRYPTOSUITE_ID,
599 ]
600 {
601 return Ok(false); }
603 match mldsa44_key {
604 Some(ml) => crate::hybrid::verify_dual(credential, ed25519_key, ml),
605 None => Ok(false),
606 }
607 }
608 _ => Ok(false),
609 }
610}
611
612pub fn verify_temporal(credential: &Value, now_iso: &str, clock_skew_seconds: i64) -> Result<bool> {
618 let skew = check_clock_skew(clock_skew_seconds)?;
619 let obj = credential
620 .as_object()
621 .ok_or_else(|| CoreError::Json("credential must be an object".into()))?;
622 let vf = obj
623 .get("validFrom")
624 .and_then(|v| v.as_str())
625 .ok_or_else(|| CoreError::Json("credential missing validFrom".into()))?;
626 let vu = obj
627 .get("validUntil")
628 .and_then(|v| v.as_str())
629 .ok_or_else(|| CoreError::Json("credential missing validUntil".into()))?;
630 let now = parse_protocol_time_ns(now_iso)?;
631 let from = parse_protocol_time_ns(vf)?;
632 let until = parse_protocol_time_ns(vu)?;
633 if window_state_ns(now, Some(from), Some(until), skew) != WindowState::Ok {
634 return Ok(false);
635 }
636 let proofs: Vec<&Value> = match obj.get("proof") {
639 Some(Value::Array(items)) => items.iter().collect(),
640 Some(p) => vec![p],
641 None => Vec::new(),
642 };
643 for p in proofs {
644 match p.get("expires") {
645 None => {}
646 Some(Value::String(e)) => {
647 let expires = parse_protocol_time_ns(e)?;
648 if window_state_ns(now, None, Some(expires), skew) != WindowState::Ok {
649 return Ok(false);
650 }
651 }
652 Some(_) => {
653 return Err(CoreError::Json(
654 "proof.expires must be a time string".into(),
655 ))
656 }
657 }
658 }
659 Ok(true)
660}
661
662#[cfg(test)]
663mod tests {
664 use super::*;
665
666 fn opts() -> BuildCredentialOptions {
667 BuildCredentialOptions {
668 issuer_did: "did:web:agent.example.com".into(),
669 credential_id: "urn:uuid:00000000-0000-4000-8000-000000000000".into(),
670 intent: json!({
671 "action": "read_database",
672 "target": "users_table",
673 "resource": "https://api.example.com/v1/users"
674 }),
675 valid_from: "2026-04-26T10:00:00Z".into(),
676 valid_until: "2026-04-26T10:05:00Z".into(),
677 reputation_score: Some(150),
678 delegation_chain: None,
679 credential_status: None,
680 }
681 }
682
683 #[test]
684 fn builds_expected_shape() {
685 let vc = build_vouch_credential(&opts()).unwrap();
686 assert_eq!(
687 vc["type"],
688 json!(["VerifiableCredential", "VouchCredential"])
689 );
690 assert_eq!(vc["credentialSubject"]["vouchVersion"], json!("1.0"));
691 assert_eq!(vc["credentialSubject"]["reputationScore"], json!(100));
693 }
694
695 #[test]
696 fn rejects_missing_intent_fields() {
697 let mut o = opts();
698 o.intent = json!({ "action": "read", "target": "t" }); assert!(build_vouch_credential(&o).is_err());
700 }
701
702 #[test]
703 fn sub_grant_names_its_parent_one_way_only() {
704 let digest = "uEiCJcGBDXiN3XLgg5yQXBbX0UV019vMoX1n9_Ttuka1VAQ";
705 let sub = build_sub_grant(&opts(), digest).unwrap();
706 assert_eq!(sub["credentialSubject"]["parentGrantDigest"], json!(digest));
707 assert!(sub["credentialSubject"].get("delegationChain").is_none());
708 let keys: Vec<&str> = sub["credentialSubject"]
710 .as_object()
711 .unwrap()
712 .keys()
713 .map(|k| k.as_str())
714 .collect();
715 assert_eq!(
716 keys,
717 [
718 "id",
719 "vouchVersion",
720 "intent",
721 "reputationScore",
722 "parentGrantDigest"
723 ]
724 );
725 assert!(build_vouch_credential(&opts())
726 .unwrap()
727 .pointer("/credentialSubject/parentGrantDigest")
728 .is_none());
729 assert_eq!(
730 build_sub_grant(&opts(), "").unwrap_err().to_string(),
731 "json error: parent_grant_digest must be a grant digest string"
732 );
733 let mut both = opts();
734 both.delegation_chain = Some(json!([{"issuer": "did:web:a"}]));
735 assert_eq!(
736 build_sub_grant(&both, digest).unwrap_err().to_string(),
737 "json error: a credential carries parentGrantDigest or a delegationChain, never both"
738 );
739 both.delegation_chain = Some(json!([]));
741 assert!(build_sub_grant(&both, digest).is_ok());
742 let mut bad = opts();
744 bad.intent = json!({ "action": "read" });
745 assert!(build_sub_grant(&bad, "")
746 .unwrap_err()
747 .to_string()
748 .contains("intent."));
749 let seed = [5u8; 32];
750 let signed = sign_sub_grant(
751 &opts(),
752 digest,
753 &seed,
754 &BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z"),
755 )
756 .unwrap();
757 let pk = crate::keys::Ed25519KeyPair::from_seed(&seed).public_key();
758 assert!(verify(&signed, &pk, "2026-04-26T10:02:00Z", 30)
759 .unwrap()
760 .is_valid());
761 }
762
763 #[test]
764 fn own_binding_fields_are_checked_on_every_verify_path() {
765 let seed = [5u8; 32];
766 let po = BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
767 let with = |fields: Value| {
768 let mut c = build_vouch_credential(&opts()).unwrap();
769 for (k, v) in fields.as_object().unwrap() {
770 c["credentialSubject"][k] = v.clone();
771 }
772 data_integrity::sign(&c, &seed, &po).unwrap()
773 };
774 let roots = ["did:web:root.example".to_string()];
775 let with_roots = crate::delegation::ChainOptions {
776 trusted_roots: Some(&roots),
777 ..Default::default()
778 };
779 let none = crate::delegation::ChainOptions::default();
780 let every_path = |c: &Value| {
782 let mut out = Vec::new();
783 for r in [
784 verify(c, &pk(), NOW, 30).unwrap(),
785 verify_with_roots(c, &pk(), NOW, 30, &roots).unwrap(),
786 ] {
787 assert!(r.proof_valid && r.time_valid);
788 out.push((r.chain_valid, None));
789 }
790 for o in [&none, &with_roots] {
791 let (r, reason) = verify_explained(c, &pk(), NOW, 30, o).unwrap();
792 assert!(r.proof_valid && r.time_valid);
793 out.push((r.chain_valid, reason.clone()));
794 let (r, reason2) = verify_with_keys(c, &pk(), None, NOW, 30, o).unwrap();
795 assert_eq!(reason2, reason);
796 out.push((r.chain_valid, reason2));
797 out.push((
798 reason.is_none(),
799 crate::delegation::verify_delegation_chain_with(c, NOW, 30, o),
800 ));
801 }
802 out
803 };
804 let malformed = Some("malformed_delegation".to_string());
805 let digest = "uEiCJcGBDXiN3XLgg5yQXBbX0UV019vMoX1n9_Ttuka1VAQ";
806 for fields in [
807 json!({"parentGrantDigest": null}),
808 json!({"parentGrantDigest": 5}),
809 json!({"parentGrantDigest": ["u"]}),
810 json!({"parentGrantDigest": {}}),
811 json!({"delegationChain": null}),
812 json!({"delegationChain": {}}),
813 json!({"parentGrantDigest": digest, "delegationChain": [{"issuer": "did:web:a"}]}),
814 json!({"parentGrantDigest": null, "delegationChain": [{"issuer": "did:web:a"}]}),
815 ] {
816 for (i, (chain_valid, reason)) in
817 every_path(&with(fields.clone())).into_iter().enumerate()
818 {
819 assert!(!chain_valid, "{fields} path {i}");
820 if i >= 2 {
821 assert_eq!(reason, malformed, "{fields} path {i}");
822 }
823 }
824 }
825 for fields in [
828 json!({ "parentGrantDigest": digest }),
829 json!({"parentGrantDigest": digest, "delegationChain": []}),
830 ] {
831 for (i, (chain_valid, reason)) in
832 every_path(&with(fields.clone())).into_iter().enumerate()
833 {
834 assert!(chain_valid, "{fields} path {i}");
835 assert_eq!(reason, None, "{fields} path {i}");
836 }
837 }
838 }
839
840 #[test]
841 fn sign_and_verify_within_window() {
842 let seed = [5u8; 32];
843 let proof_opts =
844 BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
845 let signed = sign_vouch_credential(&opts(), &seed, &proof_opts).unwrap();
846 let pk = crate::keys::Ed25519KeyPair::from_seed(&seed).public_key();
847 let r = verify(&signed, &pk, "2026-04-26T10:02:00Z", 30).unwrap();
848 assert!(r.is_valid());
849 let r2 = verify(&signed, &pk, "2026-04-26T11:00:00Z", 30).unwrap();
851 assert!(r2.proof_valid && !r2.time_valid);
852 }
853
854 fn signed_with(purpose: &str, vm: &str) -> Value {
855 let seed = [5u8; 32];
856 let mut proof_opts = BuildProofOptions::new(vm, "2026-04-26T10:00:00Z");
857 proof_opts.proof_purpose = purpose.into();
858 sign_vouch_credential(&opts(), &seed, &proof_opts).unwrap()
859 }
860
861 fn pk() -> [u8; 32] {
862 crate::keys::Ed25519KeyPair::from_seed(&[5u8; 32]).public_key()
863 }
864
865 const NOW: &str = "2026-04-26T10:02:00Z";
866
867 #[test]
868 fn proof_must_be_an_assertion_by_the_issuer() {
869 let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
870 assert!(verify(&ok, &pk(), NOW, 30).unwrap().is_valid());
871 let auth = signed_with("authentication", "did:web:agent.example.com#key-1");
872 assert!(!verify(&auth, &pk(), NOW, 30).unwrap().proof_valid);
873 let other = signed_with("assertionMethod", "did:web:other.example.com#key-1");
874 assert!(!verify(&other, &pk(), NOW, 30).unwrap().proof_valid);
875 let prefix = signed_with("assertionMethod", "did:web:agent.example.com.evil#key-1");
876 assert!(!verify(&prefix, &pk(), NOW, 30).unwrap().proof_valid);
877 }
878
879 #[test]
880 fn did_key_issuer_must_be_the_signing_key() {
881 let seed = [6u8; 32];
882 let kp = crate::keys::Ed25519KeyPair::from_seed(&seed);
883 let did = kp.did_key();
884 let mut o = opts();
885 o.issuer_did = did.clone();
886 let vm = format!("{did}#{}", did.trim_start_matches("did:key:"));
887 let signed = sign_vouch_credential(
888 &o,
889 &seed,
890 &BuildProofOptions::new(vm, "2026-04-26T10:00:00Z"),
891 )
892 .unwrap();
893 assert!(verify(&signed, &kp.public_key(), NOW, 30)
894 .unwrap()
895 .is_valid());
896 let other = [7u8; 32];
898 let vm = format!("{did}#{}", did.trim_start_matches("did:key:"));
899 let impostor = sign_vouch_credential(
900 &o,
901 &other,
902 &BuildProofOptions::new(vm, "2026-04-26T10:00:00Z"),
903 )
904 .unwrap();
905 let other_pk = crate::keys::Ed25519KeyPair::from_seed(&other).public_key();
906 assert!(!verify(&impostor, &other_pk, NOW, 30).unwrap().proof_valid);
907 }
908
909 #[test]
910 fn vouch_version_and_resource_are_required() {
911 let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
912 for (path, value) in [
913 ("vouchVersion", Value::Null),
914 ("vouchVersion", json!("2.0")),
915 ("vouchVersion", json!(1.0)),
916 ] {
917 let mut c = ok.clone();
918 if value.is_null() {
919 c["credentialSubject"].as_object_mut().unwrap().remove(path);
920 } else {
921 c["credentialSubject"][path] = value;
922 }
923 assert!(verify(&c, &pk(), NOW, 30).is_err(), "{path}");
924 }
925 for bad in [json!(""), json!(42), Value::Null, json!(["https://x"])] {
926 let mut c = ok.clone();
927 c["credentialSubject"]["intent"]["resource"] = bad.clone();
928 assert!(verify(&c, &pk(), NOW, 30).is_err(), "{bad}");
929 }
930 let mut o = opts();
932 o.intent["resource"] = json!("reports/q3.txt");
933 let signed = sign_vouch_credential(
934 &o,
935 &[5u8; 32],
936 &BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z"),
937 )
938 .unwrap();
939 assert!(verify(&signed, &pk(), NOW, 30).unwrap().is_valid());
940 }
941
942 #[test]
943 fn window_rules() {
944 let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
945 for skew in [-1, 121, i64::MAX, i64::MIN] {
947 assert!(verify(&ok, &pk(), NOW, skew).is_err(), "{skew}");
948 assert!(verify_temporal(&ok, NOW, skew).is_err(), "{skew}");
949 }
950 for now in [
952 "2026-04-26T10:02:00",
953 "2026-04-26 10:02:00Z",
954 "2026-04-26t10:02:00z",
955 ] {
956 assert!(verify_temporal(&ok, now, 30).is_err(), "{now}");
957 }
958 assert!(verify_temporal(&ok, "2026-04-26T10:05:00Z", 0).unwrap());
960 assert!(!verify_temporal(&ok, "2026-04-26T10:05:00.000000001Z", 0).unwrap());
961 let inverted =
963 json!({"validFrom": "2026-04-26T10:05:00Z", "validUntil": "2026-04-26T10:00:00Z"});
964 assert!(!verify_temporal(&inverted, "2026-04-26T10:02:00Z", 120).unwrap());
965 let mut c = json!({"validFrom": "2026-04-26T10:00:00Z", "validUntil": "2026-04-26T10:05:00Z",
967 "proof": {"expires": "2026-04-26T10:01:00Z"}});
968 assert!(!verify_temporal(&c, NOW, 30).unwrap());
969 c["proof"]["expires"] = json!("2026-04-26T10:03:00Z");
970 assert!(verify_temporal(&c, NOW, 30).unwrap());
971 c["proof"]["expires"] = json!(5);
972 assert!(verify_temporal(&c, NOW, 30).is_err());
973 }
974
975 #[test]
976 fn proof_context_must_match_the_document() {
977 let mut c = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
978 c["proof"]["@context"] = json!(["https://example.com/other"]);
979 assert!(!verify(&c, &pk(), NOW, 30).unwrap().proof_valid);
980 }
981
982 #[test]
983 fn issuer_object_is_bound_by_its_id() {
984 let mut o = opts();
985 o.issuer_did = "did:web:agent.example.com".into();
986 let mut cred = build_vouch_credential(&o).unwrap();
987 cred["issuer"] = json!({"id": "did:web:agent.example.com", "name": "Agent"});
988 let signed = data_integrity::sign(
989 &cred,
990 &[5u8; 32],
991 &BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z"),
992 )
993 .unwrap();
994 assert!(verify(&signed, &pk(), NOW, 30).unwrap().is_valid());
995 let mut bad = cred.clone();
996 bad["issuer"] = json!(["did:web:agent.example.com"]);
997 let signed = data_integrity::sign(
998 &bad,
999 &[5u8; 32],
1000 &BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z"),
1001 )
1002 .unwrap();
1003 assert!(!verify(&signed, &pk(), NOW, 30).unwrap().proof_valid);
1004 }
1005
1006 #[test]
1007 fn envelope_must_be_a_vouch_credential() {
1008 let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
1009 for (key, value) in [
1010 ("@context", Value::Null),
1011 ("@context", json!("https://www.w3.org/ns/credentials/v2")),
1012 ("@context", json!(["https://example.com/other"])),
1013 ("type", json!(["VerifiableCredential"])),
1014 ("type", json!("VouchCredential")),
1015 ] {
1016 let mut c = ok.clone();
1017 if value.is_null() {
1018 c.as_object_mut().unwrap().remove(key);
1019 } else {
1020 c[key] = value.clone();
1021 }
1022 assert!(verify(&c, &pk(), NOW, 30).is_err(), "{key} = {value}");
1023 }
1024 let mut o = opts();
1026 o.issuer_did = "agent.example.com".into();
1027 let signed = sign_vouch_credential(
1028 &o,
1029 &[5u8; 32],
1030 &BuildProofOptions::new("agent.example.com#key-1", "2026-04-26T10:00:00Z"),
1031 )
1032 .unwrap();
1033 assert!(!verify(&signed, &pk(), NOW, 30).unwrap().proof_valid);
1034 let mut c = ok.clone();
1036 c["proof"]["created"] = json!("yesterday");
1037 assert!(verify(&c, &pk(), NOW, 30).is_err());
1038 }
1039
1040 #[test]
1041 fn every_proof_shape_through_one_verifier() {
1042 use crate::delegation::ChainOptions;
1043 let seed = [5u8; 32];
1044 let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
1045 let unsigned = build_vouch_credential(&opts()).unwrap();
1046 let dual = crate::hybrid::sign_dual(
1047 &unsigned,
1048 &seed,
1049 &ml,
1050 "did:web:agent.example.com#key-1",
1051 "did:web:agent.example.com#key-2",
1052 "2026-04-26T10:00:00Z",
1053 )
1054 .unwrap();
1055 let none = ChainOptions::default();
1056 let pq = ChainOptions {
1057 require_pq: true,
1058 ..Default::default()
1059 };
1060 let mlk = ml.public_key();
1061 let run = |c: &Value, ml: Option<&[u8]>, o: &ChainOptions| {
1062 verify_with_keys(c, &pk(), ml, NOW, 30, o).unwrap().0
1063 };
1064 assert!(run(&dual, Some(&mlk), &none).is_valid());
1065 assert!(run(&dual, Some(&mlk), &pq).is_valid());
1066 assert!(!run(&dual, None, &none).proof_valid);
1068 assert!(!verify(&dual, &pk(), NOW, 30).unwrap().proof_valid);
1069 let single = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
1072 assert!(run(&single, None, &none).is_valid());
1073 assert!(!run(&single, None, &pq).proof_valid);
1074 assert!(!run(&single, Some(&mlk), &none).proof_valid);
1075 assert!(verify_with_keys(&dual, &pk(), Some(&mlk[..1311]), NOW, 30, &none).is_err());
1077 let bad_roots = vec!["127.0.0.1".to_string()];
1079 let with_bad = ChainOptions {
1080 trusted_roots: Some(&bad_roots),
1081 ..Default::default()
1082 };
1083 assert!(verify_with_keys(&single, &pk(), None, NOW, 30, &with_bad).is_err());
1084 let mut lone = dual.clone();
1086 lone["proof"] = dual["proof"][1].clone();
1087 assert!(!run(&lone, Some(&mlk), &none).proof_valid);
1088 let mut extra = dual.clone();
1089 extra["proof"]
1090 .as_array_mut()
1091 .unwrap()
1092 .push(dual["proof"][0].clone());
1093 assert!(!run(&extra, Some(&mlk), &none).proof_valid);
1094 let mut unknown = dual.clone();
1096 let mut odd = dual["proof"][0].clone();
1097 odd["cryptosuite"] = json!("some-unregistered-suite-2030");
1098 unknown["proof"].as_array_mut().unwrap().push(odd);
1099 assert!(!run(&unknown, Some(&mlk), &none).proof_valid);
1100 }
1101
1102 #[test]
1103 fn replay_key_is_issuer_nul_and_proof_digest() {
1104 use sha2::{Digest, Sha256};
1105 let k = replay_key("did:web:a.example", "z3abc").unwrap();
1106 let mut h = Sha256::new();
1107 h.update(b"did:web:a.example\x00");
1108 h.update(Sha256::digest(b"z3abc"));
1109 let want: String = h.finalize().iter().map(|b| format!("{b:02x}")).collect();
1110 assert_eq!(k, want);
1111 assert_eq!(k.len(), 64);
1112 assert!(replay_key("", "z3abc").is_err());
1113 assert!(replay_key("did:web:a.example", "").is_err());
1114 assert_ne!(
1116 replay_key("did:web:a", "bc").unwrap(),
1117 replay_key("did:web:ab", "c").unwrap()
1118 );
1119 }
1120}