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