1#[allow(unused_imports)]
9use crate::prelude::*;
10
11use serde_json::{json, Map, Value};
12
13use crate::data_integrity::{self, BuildProofOptions};
14use crate::error::{CoreError, Result};
15use crate::time::{check_clock_skew, parse_protocol_time_ns, window_state_ns, WindowState};
16
17pub const VC_CONTEXT_V2: &str = "https://www.w3.org/ns/credentials/v2";
18pub const VOUCH_CONTEXT_V1: &str = "https://vouch-protocol.com/contexts/v1";
19pub const VC_TYPE: &str = "VerifiableCredential";
20pub const VOUCH_CREDENTIAL_TYPE: &str = "VouchCredential";
21pub const PROTOCOL_VERSION: &str = "1.0";
22
23#[derive(Debug, Clone)]
25pub struct BuildCredentialOptions {
26 pub issuer_did: String,
27 pub credential_id: String,
28 pub intent: Value,
29 pub valid_from: String,
30 pub valid_until: String,
31 pub reputation_score: Option<i64>,
32 pub delegation_chain: Option<Value>,
33 pub credential_status: Option<Value>,
34}
35
36pub fn validate_intent(intent: &Value) -> Result<()> {
39 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); intent);
40 let obj = intent
41 .as_object()
42 .ok_or_else(|| CoreError::Json("intent must be an object".into()))?;
43 for req in ["action", "target", "resource"] {
44 match obj.get(req).and_then(|v| v.as_str()) {
45 Some(s) if !s.is_empty() => {}
46 _ => {
47 return Err(CoreError::Json(format!(
48 "intent.{req} is REQUIRED and must be a non-empty string"
49 )))
50 }
51 }
52 }
53 Ok(())
54}
55
56pub fn build_vouch_credential(opts: &BuildCredentialOptions) -> Result<Value> {
58 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); opts);
59 build_credential(opts, None)
60}
61
62pub fn build_sub_grant(opts: &BuildCredentialOptions, parent_grant_digest: &str) -> Result<Value> {
73 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); opts);
74 build_credential(opts, Some(parent_grant_digest))
75}
76
77pub fn sign_sub_grant(
80 opts: &BuildCredentialOptions,
81 parent_grant_digest: &str,
82 raw_private_seed: &[u8],
83 proof_opts: &BuildProofOptions,
84) -> Result<Value> {
85 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); opts);
86 let cred = build_sub_grant(opts, parent_grant_digest)?;
87 data_integrity::sign(&cred, raw_private_seed, proof_opts)
88}
89
90fn build_credential(opts: &BuildCredentialOptions, parent_digest: Option<&str>) -> Result<Value> {
91 validate_intent(&opts.intent)?;
92 let has_chain = opts
93 .delegation_chain
94 .as_ref()
95 .and_then(|c| c.as_array())
96 .is_some_and(|a| !a.is_empty());
97 if let Some(digest) = parent_digest {
98 if digest.is_empty() {
99 return Err(CoreError::Json(
100 "parent_grant_digest must be a grant digest string".into(),
101 ));
102 }
103 if has_chain {
104 return Err(CoreError::Json(
105 "a credential carries parentGrantDigest or a delegationChain, never both".into(),
106 ));
107 }
108 }
109
110 let mut subject = Map::new();
111 subject.insert("id".into(), json!(opts.issuer_did));
112 subject.insert("vouchVersion".into(), json!(PROTOCOL_VERSION));
113 subject.insert("intent".into(), opts.intent.clone());
114 if let Some(r) = opts.reputation_score {
115 subject.insert("reputationScore".into(), json!(r.clamp(0, 100)));
116 }
117 if let Some(digest) = parent_digest {
118 subject.insert(
119 crate::grant_chain::PARENT_GRANT_DIGEST.into(),
120 json!(digest),
121 );
122 }
123 if let Some(chain) = &opts.delegation_chain {
124 if chain.as_array().map(|a| !a.is_empty()).unwrap_or(false) {
125 subject.insert("delegationChain".into(), chain.clone());
126 }
127 }
128
129 let mut vc = Map::new();
130 vc.insert("@context".into(), json!([VC_CONTEXT_V2, VOUCH_CONTEXT_V1]));
131 vc.insert("id".into(), json!(opts.credential_id));
132 vc.insert("type".into(), json!([VC_TYPE, VOUCH_CREDENTIAL_TYPE]));
133 vc.insert("issuer".into(), json!(opts.issuer_did));
134 vc.insert("validFrom".into(), json!(opts.valid_from));
135 vc.insert("validUntil".into(), json!(opts.valid_until));
136 vc.insert("credentialSubject".into(), Value::Object(subject));
137 if let Some(status) = &opts.credential_status {
138 vc.insert("credentialStatus".into(), status.clone());
139 }
140 Ok(Value::Object(vc))
141}
142
143pub fn sign_vouch_credential(
145 opts: &BuildCredentialOptions,
146 raw_private_seed: &[u8],
147 proof_opts: &BuildProofOptions,
148) -> Result<Value> {
149 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); opts);
150 let cred = build_vouch_credential(opts)?;
151 data_integrity::sign(&cred, raw_private_seed, proof_opts)
152}
153
154pub const SUPPORTED_VOUCH_VERSIONS: &[&str] = &[PROTOCOL_VERSION];
157
158#[derive(Debug, Clone, Copy, PartialEq, Eq)]
162pub struct VerifyResult {
163 pub proof_valid: bool,
168 pub time_valid: bool,
171 pub chain_valid: bool,
175}
176
177impl VerifyResult {
178 pub fn is_valid(&self) -> bool {
179 self.proof_valid && self.time_valid && self.chain_valid
180 }
181}
182
183pub fn issuer_did(credential: &Value) -> Option<&str> {
186 match credential.get("issuer") {
187 Some(Value::String(s)) if !s.is_empty() => Some(s.as_str()),
188 Some(Value::Object(o)) => o
189 .get("id")
190 .and_then(|v| v.as_str())
191 .filter(|s| !s.is_empty()),
192 _ => None,
193 }
194}
195
196pub fn proof_bound_to_issuer(proof: &Value, issuer: &str) -> bool {
202 crate::nesting::deep_guard!(false; proof);
203 let Some(p) = proof.as_object() else {
204 return false;
205 };
206 if p.get("proofPurpose").and_then(|v| v.as_str()) != Some("assertionMethod") {
207 return false;
208 }
209 match p.get("verificationMethod").and_then(|v| v.as_str()) {
210 Some(vm) if !vm.is_empty() => crate::verification_method::proof_method_names(p, issuer),
211 _ => false,
212 }
213}
214
215pub fn check_vouch_version(credential: &Value) -> Result<()> {
218 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
219 let version = credential
220 .get("credentialSubject")
221 .and_then(|s| s.get("vouchVersion"));
222 match version.and_then(|v| v.as_str()) {
223 Some(v) if SUPPORTED_VOUCH_VERSIONS.contains(&v) => Ok(()),
224 Some(v) => Err(CoreError::Json(format!(
225 "unsupported vouchVersion {:?}",
226 v.chars().take(32).collect::<String>()
227 ))),
228 None => Err(CoreError::Json(
229 "credentialSubject.vouchVersion is required".into(),
230 )),
231 }
232}
233
234pub fn check_intent_resource(credential: &Value) -> Result<()> {
239 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
240 let resource = credential
241 .get("credentialSubject")
242 .and_then(|s| s.get("intent"))
243 .and_then(|i| i.get("resource"));
244 match resource.and_then(|r| r.as_str()) {
245 Some(r) if !r.is_empty() => Ok(()),
246 _ => Err(CoreError::Json(
247 "intent.resource is REQUIRED and must be a non-empty string".into(),
248 )),
249 }
250}
251
252pub fn check_envelope(credential: &Value) -> Result<()> {
257 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
258 let ctx_ok = credential
259 .get("@context")
260 .and_then(|c| c.as_array())
261 .and_then(|c| c.first())
262 .and_then(|c| c.as_str())
263 == Some(VC_CONTEXT_V2);
264 if !ctx_ok {
265 return Err(CoreError::Json(
266 "the credential's @context must start with the VC 2.0 context".into(),
267 ));
268 }
269 let types_ok = credential
270 .get("type")
271 .and_then(|t| t.as_array())
272 .map(|t| {
273 [VC_TYPE, VOUCH_CREDENTIAL_TYPE]
274 .iter()
275 .all(|want| t.iter().any(|x| x.as_str() == Some(want)))
276 })
277 .unwrap_or(false);
278 if !types_ok {
279 return Err(CoreError::Json(
280 "the credential's type must include VerifiableCredential and VouchCredential".into(),
281 ));
282 }
283 let subject_ok = credential
284 .get("credentialSubject")
285 .map(|s| s.is_object() && s.get("intent").map(|i| i.is_object()).unwrap_or(false))
286 .unwrap_or(false);
287 if !subject_ok {
288 return Err(CoreError::Json(
289 "credentialSubject and its intent must be objects".into(),
290 ));
291 }
292 Ok(())
293}
294
295fn proof_fields_ok(proof: &Value, issuer: &str) -> Result<bool> {
301 let Some(p) = proof.as_object() else {
302 return Ok(false);
303 };
304 if p.get("type").and_then(|v| v.as_str()) != Some(data_integrity::PROOF_TYPE) {
305 return Ok(false);
306 }
307 let known = crate::hybrid::Suite::of_proof(proof).is_some();
310 if !known || !proof_bound_to_issuer(proof, issuer) {
311 return Ok(false);
312 }
313 let has_value = p
314 .get("proofValue")
315 .and_then(|v| v.as_str())
316 .is_some_and(|v| !v.is_empty());
317 if !has_value {
318 return Ok(false);
319 }
320 if let Some(created) = p.get("created") {
321 match created.as_str() {
322 Some(c) => {
323 parse_protocol_time_ns(c)?;
324 }
325 None => {
326 return Err(CoreError::Json(
327 "proof.created must be a time string".into(),
328 ))
329 }
330 }
331 }
332 Ok(true)
333}
334
335pub fn replay_key(issuer: &str, proof_value: &str) -> Result<String> {
342 use sha2::{Digest, Sha256};
343 if issuer.is_empty() || proof_value.is_empty() {
344 return Err(CoreError::Json(
345 "issuer and proofValue must be non-empty strings".into(),
346 ));
347 }
348 let inner = Sha256::digest(proof_value.as_bytes());
349 let mut h = Sha256::new();
350 h.update(issuer.as_bytes());
351 h.update([0u8]);
352 h.update(inner);
353 Ok(h.finalize().iter().map(|b| format!("{b:02x}")).collect())
354}
355
356pub(crate) fn proof_member_ok(proof: &Value, issuer: &str, now: i128, skew: i128) -> bool {
360 if !matches!(proof_fields_ok(proof, issuer), Ok(true)) {
361 return false;
362 }
363 match proof.get("expires") {
364 None => true,
365 Some(Value::String(e)) => match parse_protocol_time_ns(e) {
366 Ok(t) => window_state_ns(now, None, Some(t), skew) == WindowState::Ok,
367 Err(_) => false,
368 },
369 Some(_) => false,
370 }
371}
372
373fn key_matches_issuer(issuer: &str, raw_public_key: &[u8]) -> bool {
378 if issuer.starts_with("did:key:") {
379 return match crate::keys::did_key_to_ed25519(issuer) {
380 Ok(k) => k.as_slice() == raw_public_key,
381 Err(_) => false,
382 };
383 }
384 true
385}
386
387pub fn verify(
402 credential: &Value,
403 raw_public_key: &[u8],
404 now_iso: &str,
405 clock_skew_seconds: i64,
406) -> Result<VerifyResult> {
407 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
408 let opts = crate::delegation::ChainOptions::default();
409 Ok(verify_explained(
410 credential,
411 raw_public_key,
412 now_iso,
413 clock_skew_seconds,
414 &opts,
415 )?
416 .0)
417}
418
419pub fn verify_with_roots(
423 credential: &Value,
424 raw_public_key: &[u8],
425 now_iso: &str,
426 clock_skew_seconds: i64,
427 trusted_roots: &[String],
428) -> Result<VerifyResult> {
429 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
430 let opts = crate::delegation::ChainOptions {
431 trusted_roots: Some(trusted_roots),
432 ..Default::default()
433 };
434 Ok(verify_explained(
435 credential,
436 raw_public_key,
437 now_iso,
438 clock_skew_seconds,
439 &opts,
440 )?
441 .0)
442}
443
444pub fn verify_explained(
451 credential: &Value,
452 raw_public_key: &[u8],
453 now_iso: &str,
454 clock_skew_seconds: i64,
455 opts: &crate::delegation::ChainOptions,
456) -> Result<(VerifyResult, Option<String>)> {
457 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, opts);
458 verify_with_keys(
459 credential,
460 raw_public_key,
461 None,
462 now_iso,
463 clock_skew_seconds,
464 opts,
465 )
466}
467
468pub fn verify_with_keys(
505 credential: &Value,
506 ed25519_key: &[u8],
507 mldsa44_key: Option<&[u8]>,
508 now_iso: &str,
509 clock_skew_seconds: i64,
510 opts: &crate::delegation::ChainOptions,
511) -> Result<(VerifyResult, Option<String>)> {
512 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, opts);
513 check_clock_skew(clock_skew_seconds)?;
514 if let Some(ml) = mldsa44_key {
515 if ml.len() != crate::pq::MLDSA44_PUBLIC_LEN {
516 return Err(CoreError::InvalidKeyLength {
517 expected: crate::pq::MLDSA44_PUBLIC_LEN,
518 got: ml.len(),
519 });
520 }
521 }
522 if let Some(slh) = opts.slhdsa128_key {
523 if slh.len() != crate::slh::SLHDSA128_PUBLIC_LEN {
524 return Err(CoreError::InvalidKeyLength {
525 expected: crate::slh::SLHDSA128_PUBLIC_LEN,
526 got: slh.len(),
527 });
528 }
529 }
530 verify_with_selected_keys(
532 credential,
533 Some(ed25519_key),
534 mldsa44_key,
535 opts.slhdsa128_key,
536 crate::hybrid::Required {
537 post_quantum: false,
538 mldsa44: mldsa44_key.is_some(),
539 slhdsa128: opts.slhdsa128_key.is_some(),
540 },
541 now_iso,
542 clock_skew_seconds,
543 opts,
544 )
545}
546
547#[allow(clippy::too_many_arguments)]
552fn verify_with_selected_keys(
553 credential: &Value,
554 ed25519_key: Option<&[u8]>,
555 mldsa44_key: Option<&[u8]>,
556 slhdsa128_key: Option<&[u8]>,
557 issuer_requires: crate::hybrid::Required,
558 now_iso: &str,
559 clock_skew_seconds: i64,
560 opts: &crate::delegation::ChainOptions,
561) -> Result<(VerifyResult, Option<String>)> {
562 check_clock_skew(clock_skew_seconds)?;
563 if let Some(roots) = opts.trusted_roots {
564 for r in roots {
565 crate::did_web::normalize_root(r)?;
566 }
567 }
568 if !credential.is_object() {
569 return Err(CoreError::Json("credential must be an object".into()));
570 }
571 check_envelope(credential)?;
572 check_vouch_version(credential)?;
573 check_intent_resource(credential)?;
574
575 let issuer = issuer_did(credential).filter(|i| i.starts_with("did:") && i.len() > 4);
576 let proof_valid = match (issuer, credential.get("proof")) {
577 (Some(issuer), Some(proof)) => {
578 let members: Vec<&Value> = match proof {
579 Value::Array(items) => items.iter().collect(),
580 other => vec![other],
581 };
582 let mut fields_ok = !members.is_empty();
583 for m in &members {
584 fields_ok = fields_ok && proof_fields_ok(m, issuer)?;
585 }
586 match ed25519_key {
587 Some(ed) => {
588 fields_ok
589 && key_matches_issuer(issuer, ed)
590 && proof_shape_verifies(
591 credential,
592 proof,
593 ed,
594 mldsa44_key,
595 slhdsa128_key,
596 issuer_requires,
597 opts,
598 )?
599 }
600 None => false,
602 }
603 }
604 _ => false,
606 };
607 let time_valid = verify_temporal(credential, now_iso, clock_skew_seconds)?;
608 let chain_reason = crate::delegation::verify_delegation_chain_with(
609 credential,
610 now_iso,
611 clock_skew_seconds,
612 opts,
613 );
614 Ok((
615 VerifyResult {
616 proof_valid,
617 time_valid,
618 chain_valid: chain_reason.is_none(),
619 },
620 chain_reason,
621 ))
622}
623
624#[derive(Debug, Clone, PartialEq, Eq)]
626pub struct DidWebvhVerifyOutcome {
627 pub result: VerifyResult,
629 pub chain_reason: Option<String>,
631 pub log: core::result::Result<String, crate::did_webvh::DidWebvhError>,
635 pub grant_logs: alloc::collections::BTreeMap<
639 String,
640 core::result::Result<String, crate::did_webvh::DidWebvhError>,
641 >,
642}
643
644#[derive(Debug, Clone, Default, PartialEq, Eq)]
647pub(crate) struct ProofMethods {
648 pub ed25519: Option<String>,
649 pub mldsa44: Option<String>,
650 pub slhdsa128: Option<String>,
651}
652
653pub(crate) fn proof_methods(credential: &Value) -> ProofMethods {
654 use crate::hybrid::Suite;
655 let vm = |p: &Value| {
656 p.get("verificationMethod")
657 .and_then(Value::as_str)
658 .map(str::to_string)
659 };
660 match credential.get("proof") {
661 Some(p @ Value::Object(_)) if Suite::of_proof(p) == Some(Suite::Eddsa) => ProofMethods {
662 ed25519: vm(p),
663 ..Default::default()
664 },
665 Some(Value::Array(items)) => {
666 let first = |suite: Suite| {
667 items
668 .iter()
669 .find(|p| Suite::of_proof(p) == Some(suite))
670 .and_then(vm)
671 };
672 ProofMethods {
673 ed25519: first(Suite::Eddsa),
674 mldsa44: first(Suite::Mldsa44),
675 slhdsa128: first(Suite::Slhdsa128),
676 }
677 }
678 _ => ProofMethods::default(),
679 }
680}
681
682pub fn verify_with_did_webvh_log(
711 credential: &Value,
712 logs: &crate::did_webvh::LogSet,
713 now_iso: &str,
714 clock_skew_seconds: i64,
715 opts: &crate::delegation::ChainOptions,
716) -> Result<DidWebvhVerifyOutcome> {
717 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential, opts);
718 check_clock_skew(clock_skew_seconds)?;
719 parse_protocol_time_ns(now_iso)?;
720 let issuer = issuer_did(credential)
721 .filter(|i| crate::did_webvh::is_did_webvh(i))
722 .ok_or_else(|| {
723 CoreError::InvalidDid("the credential's issuer is not a did:webvh DID".into())
724 })?
725 .to_string();
726 let resolved = logs
727 .resolve(&issuer)
728 .ok_or_else(|| CoreError::Json("there is no log for the credential's issuer".into()))?;
729 let keys = match &resolved {
730 Ok(resolution) => {
731 let methods = proof_methods(credential);
732 crate::did_document::proof_keys_for(
733 &resolution.document,
734 &issuer,
735 crate::did_document::ProofMethodRefs {
736 ed25519: methods.ed25519.as_deref(),
737 mldsa44: methods.mldsa44.as_deref(),
738 slhdsa128: methods.slhdsa128.as_deref(),
739 },
740 )
741 }
742 Err(_) => crate::did_document::ProofKeys::default(),
743 };
744 let chain = crate::delegation::ChainOptions {
745 grant_logs: Some(logs),
746 ..*opts
747 };
748 let (result, chain_reason) = verify_with_selected_keys(
749 credential,
750 keys.ed25519.as_deref(),
751 keys.mldsa44.as_deref(),
752 keys.slhdsa128.as_deref(),
753 keys.required(),
754 now_iso,
755 clock_skew_seconds,
756 &chain,
757 )?;
758 let mut grant_logs = logs.outcomes();
759 grant_logs.remove(&issuer);
760 Ok(DidWebvhVerifyOutcome {
761 result,
762 chain_reason,
763 log: resolved.map(|r| r.latest_version_id),
764 grant_logs,
765 })
766}
767
768pub fn verify_request_json(request: &Value) -> Result<Value> {
771 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
772 verify_request_json_with_clock(request, crate::did_webvh::LogClock::System)
773}
774
775pub fn verify_request_json_with_clock(
806 request: &Value,
807 clock: crate::did_webvh::LogClock,
808) -> Result<Value> {
809 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
810 use crate::did_webvh::{base64_decode, grant_log_json, read_chain_request, request_object};
811
812 let mut allowed = vec![
813 "credential",
814 "publicKey",
815 "mldsa44PublicKey",
816 "slhdsa128PublicKey",
817 ];
818 allowed.extend(crate::did_webvh::CHAIN_REQUEST_MEMBERS);
819 let obj = request_object(request, &allowed)?;
820 let credential = obj
821 .get("credential")
822 .filter(|c| c.is_object())
823 .ok_or_else(|| CoreError::Json("credential must be a JSON object".into()))?;
824 let public_key = obj
825 .get("publicKey")
826 .and_then(Value::as_str)
827 .ok_or_else(|| CoreError::Json("publicKey must be a base64 Ed25519 key".into()))?;
828 let public_key = base64_decode(public_key, "publicKey")?;
829 let mldsa44_key = match obj.get("mldsa44PublicKey") {
830 None | Some(Value::Null) => None,
831 Some(Value::String(b64)) => Some(base64_decode(b64, "mldsa44PublicKey")?),
832 Some(_) => {
833 return Err(CoreError::Json(
834 "mldsa44PublicKey must be a base64 ML-DSA-44 key".into(),
835 ))
836 }
837 };
838 let slhdsa128_key = match obj.get("slhdsa128PublicKey") {
839 None | Some(Value::Null) => None,
840 Some(Value::String(b64)) => Some(base64_decode(b64, "slhdsa128PublicKey")?),
841 Some(_) => {
842 return Err(CoreError::Json(
843 "slhdsa128PublicKey must be a base64 SLH-DSA-SHA2-128s key".into(),
844 ))
845 }
846 };
847 let request = read_chain_request(obj, clock)?;
848 let chain = crate::delegation::ChainOptions {
849 trusted_roots: request.roots.as_deref(),
850 grant_keys: request.grant_keys.as_ref(),
851 mldsa_keys: request.grant_mldsa_keys.as_ref(),
852 slhdsa_keys: request.grant_slhdsa_keys.as_ref(),
853 slhdsa128_key: slhdsa128_key.as_deref(),
854 require_pq: request.require_pq,
855 grant_logs: Some(&request.logs),
856 ..Default::default()
857 };
858 let (r, chain_reason) = verify_with_keys(
859 credential,
860 &public_key,
861 mldsa44_key.as_deref(),
862 &request.now,
863 request.skew,
864 &chain,
865 )?;
866 let (grant_versions, grant_errors) = grant_log_json(&request.logs.outcomes());
867 Ok(serde_json::json!({
868 "proofValid": r.proof_valid,
869 "timeValid": r.time_valid,
870 "chainValid": r.chain_valid,
871 "valid": r.is_valid(),
872 "chainReason": chain_reason,
873 "grantVersionIds": grant_versions,
874 "grantLogErrors": grant_errors,
875 }))
876}
877
878fn proof_shape_verifies(
880 credential: &Value,
881 proof: &Value,
882 ed25519_key: &[u8],
883 mldsa44_key: Option<&[u8]>,
884 slhdsa128_key: Option<&[u8]>,
885 issuer_requires: crate::hybrid::Required,
886 opts: &crate::delegation::ChainOptions,
887) -> Result<bool> {
888 use crate::hybrid::Suite;
889 let required = crate::hybrid::Required {
890 post_quantum: issuer_requires.post_quantum || opts.require_pq,
891 ..issuer_requires
892 };
893 match proof {
894 Value::Object(_) => {
898 if Suite::of_proof(proof) != Some(Suite::Eddsa) || required.any() {
899 return Ok(false);
900 }
901 data_integrity::verify_proof(credential, ed25519_key)
902 }
903 Value::Array(items) => {
904 let Some(members) = crate::hybrid::set_members(items) else {
905 return Ok(false); };
907 if !required.met_by(&members.suites()) {
908 return Ok(false);
909 }
910 crate::hybrid::verify_set(credential, ed25519_key, mldsa44_key, slhdsa128_key)
911 }
912 _ => Ok(false),
913 }
914}
915
916pub fn verify_temporal(credential: &Value, now_iso: &str, clock_skew_seconds: i64) -> Result<bool> {
922 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
923 let skew = check_clock_skew(clock_skew_seconds)?;
924 let obj = credential
925 .as_object()
926 .ok_or_else(|| CoreError::Json("credential must be an object".into()))?;
927 let vf = obj
928 .get("validFrom")
929 .and_then(|v| v.as_str())
930 .ok_or_else(|| CoreError::Json("credential missing validFrom".into()))?;
931 let vu = obj
932 .get("validUntil")
933 .and_then(|v| v.as_str())
934 .ok_or_else(|| CoreError::Json("credential missing validUntil".into()))?;
935 let now = parse_protocol_time_ns(now_iso)?;
936 let from = parse_protocol_time_ns(vf)?;
937 let until = parse_protocol_time_ns(vu)?;
938 if window_state_ns(now, Some(from), Some(until), skew) != WindowState::Ok {
939 return Ok(false);
940 }
941 let proofs: Vec<&Value> = match obj.get("proof") {
944 Some(Value::Array(items)) => items.iter().collect(),
945 Some(p) => vec![p],
946 None => Vec::new(),
947 };
948 for p in proofs {
949 match p.get("expires") {
950 None => {}
951 Some(Value::String(e)) => {
952 let expires = parse_protocol_time_ns(e)?;
953 if window_state_ns(now, None, Some(expires), skew) != WindowState::Ok {
954 return Ok(false);
955 }
956 }
957 Some(_) => {
958 return Err(CoreError::Json(
959 "proof.expires must be a time string".into(),
960 ))
961 }
962 }
963 }
964 Ok(true)
965}
966
967crate::nesting::nested_fields!(BuildCredentialOptions; intent, delegation_chain, credential_status);
969
970#[cfg(test)]
971mod tests {
972 use super::*;
973
974 fn opts() -> BuildCredentialOptions {
975 BuildCredentialOptions {
976 issuer_did: "did:web:agent.example.com".into(),
977 credential_id: "urn:uuid:00000000-0000-4000-8000-000000000000".into(),
978 intent: json!({
979 "action": "read_database",
980 "target": "users_table",
981 "resource": "https://api.example.com/v1/users"
982 }),
983 valid_from: "2026-04-26T10:00:00Z".into(),
984 valid_until: "2026-04-26T10:05:00Z".into(),
985 reputation_score: Some(150),
986 delegation_chain: None,
987 credential_status: None,
988 }
989 }
990
991 #[test]
992 fn builds_expected_shape() {
993 let vc = build_vouch_credential(&opts()).unwrap();
994 assert_eq!(
995 vc["type"],
996 json!(["VerifiableCredential", "VouchCredential"])
997 );
998 assert_eq!(vc["credentialSubject"]["vouchVersion"], json!("1.0"));
999 assert_eq!(vc["credentialSubject"]["reputationScore"], json!(100));
1001 }
1002
1003 #[test]
1004 fn rejects_missing_intent_fields() {
1005 let mut o = opts();
1006 o.intent = json!({ "action": "read", "target": "t" }); assert!(build_vouch_credential(&o).is_err());
1008 }
1009
1010 #[test]
1011 #[cfg_attr(
1012 not(feature = "std"),
1013 ignore = "member order follows insertion only with std"
1014 )]
1015 fn sub_grant_names_its_parent_one_way_only() {
1016 let digest = "uEiCJcGBDXiN3XLgg5yQXBbX0UV019vMoX1n9_Ttuka1VAQ";
1017 let sub = build_sub_grant(&opts(), digest).unwrap();
1018 assert_eq!(sub["credentialSubject"]["parentGrantDigest"], json!(digest));
1019 assert!(sub["credentialSubject"].get("delegationChain").is_none());
1020 let keys: Vec<&str> = sub["credentialSubject"]
1022 .as_object()
1023 .unwrap()
1024 .keys()
1025 .map(|k| k.as_str())
1026 .collect();
1027 assert_eq!(
1028 keys,
1029 [
1030 "id",
1031 "vouchVersion",
1032 "intent",
1033 "reputationScore",
1034 "parentGrantDigest"
1035 ]
1036 );
1037 assert!(build_vouch_credential(&opts())
1038 .unwrap()
1039 .pointer("/credentialSubject/parentGrantDigest")
1040 .is_none());
1041 assert_eq!(
1042 build_sub_grant(&opts(), "").unwrap_err().to_string(),
1043 "json error: parent_grant_digest must be a grant digest string"
1044 );
1045 let mut both = opts();
1046 both.delegation_chain = Some(json!([{"issuer": "did:web:a"}]));
1047 assert_eq!(
1048 build_sub_grant(&both, digest).unwrap_err().to_string(),
1049 "json error: a credential carries parentGrantDigest or a delegationChain, never both"
1050 );
1051 both.delegation_chain = Some(json!([]));
1053 assert!(build_sub_grant(&both, digest).is_ok());
1054 let mut bad = opts();
1056 bad.intent = json!({ "action": "read" });
1057 assert!(build_sub_grant(&bad, "")
1058 .unwrap_err()
1059 .to_string()
1060 .contains("intent."));
1061 let seed = [5u8; 32];
1062 let signed = sign_sub_grant(
1063 &opts(),
1064 digest,
1065 &seed,
1066 &BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z"),
1067 )
1068 .unwrap();
1069 let pk = crate::keys::Ed25519KeyPair::from_seed(&seed).public_key();
1070 assert!(verify(&signed, &pk, "2026-04-26T10:02:00Z", 30)
1071 .unwrap()
1072 .is_valid());
1073 }
1074
1075 #[test]
1076 fn own_binding_fields_are_checked_on_every_verify_path() {
1077 let seed = [5u8; 32];
1078 let po = BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
1079 let with = |fields: Value| {
1080 let mut c = build_vouch_credential(&opts()).unwrap();
1081 for (k, v) in fields.as_object().unwrap() {
1082 c["credentialSubject"][k] = v.clone();
1083 }
1084 data_integrity::sign(&c, &seed, &po).unwrap()
1085 };
1086 let roots = ["did:web:root.example".to_string()];
1087 let with_roots = crate::delegation::ChainOptions {
1088 trusted_roots: Some(&roots),
1089 ..Default::default()
1090 };
1091 let none = crate::delegation::ChainOptions::default();
1092 let every_path = |c: &Value| {
1094 let mut out = Vec::new();
1095 for r in [
1096 verify(c, &pk(), NOW, 30).unwrap(),
1097 verify_with_roots(c, &pk(), NOW, 30, &roots).unwrap(),
1098 ] {
1099 assert!(r.proof_valid && r.time_valid);
1100 out.push((r.chain_valid, None));
1101 }
1102 for o in [&none, &with_roots] {
1103 let (r, reason) = verify_explained(c, &pk(), NOW, 30, o).unwrap();
1104 assert!(r.proof_valid && r.time_valid);
1105 out.push((r.chain_valid, reason.clone()));
1106 let (r, reason2) = verify_with_keys(c, &pk(), None, NOW, 30, o).unwrap();
1107 assert_eq!(reason2, reason);
1108 out.push((r.chain_valid, reason2));
1109 out.push((
1110 reason.is_none(),
1111 crate::delegation::verify_delegation_chain_with(c, NOW, 30, o),
1112 ));
1113 }
1114 out
1115 };
1116 let malformed = Some("malformed_delegation".to_string());
1117 let digest = "uEiCJcGBDXiN3XLgg5yQXBbX0UV019vMoX1n9_Ttuka1VAQ";
1118 for fields in [
1119 json!({"parentGrantDigest": null}),
1120 json!({"parentGrantDigest": 5}),
1121 json!({"parentGrantDigest": ["u"]}),
1122 json!({"parentGrantDigest": {}}),
1123 json!({"delegationChain": null}),
1124 json!({"delegationChain": {}}),
1125 json!({"parentGrantDigest": digest, "delegationChain": [{"issuer": "did:web:a"}]}),
1126 json!({"parentGrantDigest": null, "delegationChain": [{"issuer": "did:web:a"}]}),
1127 ] {
1128 for (i, (chain_valid, reason)) in
1129 every_path(&with(fields.clone())).into_iter().enumerate()
1130 {
1131 assert!(!chain_valid, "{fields} path {i}");
1132 if i >= 2 {
1133 assert_eq!(reason, malformed, "{fields} path {i}");
1134 }
1135 }
1136 }
1137 for fields in [
1140 json!({ "parentGrantDigest": digest }),
1141 json!({"parentGrantDigest": digest, "delegationChain": []}),
1142 ] {
1143 for (i, (chain_valid, reason)) in
1144 every_path(&with(fields.clone())).into_iter().enumerate()
1145 {
1146 assert!(chain_valid, "{fields} path {i}");
1147 assert_eq!(reason, None, "{fields} path {i}");
1148 }
1149 }
1150 }
1151
1152 #[test]
1153 fn sign_and_verify_within_window() {
1154 let seed = [5u8; 32];
1155 let proof_opts =
1156 BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z");
1157 let signed = sign_vouch_credential(&opts(), &seed, &proof_opts).unwrap();
1158 let pk = crate::keys::Ed25519KeyPair::from_seed(&seed).public_key();
1159 let r = verify(&signed, &pk, "2026-04-26T10:02:00Z", 30).unwrap();
1160 assert!(r.is_valid());
1161 let r2 = verify(&signed, &pk, "2026-04-26T11:00:00Z", 30).unwrap();
1163 assert!(r2.proof_valid && !r2.time_valid);
1164 }
1165
1166 fn signed_with(purpose: &str, vm: &str) -> Value {
1167 let seed = [5u8; 32];
1168 let mut proof_opts = BuildProofOptions::new(vm, "2026-04-26T10:00:00Z");
1169 proof_opts.proof_purpose = purpose.into();
1170 sign_vouch_credential(&opts(), &seed, &proof_opts).unwrap()
1171 }
1172
1173 fn pk() -> [u8; 32] {
1174 crate::keys::Ed25519KeyPair::from_seed(&[5u8; 32]).public_key()
1175 }
1176
1177 const NOW: &str = "2026-04-26T10:02:00Z";
1178
1179 #[test]
1180 fn proof_must_be_an_assertion_by_the_issuer() {
1181 let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
1182 assert!(verify(&ok, &pk(), NOW, 30).unwrap().is_valid());
1183 let auth = signed_with("authentication", "did:web:agent.example.com#key-1");
1184 assert!(!verify(&auth, &pk(), NOW, 30).unwrap().proof_valid);
1185 let other = signed_with("assertionMethod", "did:web:other.example.com#key-1");
1186 assert!(!verify(&other, &pk(), NOW, 30).unwrap().proof_valid);
1187 let prefix = signed_with("assertionMethod", "did:web:agent.example.com.evil#key-1");
1188 assert!(!verify(&prefix, &pk(), NOW, 30).unwrap().proof_valid);
1189 }
1190
1191 #[test]
1192 fn did_key_issuer_must_be_the_signing_key() {
1193 let seed = [6u8; 32];
1194 let kp = crate::keys::Ed25519KeyPair::from_seed(&seed);
1195 let did = kp.did_key();
1196 let mut o = opts();
1197 o.issuer_did = did.clone();
1198 let vm = format!("{did}#{}", did.trim_start_matches("did:key:"));
1199 let signed = sign_vouch_credential(
1200 &o,
1201 &seed,
1202 &BuildProofOptions::new(vm, "2026-04-26T10:00:00Z"),
1203 )
1204 .unwrap();
1205 assert!(verify(&signed, &kp.public_key(), NOW, 30)
1206 .unwrap()
1207 .is_valid());
1208 let other = [7u8; 32];
1210 let vm = format!("{did}#{}", did.trim_start_matches("did:key:"));
1211 let impostor = sign_vouch_credential(
1212 &o,
1213 &other,
1214 &BuildProofOptions::new(vm, "2026-04-26T10:00:00Z"),
1215 )
1216 .unwrap();
1217 let other_pk = crate::keys::Ed25519KeyPair::from_seed(&other).public_key();
1218 assert!(!verify(&impostor, &other_pk, NOW, 30).unwrap().proof_valid);
1219 }
1220
1221 #[test]
1222 fn vouch_version_and_resource_are_required() {
1223 let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
1224 for (path, value) in [
1225 ("vouchVersion", Value::Null),
1226 ("vouchVersion", json!("2.0")),
1227 ("vouchVersion", json!(1.0)),
1228 ] {
1229 let mut c = ok.clone();
1230 if value.is_null() {
1231 c["credentialSubject"].as_object_mut().unwrap().remove(path);
1232 } else {
1233 c["credentialSubject"][path] = value;
1234 }
1235 assert!(verify(&c, &pk(), NOW, 30).is_err(), "{path}");
1236 }
1237 for bad in [json!(""), json!(42), Value::Null, json!(["https://x"])] {
1238 let mut c = ok.clone();
1239 c["credentialSubject"]["intent"]["resource"] = bad.clone();
1240 assert!(verify(&c, &pk(), NOW, 30).is_err(), "{bad}");
1241 }
1242 let mut o = opts();
1244 o.intent["resource"] = json!("reports/q3.txt");
1245 let signed = sign_vouch_credential(
1246 &o,
1247 &[5u8; 32],
1248 &BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z"),
1249 )
1250 .unwrap();
1251 assert!(verify(&signed, &pk(), NOW, 30).unwrap().is_valid());
1252 }
1253
1254 #[test]
1255 fn window_rules() {
1256 let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
1257 for skew in [-1, 121, i64::MAX, i64::MIN] {
1259 assert!(verify(&ok, &pk(), NOW, skew).is_err(), "{skew}");
1260 assert!(verify_temporal(&ok, NOW, skew).is_err(), "{skew}");
1261 }
1262 for now in [
1264 "2026-04-26T10:02:00",
1265 "2026-04-26 10:02:00Z",
1266 "2026-04-26t10:02:00z",
1267 ] {
1268 assert!(verify_temporal(&ok, now, 30).is_err(), "{now}");
1269 }
1270 assert!(verify_temporal(&ok, "2026-04-26T10:05:00Z", 0).unwrap());
1272 assert!(!verify_temporal(&ok, "2026-04-26T10:05:00.000000001Z", 0).unwrap());
1273 let inverted =
1275 json!({"validFrom": "2026-04-26T10:05:00Z", "validUntil": "2026-04-26T10:00:00Z"});
1276 assert!(!verify_temporal(&inverted, "2026-04-26T10:02:00Z", 120).unwrap());
1277 let mut c = json!({"validFrom": "2026-04-26T10:00:00Z", "validUntil": "2026-04-26T10:05:00Z",
1279 "proof": {"expires": "2026-04-26T10:01:00Z"}});
1280 assert!(!verify_temporal(&c, NOW, 30).unwrap());
1281 c["proof"]["expires"] = json!("2026-04-26T10:03:00Z");
1282 assert!(verify_temporal(&c, NOW, 30).unwrap());
1283 c["proof"]["expires"] = json!(5);
1284 assert!(verify_temporal(&c, NOW, 30).is_err());
1285 }
1286
1287 #[test]
1288 fn proof_context_must_match_the_document() {
1289 let mut c = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
1290 c["proof"]["@context"] = json!(["https://example.com/other"]);
1291 assert!(!verify(&c, &pk(), NOW, 30).unwrap().proof_valid);
1292 }
1293
1294 #[test]
1295 fn issuer_object_is_bound_by_its_id() {
1296 let mut o = opts();
1297 o.issuer_did = "did:web:agent.example.com".into();
1298 let mut cred = build_vouch_credential(&o).unwrap();
1299 cred["issuer"] = json!({"id": "did:web:agent.example.com", "name": "Agent"});
1300 let signed = data_integrity::sign(
1301 &cred,
1302 &[5u8; 32],
1303 &BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z"),
1304 )
1305 .unwrap();
1306 assert!(verify(&signed, &pk(), NOW, 30).unwrap().is_valid());
1307 let mut bad = cred.clone();
1308 bad["issuer"] = json!(["did:web:agent.example.com"]);
1309 let signed = data_integrity::sign(
1310 &bad,
1311 &[5u8; 32],
1312 &BuildProofOptions::new("did:web:agent.example.com#key-1", "2026-04-26T10:00:00Z"),
1313 )
1314 .unwrap();
1315 assert!(!verify(&signed, &pk(), NOW, 30).unwrap().proof_valid);
1316 }
1317
1318 #[test]
1319 fn envelope_must_be_a_vouch_credential() {
1320 let ok = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
1321 for (key, value) in [
1322 ("@context", Value::Null),
1323 ("@context", json!("https://www.w3.org/ns/credentials/v2")),
1324 ("@context", json!(["https://example.com/other"])),
1325 ("type", json!(["VerifiableCredential"])),
1326 ("type", json!("VouchCredential")),
1327 ] {
1328 let mut c = ok.clone();
1329 if value.is_null() {
1330 c.as_object_mut().unwrap().remove(key);
1331 } else {
1332 c[key] = value.clone();
1333 }
1334 assert!(verify(&c, &pk(), NOW, 30).is_err(), "{key} = {value}");
1335 }
1336 let mut o = opts();
1338 o.issuer_did = "agent.example.com".into();
1339 let signed = sign_vouch_credential(
1340 &o,
1341 &[5u8; 32],
1342 &BuildProofOptions::new("agent.example.com#key-1", "2026-04-26T10:00:00Z"),
1343 )
1344 .unwrap();
1345 assert!(!verify(&signed, &pk(), NOW, 30).unwrap().proof_valid);
1346 let mut c = ok.clone();
1348 c["proof"]["created"] = json!("yesterday");
1349 assert!(verify(&c, &pk(), NOW, 30).is_err());
1350 }
1351
1352 #[test]
1353 #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
1354 fn every_proof_shape_through_one_verifier() {
1355 use crate::delegation::ChainOptions;
1356 let seed = [5u8; 32];
1357 let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
1358 let unsigned = build_vouch_credential(&opts()).unwrap();
1359 let dual = crate::hybrid::sign_dual(
1360 &unsigned,
1361 &seed,
1362 &ml,
1363 "did:web:agent.example.com#key-1",
1364 "did:web:agent.example.com#key-2",
1365 "2026-04-26T10:00:00Z",
1366 )
1367 .unwrap();
1368 let none = ChainOptions::default();
1369 let pq = ChainOptions {
1370 require_pq: true,
1371 ..Default::default()
1372 };
1373 let mlk = ml.public_key();
1374 let run = |c: &Value, ml: Option<&[u8]>, o: &ChainOptions| {
1375 verify_with_keys(c, &pk(), ml, NOW, 30, o).unwrap().0
1376 };
1377 assert!(run(&dual, Some(&mlk), &none).is_valid());
1378 assert!(run(&dual, Some(&mlk), &pq).is_valid());
1379 assert!(!run(&dual, None, &none).proof_valid);
1381 assert!(!verify(&dual, &pk(), NOW, 30).unwrap().proof_valid);
1382 let single = signed_with("assertionMethod", "did:web:agent.example.com#key-1");
1385 assert!(run(&single, None, &none).is_valid());
1386 assert!(!run(&single, None, &pq).proof_valid);
1387 assert!(!run(&single, Some(&mlk), &none).proof_valid);
1388 assert!(verify_with_keys(&dual, &pk(), Some(&mlk[..1311]), NOW, 30, &none).is_err());
1390 let bad_roots = vec!["127.0.0.1".to_string()];
1392 let with_bad = ChainOptions {
1393 trusted_roots: Some(&bad_roots),
1394 ..Default::default()
1395 };
1396 assert!(verify_with_keys(&single, &pk(), None, NOW, 30, &with_bad).is_err());
1397 let mut lone = dual.clone();
1399 lone["proof"] = dual["proof"][1].clone();
1400 assert!(!run(&lone, Some(&mlk), &none).proof_valid);
1401 let mut extra = dual.clone();
1402 extra["proof"]
1403 .as_array_mut()
1404 .unwrap()
1405 .push(dual["proof"][0].clone());
1406 assert!(!run(&extra, Some(&mlk), &none).proof_valid);
1407 let mut unknown = dual.clone();
1409 let mut odd = dual["proof"][0].clone();
1410 odd["cryptosuite"] = json!("some-unregistered-suite-2030");
1411 unknown["proof"].as_array_mut().unwrap().push(odd);
1412 assert!(!run(&unknown, Some(&mlk), &none).proof_valid);
1413 }
1414
1415 #[test]
1416 fn replay_key_is_issuer_nul_and_proof_digest() {
1417 use sha2::{Digest, Sha256};
1418 let k = replay_key("did:web:a.example", "z3abc").unwrap();
1419 let mut h = Sha256::new();
1420 h.update(b"did:web:a.example\x00");
1421 h.update(Sha256::digest(b"z3abc"));
1422 let want: String = h.finalize().iter().map(|b| format!("{b:02x}")).collect();
1423 assert_eq!(k, want);
1424 assert_eq!(k.len(), 64);
1425 assert!(replay_key("", "z3abc").is_err());
1426 assert!(replay_key("did:web:a.example", "").is_err());
1427 assert_ne!(
1429 replay_key("did:web:a", "bc").unwrap(),
1430 replay_key("did:web:ab", "c").unwrap()
1431 );
1432 }
1433}