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!(
298 p.get("cryptosuite").and_then(|v| v.as_str()),
299 Some(
300 crate::hybrid::EDDSA_CRYPTOSUITE_ID
301 | crate::hybrid::MLDSA44_CRYPTOSUITE_ID
302 | crate::hybrid::MLDSA44_LEGACY_CRYPTOSUITE_ID
303 )
304 );
305 if !known || !proof_bound_to_issuer(proof, issuer) {
306 return Ok(false);
307 }
308 let has_value = p
309 .get("proofValue")
310 .and_then(|v| v.as_str())
311 .is_some_and(|v| !v.is_empty());
312 if !has_value {
313 return Ok(false);
314 }
315 if let Some(created) = p.get("created") {
316 match created.as_str() {
317 Some(c) => {
318 parse_protocol_time_ns(c)?;
319 }
320 None => {
321 return Err(CoreError::Json(
322 "proof.created must be a time string".into(),
323 ))
324 }
325 }
326 }
327 Ok(true)
328}
329
330pub fn replay_key(issuer: &str, proof_value: &str) -> Result<String> {
337 use sha2::{Digest, Sha256};
338 if issuer.is_empty() || proof_value.is_empty() {
339 return Err(CoreError::Json(
340 "issuer and proofValue must be non-empty strings".into(),
341 ));
342 }
343 let inner = Sha256::digest(proof_value.as_bytes());
344 let mut h = Sha256::new();
345 h.update(issuer.as_bytes());
346 h.update([0u8]);
347 h.update(inner);
348 Ok(h.finalize().iter().map(|b| format!("{b:02x}")).collect())
349}
350
351pub(crate) fn proof_member_ok(proof: &Value, issuer: &str, now: i128, skew: i128) -> bool {
355 if !matches!(proof_fields_ok(proof, issuer), Ok(true)) {
356 return false;
357 }
358 match proof.get("expires") {
359 None => true,
360 Some(Value::String(e)) => match parse_protocol_time_ns(e) {
361 Ok(t) => window_state_ns(now, None, Some(t), skew) == WindowState::Ok,
362 Err(_) => false,
363 },
364 Some(_) => false,
365 }
366}
367
368fn key_matches_issuer(issuer: &str, raw_public_key: &[u8]) -> bool {
373 if issuer.starts_with("did:key:") {
374 return match crate::keys::did_key_to_ed25519(issuer) {
375 Ok(k) => k.as_slice() == raw_public_key,
376 Err(_) => false,
377 };
378 }
379 true
380}
381
382pub fn verify(
397 credential: &Value,
398 raw_public_key: &[u8],
399 now_iso: &str,
400 clock_skew_seconds: i64,
401) -> Result<VerifyResult> {
402 let opts = crate::delegation::ChainOptions::default();
403 Ok(verify_explained(
404 credential,
405 raw_public_key,
406 now_iso,
407 clock_skew_seconds,
408 &opts,
409 )?
410 .0)
411}
412
413pub fn verify_with_roots(
417 credential: &Value,
418 raw_public_key: &[u8],
419 now_iso: &str,
420 clock_skew_seconds: i64,
421 trusted_roots: &[String],
422) -> Result<VerifyResult> {
423 let opts = crate::delegation::ChainOptions {
424 trusted_roots: Some(trusted_roots),
425 ..Default::default()
426 };
427 Ok(verify_explained(
428 credential,
429 raw_public_key,
430 now_iso,
431 clock_skew_seconds,
432 &opts,
433 )?
434 .0)
435}
436
437pub fn verify_explained(
444 credential: &Value,
445 raw_public_key: &[u8],
446 now_iso: &str,
447 clock_skew_seconds: i64,
448 opts: &crate::delegation::ChainOptions,
449) -> Result<(VerifyResult, Option<String>)> {
450 verify_with_keys(
451 credential,
452 raw_public_key,
453 None,
454 now_iso,
455 clock_skew_seconds,
456 opts,
457 )
458}
459
460pub fn verify_with_keys(
493 credential: &Value,
494 ed25519_key: &[u8],
495 mldsa44_key: Option<&[u8]>,
496 now_iso: &str,
497 clock_skew_seconds: i64,
498 opts: &crate::delegation::ChainOptions,
499) -> Result<(VerifyResult, Option<String>)> {
500 check_clock_skew(clock_skew_seconds)?;
501 if let Some(ml) = mldsa44_key {
502 if ml.len() != crate::pq::MLDSA44_PUBLIC_LEN {
503 return Err(CoreError::InvalidKeyLength {
504 expected: crate::pq::MLDSA44_PUBLIC_LEN,
505 got: ml.len(),
506 });
507 }
508 }
509 verify_with_selected_keys(
511 credential,
512 Some(ed25519_key),
513 mldsa44_key,
514 mldsa44_key.is_some(),
515 now_iso,
516 clock_skew_seconds,
517 opts,
518 )
519}
520
521fn verify_with_selected_keys(
526 credential: &Value,
527 ed25519_key: Option<&[u8]>,
528 mldsa44_key: Option<&[u8]>,
529 issuer_requires_pq: bool,
530 now_iso: &str,
531 clock_skew_seconds: i64,
532 opts: &crate::delegation::ChainOptions,
533) -> Result<(VerifyResult, Option<String>)> {
534 check_clock_skew(clock_skew_seconds)?;
535 if let Some(roots) = opts.trusted_roots {
536 for r in roots {
537 crate::did_web::normalize_root(r)?;
538 }
539 }
540 if !credential.is_object() {
541 return Err(CoreError::Json("credential must be an object".into()));
542 }
543 check_envelope(credential)?;
544 check_vouch_version(credential)?;
545 check_intent_resource(credential)?;
546
547 let issuer = issuer_did(credential).filter(|i| i.starts_with("did:") && i.len() > 4);
548 let proof_valid = match (issuer, credential.get("proof")) {
549 (Some(issuer), Some(proof)) => {
550 let members: Vec<&Value> = match proof {
551 Value::Array(items) => items.iter().collect(),
552 other => vec![other],
553 };
554 let mut fields_ok = !members.is_empty();
555 for m in &members {
556 fields_ok = fields_ok && proof_fields_ok(m, issuer)?;
557 }
558 match ed25519_key {
559 Some(ed) => {
560 fields_ok
561 && key_matches_issuer(issuer, ed)
562 && proof_shape_verifies(
563 credential,
564 proof,
565 ed,
566 mldsa44_key,
567 issuer_requires_pq,
568 opts,
569 )?
570 }
571 None => false,
573 }
574 }
575 _ => false,
577 };
578 let time_valid = verify_temporal(credential, now_iso, clock_skew_seconds)?;
579 let chain_reason = crate::delegation::verify_delegation_chain_with(
580 credential,
581 now_iso,
582 clock_skew_seconds,
583 opts,
584 );
585 Ok((
586 VerifyResult {
587 proof_valid,
588 time_valid,
589 chain_valid: chain_reason.is_none(),
590 },
591 chain_reason,
592 ))
593}
594
595#[derive(Debug, Clone, PartialEq, Eq)]
597pub struct DidWebvhVerifyOutcome {
598 pub result: VerifyResult,
600 pub chain_reason: Option<String>,
602 pub log: std::result::Result<String, crate::did_webvh::DidWebvhError>,
606 pub grant_logs: std::collections::BTreeMap<
610 String,
611 std::result::Result<String, crate::did_webvh::DidWebvhError>,
612 >,
613}
614
615pub(crate) fn proof_methods(credential: &Value) -> (Option<String>, Option<String>) {
618 let suite = |p: &Value| {
619 p.get("cryptosuite")
620 .and_then(Value::as_str)
621 .map(str::to_string)
622 };
623 let vm = |p: &Value| {
624 p.get("verificationMethod")
625 .and_then(Value::as_str)
626 .map(str::to_string)
627 };
628 let is_mldsa = |s: &str| {
629 s == crate::hybrid::MLDSA44_CRYPTOSUITE_ID
630 || s == crate::hybrid::MLDSA44_LEGACY_CRYPTOSUITE_ID
631 };
632 match credential.get("proof") {
633 Some(p @ Value::Object(_)) => match suite(p).as_deref() {
634 Some(crate::hybrid::EDDSA_CRYPTOSUITE_ID) => (vm(p), None),
635 Some(crate::hybrid::HYBRID_COMPOSITE_CRYPTOSUITE_ID) => {
636 let ed = vm(p);
639 let ml = ed.as_deref().map(|v| match v.strip_suffix("#key-1") {
640 Some(base) => format!("{base}#key-2"),
641 None => match v.split_once('#') {
642 Some((base, _)) => format!("{base}#key-2"),
643 None => format!("{v}#key-2"),
644 },
645 });
646 (ed, ml)
647 }
648 _ => (None, None),
649 },
650 Some(Value::Array(items)) => {
651 let ed = items
652 .iter()
653 .find(|p| suite(p).as_deref() == Some(crate::hybrid::EDDSA_CRYPTOSUITE_ID))
654 .and_then(vm);
655 let ml = items
656 .iter()
657 .find(|p| suite(p).as_deref().is_some_and(is_mldsa))
658 .and_then(vm);
659 (ed, ml)
660 }
661 _ => (None, None),
662 }
663}
664
665pub fn verify_with_did_webvh_log(
693 credential: &Value,
694 logs: &crate::did_webvh::LogSet,
695 now_iso: &str,
696 clock_skew_seconds: i64,
697 opts: &crate::delegation::ChainOptions,
698) -> Result<DidWebvhVerifyOutcome> {
699 check_clock_skew(clock_skew_seconds)?;
700 parse_protocol_time_ns(now_iso)?;
701 let issuer = issuer_did(credential)
702 .filter(|i| crate::did_webvh::is_did_webvh(i))
703 .ok_or_else(|| {
704 CoreError::InvalidDid("the credential's issuer is not a did:webvh DID".into())
705 })?
706 .to_string();
707 let resolved = logs
708 .resolve(&issuer)
709 .ok_or_else(|| CoreError::Json("there is no log for the credential's issuer".into()))?;
710 let keys = match &resolved {
711 Ok(resolution) => {
712 let (ed_vm, ml_vm) = proof_methods(credential);
713 crate::did_document::proof_keys(
714 &resolution.document,
715 &issuer,
716 ed_vm.as_deref(),
717 ml_vm.as_deref(),
718 )
719 }
720 Err(_) => crate::did_document::ProofKeys::default(),
721 };
722 let chain = crate::delegation::ChainOptions {
723 grant_logs: Some(logs),
724 ..*opts
725 };
726 let (result, chain_reason) = verify_with_selected_keys(
727 credential,
728 keys.ed25519.as_deref(),
729 keys.mldsa44.as_deref(),
730 keys.requires_post_quantum,
731 now_iso,
732 clock_skew_seconds,
733 &chain,
734 )?;
735 let mut grant_logs = logs.outcomes();
736 grant_logs.remove(&issuer);
737 Ok(DidWebvhVerifyOutcome {
738 result,
739 chain_reason,
740 log: resolved.map(|r| r.latest_version_id),
741 grant_logs,
742 })
743}
744
745pub fn verify_request_json(request: &Value) -> Result<Value> {
748 verify_request_json_with_clock(request, crate::did_webvh::LogClock::System)
749}
750
751pub fn verify_request_json_with_clock(
779 request: &Value,
780 clock: crate::did_webvh::LogClock,
781) -> Result<Value> {
782 use crate::did_webvh::{base64_decode, grant_log_json, read_chain_request, request_object};
783
784 let mut allowed = vec!["credential", "publicKey", "mldsa44PublicKey"];
785 allowed.extend(crate::did_webvh::CHAIN_REQUEST_MEMBERS);
786 let obj = request_object(request, &allowed)?;
787 let credential = obj
788 .get("credential")
789 .filter(|c| c.is_object())
790 .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?;
791 let public_key = obj
792 .get("publicKey")
793 .and_then(Value::as_str)
794 .ok_or_else(|| CoreError::Json("publicKey must be a base64 Ed25519 key".into()))?;
795 let public_key = base64_decode(public_key, "publicKey")?;
796 let mldsa44_key = match obj.get("mldsa44PublicKey") {
797 None | Some(Value::Null) => None,
798 Some(Value::String(b64)) => Some(base64_decode(b64, "mldsa44PublicKey")?),
799 Some(_) => {
800 return Err(CoreError::Json(
801 "mldsa44PublicKey must be a base64 ML-DSA-44 key".into(),
802 ))
803 }
804 };
805 let request = read_chain_request(obj, clock)?;
806 let chain = crate::delegation::ChainOptions {
807 trusted_roots: request.roots.as_deref(),
808 grant_keys: request.grant_keys.as_ref(),
809 mldsa_keys: request.grant_mldsa_keys.as_ref(),
810 require_pq: request.require_pq,
811 grant_logs: Some(&request.logs),
812 ..Default::default()
813 };
814 let (r, chain_reason) = verify_with_keys(
815 credential,
816 &public_key,
817 mldsa44_key.as_deref(),
818 &request.now,
819 request.skew,
820 &chain,
821 )?;
822 let (grant_versions, grant_errors) = grant_log_json(&request.logs.outcomes());
823 Ok(serde_json::json!({
824 "proofValid": r.proof_valid,
825 "timeValid": r.time_valid,
826 "chainValid": r.chain_valid,
827 "valid": r.is_valid(),
828 "chainReason": chain_reason,
829 "grantVersionIds": grant_versions,
830 "grantLogErrors": grant_errors,
831 }))
832}
833
834fn proof_shape_verifies(
836 credential: &Value,
837 proof: &Value,
838 ed25519_key: &[u8],
839 mldsa44_key: Option<&[u8]>,
840 issuer_requires_pq: bool,
841 opts: &crate::delegation::ChainOptions,
842) -> Result<bool> {
843 let suite = |p: &Value| {
844 p.get("cryptosuite")
845 .and_then(|v| v.as_str())
846 .unwrap_or_default()
847 .to_string()
848 };
849 match proof {
850 Value::Object(_) => match suite(proof).as_str() {
851 crate::hybrid::EDDSA_CRYPTOSUITE_ID => {
852 if opts.require_pq || issuer_requires_pq {
853 return Ok(false);
854 }
855 data_integrity::verify_proof(credential, ed25519_key)
856 }
857 crate::hybrid::HYBRID_COMPOSITE_CRYPTOSUITE_ID => match mldsa44_key {
858 Some(ml) => crate::hybrid::verify_composite(credential, ed25519_key, ml),
859 None => Ok(false),
860 },
861 _ => Ok(false),
863 },
864 Value::Array(items) => {
865 let mut suites: Vec<String> = items
866 .iter()
867 .map(|p| {
868 let s = suite(p);
869 if s == crate::hybrid::MLDSA44_LEGACY_CRYPTOSUITE_ID {
870 crate::hybrid::MLDSA44_CRYPTOSUITE_ID.to_string()
871 } else {
872 s
873 }
874 })
875 .collect();
876 suites.sort();
877 if suites
878 != [
879 crate::hybrid::EDDSA_CRYPTOSUITE_ID,
880 crate::hybrid::MLDSA44_CRYPTOSUITE_ID,
881 ]
882 {
883 return Ok(false); }
885 match mldsa44_key {
886 Some(ml) => crate::hybrid::verify_dual(credential, ed25519_key, ml),
887 None => Ok(false),
888 }
889 }
890 _ => Ok(false),
891 }
892}
893
894pub fn verify_temporal(credential: &Value, now_iso: &str, clock_skew_seconds: i64) -> Result<bool> {
900 let skew = check_clock_skew(clock_skew_seconds)?;
901 let obj = credential
902 .as_object()
903 .ok_or_else(|| CoreError::Json("credential must be an object".into()))?;
904 let vf = obj
905 .get("validFrom")
906 .and_then(|v| v.as_str())
907 .ok_or_else(|| CoreError::Json("credential missing validFrom".into()))?;
908 let vu = obj
909 .get("validUntil")
910 .and_then(|v| v.as_str())
911 .ok_or_else(|| CoreError::Json("credential missing validUntil".into()))?;
912 let now = parse_protocol_time_ns(now_iso)?;
913 let from = parse_protocol_time_ns(vf)?;
914 let until = parse_protocol_time_ns(vu)?;
915 if window_state_ns(now, Some(from), Some(until), skew) != WindowState::Ok {
916 return Ok(false);
917 }
918 let proofs: Vec<&Value> = match obj.get("proof") {
921 Some(Value::Array(items)) => items.iter().collect(),
922 Some(p) => vec![p],
923 None => Vec::new(),
924 };
925 for p in proofs {
926 match p.get("expires") {
927 None => {}
928 Some(Value::String(e)) => {
929 let expires = parse_protocol_time_ns(e)?;
930 if window_state_ns(now, None, Some(expires), skew) != WindowState::Ok {
931 return Ok(false);
932 }
933 }
934 Some(_) => {
935 return Err(CoreError::Json(
936 "proof.expires must be a time string".into(),
937 ))
938 }
939 }
940 }
941 Ok(true)
942}
943
944#[cfg(test)]
945mod tests {
946 use super::*;
947
948 fn opts() -> BuildCredentialOptions {
949 BuildCredentialOptions {
950 issuer_did: "did:web:agent.example.com".into(),
951 credential_id: "urn:uuid:00000000-0000-4000-8000-000000000000".into(),
952 intent: json!({
953 "action": "read_database",
954 "target": "users_table",
955 "resource": "https://api.example.com/v1/users"
956 }),
957 valid_from: "2026-04-26T10:00:00Z".into(),
958 valid_until: "2026-04-26T10:05:00Z".into(),
959 reputation_score: Some(150),
960 delegation_chain: None,
961 credential_status: None,
962 }
963 }
964
965 #[test]
966 fn builds_expected_shape() {
967 let vc = build_vouch_credential(&opts()).unwrap();
968 assert_eq!(
969 vc["type"],
970 json!(["VerifiableCredential", "VouchCredential"])
971 );
972 assert_eq!(vc["credentialSubject"]["vouchVersion"], json!("1.0"));
973 assert_eq!(vc["credentialSubject"]["reputationScore"], json!(100));
975 }
976
977 #[test]
978 fn rejects_missing_intent_fields() {
979 let mut o = opts();
980 o.intent = json!({ "action": "read", "target": "t" }); assert!(build_vouch_credential(&o).is_err());
982 }
983
984 #[test]
985 fn sub_grant_names_its_parent_one_way_only() {
986 let digest = "uEiCJcGBDXiN3XLgg5yQXBbX0UV019vMoX1n9_Ttuka1VAQ";
987 let sub = build_sub_grant(&opts(), digest).unwrap();
988 assert_eq!(sub["credentialSubject"]["parentGrantDigest"], json!(digest));
989 assert!(sub["credentialSubject"].get("delegationChain").is_none());
990 let keys: Vec<&str> = sub["credentialSubject"]
992 .as_object()
993 .unwrap()
994 .keys()
995 .map(|k| k.as_str())
996 .collect();
997 assert_eq!(
998 keys,
999 [
1000 "id",
1001 "vouchVersion",
1002 "intent",
1003 "reputationScore",
1004 "parentGrantDigest"
1005 ]
1006 );
1007 assert!(build_vouch_credential(&opts())
1008 .unwrap()
1009 .pointer("/credentialSubject/parentGrantDigest")
1010 .is_none());
1011 assert_eq!(
1012 build_sub_grant(&opts(), "").unwrap_err().to_string(),
1013 "json error: parent_grant_digest must be a grant digest string"
1014 );
1015 let mut both = opts();
1016 both.delegation_chain = Some(json!([{"issuer": "did:web:a"}]));
1017 assert_eq!(
1018 build_sub_grant(&both, digest).unwrap_err().to_string(),
1019 "json error: a credential carries parentGrantDigest or a delegationChain, never both"
1020 );
1021 both.delegation_chain = Some(json!([]));
1023 assert!(build_sub_grant(&both, digest).is_ok());
1024 let mut bad = opts();
1026 bad.intent = json!({ "action": "read" });
1027 assert!(build_sub_grant(&bad, "")
1028 .unwrap_err()
1029 .to_string()
1030 .contains("intent."));
1031 let seed = [5u8; 32];
1032 let signed = sign_sub_grant(
1033 &opts(),
1034 digest,
1035 &seed,
1036 &BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z"),
1037 )
1038 .unwrap();
1039 let pk = crate::keys::Ed25519KeyPair::from_seed(&seed).public_key();
1040 assert!(verify(&signed, &pk, "2026-04-26T10:02:00Z", 30)
1041 .unwrap()
1042 .is_valid());
1043 }
1044
1045 #[test]
1046 fn own_binding_fields_are_checked_on_every_verify_path() {
1047 let seed = [5u8; 32];
1048 let po = BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
1049 let with = |fields: Value| {
1050 let mut c = build_vouch_credential(&opts()).unwrap();
1051 for (k, v) in fields.as_object().unwrap() {
1052 c["credentialSubject"][k] = v.clone();
1053 }
1054 data_integrity::sign(&c, &seed, &po).unwrap()
1055 };
1056 let roots = ["did:web:root.example".to_string()];
1057 let with_roots = crate::delegation::ChainOptions {
1058 trusted_roots: Some(&roots),
1059 ..Default::default()
1060 };
1061 let none = crate::delegation::ChainOptions::default();
1062 let every_path = |c: &Value| {
1064 let mut out = Vec::new();
1065 for r in [
1066 verify(c, &pk(), NOW, 30).unwrap(),
1067 verify_with_roots(c, &pk(), NOW, 30, &roots).unwrap(),
1068 ] {
1069 assert!(r.proof_valid && r.time_valid);
1070 out.push((r.chain_valid, None));
1071 }
1072 for o in [&none, &with_roots] {
1073 let (r, reason) = verify_explained(c, &pk(), NOW, 30, o).unwrap();
1074 assert!(r.proof_valid && r.time_valid);
1075 out.push((r.chain_valid, reason.clone()));
1076 let (r, reason2) = verify_with_keys(c, &pk(), None, NOW, 30, o).unwrap();
1077 assert_eq!(reason2, reason);
1078 out.push((r.chain_valid, reason2));
1079 out.push((
1080 reason.is_none(),
1081 crate::delegation::verify_delegation_chain_with(c, NOW, 30, o),
1082 ));
1083 }
1084 out
1085 };
1086 let malformed = Some("malformed_delegation".to_string());
1087 let digest = "uEiCJcGBDXiN3XLgg5yQXBbX0UV019vMoX1n9_Ttuka1VAQ";
1088 for fields in [
1089 json!({"parentGrantDigest": null}),
1090 json!({"parentGrantDigest": 5}),
1091 json!({"parentGrantDigest": ["u"]}),
1092 json!({"parentGrantDigest": {}}),
1093 json!({"delegationChain": null}),
1094 json!({"delegationChain": {}}),
1095 json!({"parentGrantDigest": digest, "delegationChain": [{"issuer": "did:web:a"}]}),
1096 json!({"parentGrantDigest": null, "delegationChain": [{"issuer": "did:web:a"}]}),
1097 ] {
1098 for (i, (chain_valid, reason)) in
1099 every_path(&with(fields.clone())).into_iter().enumerate()
1100 {
1101 assert!(!chain_valid, "{fields} path {i}");
1102 if i >= 2 {
1103 assert_eq!(reason, malformed, "{fields} path {i}");
1104 }
1105 }
1106 }
1107 for fields in [
1110 json!({ "parentGrantDigest": digest }),
1111 json!({"parentGrantDigest": digest, "delegationChain": []}),
1112 ] {
1113 for (i, (chain_valid, reason)) in
1114 every_path(&with(fields.clone())).into_iter().enumerate()
1115 {
1116 assert!(chain_valid, "{fields} path {i}");
1117 assert_eq!(reason, None, "{fields} path {i}");
1118 }
1119 }
1120 }
1121
1122 #[test]
1123 fn sign_and_verify_within_window() {
1124 let seed = [5u8; 32];
1125 let proof_opts =
1126 BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
1127 let signed = sign_vouch_credential(&opts(), &seed, &proof_opts).unwrap();
1128 let pk = crate::keys::Ed25519KeyPair::from_seed(&seed).public_key();
1129 let r = verify(&signed, &pk, "2026-04-26T10:02:00Z", 30).unwrap();
1130 assert!(r.is_valid());
1131 let r2 = verify(&signed, &pk, "2026-04-26T11:00:00Z", 30).unwrap();
1133 assert!(r2.proof_valid && !r2.time_valid);
1134 }
1135
1136 fn signed_with(purpose: &str, vm: &str) -> Value {
1137 let seed = [5u8; 32];
1138 let mut proof_opts = BuildProofOptions::new(vm, "2026-04-26T10:00:00Z");
1139 proof_opts.proof_purpose = purpose.into();
1140 sign_vouch_credential(&opts(), &seed, &proof_opts).unwrap()
1141 }
1142
1143 fn pk() -> [u8; 32] {
1144 crate::keys::Ed25519KeyPair::from_seed(&[5u8; 32]).public_key()
1145 }
1146
1147 const NOW: &str = "2026-04-26T10:02:00Z";
1148
1149 #[test]
1150 fn proof_must_be_an_assertion_by_the_issuer() {
1151 let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
1152 assert!(verify(&ok, &pk(), NOW, 30).unwrap().is_valid());
1153 let auth = signed_with("authentication", "did:web:agent.example.com#key-1");
1154 assert!(!verify(&auth, &pk(), NOW, 30).unwrap().proof_valid);
1155 let other = signed_with("assertionMethod", "did:web:other.example.com#key-1");
1156 assert!(!verify(&other, &pk(), NOW, 30).unwrap().proof_valid);
1157 let prefix = signed_with("assertionMethod", "did:web:agent.example.com.evil#key-1");
1158 assert!(!verify(&prefix, &pk(), NOW, 30).unwrap().proof_valid);
1159 }
1160
1161 #[test]
1162 fn did_key_issuer_must_be_the_signing_key() {
1163 let seed = [6u8; 32];
1164 let kp = crate::keys::Ed25519KeyPair::from_seed(&seed);
1165 let did = kp.did_key();
1166 let mut o = opts();
1167 o.issuer_did = did.clone();
1168 let vm = format!("{did}#{}", did.trim_start_matches("did:key:"));
1169 let signed = sign_vouch_credential(
1170 &o,
1171 &seed,
1172 &BuildProofOptions::new(vm, "2026-04-26T10:00:00Z"),
1173 )
1174 .unwrap();
1175 assert!(verify(&signed, &kp.public_key(), NOW, 30)
1176 .unwrap()
1177 .is_valid());
1178 let other = [7u8; 32];
1180 let vm = format!("{did}#{}", did.trim_start_matches("did:key:"));
1181 let impostor = sign_vouch_credential(
1182 &o,
1183 &other,
1184 &BuildProofOptions::new(vm, "2026-04-26T10:00:00Z"),
1185 )
1186 .unwrap();
1187 let other_pk = crate::keys::Ed25519KeyPair::from_seed(&other).public_key();
1188 assert!(!verify(&impostor, &other_pk, NOW, 30).unwrap().proof_valid);
1189 }
1190
1191 #[test]
1192 fn vouch_version_and_resource_are_required() {
1193 let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
1194 for (path, value) in [
1195 ("vouchVersion", Value::Null),
1196 ("vouchVersion", json!("2.0")),
1197 ("vouchVersion", json!(1.0)),
1198 ] {
1199 let mut c = ok.clone();
1200 if value.is_null() {
1201 c["credentialSubject"].as_object_mut().unwrap().remove(path);
1202 } else {
1203 c["credentialSubject"][path] = value;
1204 }
1205 assert!(verify(&c, &pk(), NOW, 30).is_err(), "{path}");
1206 }
1207 for bad in [json!(""), json!(42), Value::Null, json!(["https://x"])] {
1208 let mut c = ok.clone();
1209 c["credentialSubject"]["intent"]["resource"] = bad.clone();
1210 assert!(verify(&c, &pk(), NOW, 30).is_err(), "{bad}");
1211 }
1212 let mut o = opts();
1214 o.intent["resource"] = json!("reports/q3.txt");
1215 let signed = sign_vouch_credential(
1216 &o,
1217 &[5u8; 32],
1218 &BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z"),
1219 )
1220 .unwrap();
1221 assert!(verify(&signed, &pk(), NOW, 30).unwrap().is_valid());
1222 }
1223
1224 #[test]
1225 fn window_rules() {
1226 let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
1227 for skew in [-1, 121, i64::MAX, i64::MIN] {
1229 assert!(verify(&ok, &pk(), NOW, skew).is_err(), "{skew}");
1230 assert!(verify_temporal(&ok, NOW, skew).is_err(), "{skew}");
1231 }
1232 for now in [
1234 "2026-04-26T10:02:00",
1235 "2026-04-26 10:02:00Z",
1236 "2026-04-26t10:02:00z",
1237 ] {
1238 assert!(verify_temporal(&ok, now, 30).is_err(), "{now}");
1239 }
1240 assert!(verify_temporal(&ok, "2026-04-26T10:05:00Z", 0).unwrap());
1242 assert!(!verify_temporal(&ok, "2026-04-26T10:05:00.000000001Z", 0).unwrap());
1243 let inverted =
1245 json!({"validFrom": "2026-04-26T10:05:00Z", "validUntil": "2026-04-26T10:00:00Z"});
1246 assert!(!verify_temporal(&inverted, "2026-04-26T10:02:00Z", 120).unwrap());
1247 let mut c = json!({"validFrom": "2026-04-26T10:00:00Z", "validUntil": "2026-04-26T10:05:00Z",
1249 "proof": {"expires": "2026-04-26T10:01:00Z"}});
1250 assert!(!verify_temporal(&c, NOW, 30).unwrap());
1251 c["proof"]["expires"] = json!("2026-04-26T10:03:00Z");
1252 assert!(verify_temporal(&c, NOW, 30).unwrap());
1253 c["proof"]["expires"] = json!(5);
1254 assert!(verify_temporal(&c, NOW, 30).is_err());
1255 }
1256
1257 #[test]
1258 fn proof_context_must_match_the_document() {
1259 let mut c = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
1260 c["proof"]["@context"] = json!(["https://example.com/other"]);
1261 assert!(!verify(&c, &pk(), NOW, 30).unwrap().proof_valid);
1262 }
1263
1264 #[test]
1265 fn issuer_object_is_bound_by_its_id() {
1266 let mut o = opts();
1267 o.issuer_did = "did:web:agent.example.com".into();
1268 let mut cred = build_vouch_credential(&o).unwrap();
1269 cred["issuer"] = json!({"id": "did:web:agent.example.com", "name": "Agent"});
1270 let signed = data_integrity::sign(
1271 &cred,
1272 &[5u8; 32],
1273 &BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z"),
1274 )
1275 .unwrap();
1276 assert!(verify(&signed, &pk(), NOW, 30).unwrap().is_valid());
1277 let mut bad = cred.clone();
1278 bad["issuer"] = json!(["did:web:agent.example.com"]);
1279 let signed = data_integrity::sign(
1280 &bad,
1281 &[5u8; 32],
1282 &BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z"),
1283 )
1284 .unwrap();
1285 assert!(!verify(&signed, &pk(), NOW, 30).unwrap().proof_valid);
1286 }
1287
1288 #[test]
1289 fn envelope_must_be_a_vouch_credential() {
1290 let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
1291 for (key, value) in [
1292 ("@context", Value::Null),
1293 ("@context", json!("https://www.w3.org/ns/credentials/v2")),
1294 ("@context", json!(["https://example.com/other"])),
1295 ("type", json!(["VerifiableCredential"])),
1296 ("type", json!("VouchCredential")),
1297 ] {
1298 let mut c = ok.clone();
1299 if value.is_null() {
1300 c.as_object_mut().unwrap().remove(key);
1301 } else {
1302 c[key] = value.clone();
1303 }
1304 assert!(verify(&c, &pk(), NOW, 30).is_err(), "{key} = {value}");
1305 }
1306 let mut o = opts();
1308 o.issuer_did = "agent.example.com".into();
1309 let signed = sign_vouch_credential(
1310 &o,
1311 &[5u8; 32],
1312 &BuildProofOptions::new("agent.example.com#key-1", "2026-04-26T10:00:00Z"),
1313 )
1314 .unwrap();
1315 assert!(!verify(&signed, &pk(), NOW, 30).unwrap().proof_valid);
1316 let mut c = ok.clone();
1318 c["proof"]["created"] = json!("yesterday");
1319 assert!(verify(&c, &pk(), NOW, 30).is_err());
1320 }
1321
1322 #[test]
1323 fn every_proof_shape_through_one_verifier() {
1324 use crate::delegation::ChainOptions;
1325 let seed = [5u8; 32];
1326 let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
1327 let unsigned = build_vouch_credential(&opts()).unwrap();
1328 let dual = crate::hybrid::sign_dual(
1329 &unsigned,
1330 &seed,
1331 &ml,
1332 "did:web:agent.example.com#key-1",
1333 "did:web:agent.example.com#key-2",
1334 "2026-04-26T10:00:00Z",
1335 )
1336 .unwrap();
1337 let none = ChainOptions::default();
1338 let pq = ChainOptions {
1339 require_pq: true,
1340 ..Default::default()
1341 };
1342 let mlk = ml.public_key();
1343 let run = |c: &Value, ml: Option<&[u8]>, o: &ChainOptions| {
1344 verify_with_keys(c, &pk(), ml, NOW, 30, o).unwrap().0
1345 };
1346 assert!(run(&dual, Some(&mlk), &none).is_valid());
1347 assert!(run(&dual, Some(&mlk), &pq).is_valid());
1348 assert!(!run(&dual, None, &none).proof_valid);
1350 assert!(!verify(&dual, &pk(), NOW, 30).unwrap().proof_valid);
1351 let single = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
1354 assert!(run(&single, None, &none).is_valid());
1355 assert!(!run(&single, None, &pq).proof_valid);
1356 assert!(!run(&single, Some(&mlk), &none).proof_valid);
1357 assert!(verify_with_keys(&dual, &pk(), Some(&mlk[..1311]), NOW, 30, &none).is_err());
1359 let bad_roots = vec!["127.0.0.1".to_string()];
1361 let with_bad = ChainOptions {
1362 trusted_roots: Some(&bad_roots),
1363 ..Default::default()
1364 };
1365 assert!(verify_with_keys(&single, &pk(), None, NOW, 30, &with_bad).is_err());
1366 let mut lone = dual.clone();
1368 lone["proof"] = dual["proof"][1].clone();
1369 assert!(!run(&lone, Some(&mlk), &none).proof_valid);
1370 let mut extra = dual.clone();
1371 extra["proof"]
1372 .as_array_mut()
1373 .unwrap()
1374 .push(dual["proof"][0].clone());
1375 assert!(!run(&extra, Some(&mlk), &none).proof_valid);
1376 let mut unknown = dual.clone();
1378 let mut odd = dual["proof"][0].clone();
1379 odd["cryptosuite"] = json!("some-unregistered-suite-2030");
1380 unknown["proof"].as_array_mut().unwrap().push(odd);
1381 assert!(!run(&unknown, Some(&mlk), &none).proof_valid);
1382 }
1383
1384 #[test]
1385 fn replay_key_is_issuer_nul_and_proof_digest() {
1386 use sha2::{Digest, Sha256};
1387 let k = replay_key("did:web:a.example", "z3abc").unwrap();
1388 let mut h = Sha256::new();
1389 h.update(b"did:web:a.example\x00");
1390 h.update(Sha256::digest(b"z3abc"));
1391 let want: String = h.finalize().iter().map(|b| format!("{b:02x}")).collect();
1392 assert_eq!(k, want);
1393 assert_eq!(k.len(), 64);
1394 assert!(replay_key("", "z3abc").is_err());
1395 assert!(replay_key("did:web:a.example", "").is_err());
1396 assert_ne!(
1398 replay_key("did:web:a", "bc").unwrap(),
1399 replay_key("did:web:ab", "c").unwrap()
1400 );
1401 }
1402}