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