1#[allow(unused_imports)]
11use crate::prelude::*;
12
13use alloc::collections::BTreeMap;
14
15use serde_json::{json, Map, Value};
16
17use crate::attenuation;
18use crate::data_integrity;
19use crate::error::{CoreError, Result};
20use crate::grant_chain;
21use crate::hybrid;
22use crate::multikey;
23use crate::time::{check_clock_skew, parse_protocol_time_ns, window_state_ns, WindowState};
24
25#[derive(Debug, Clone)]
27pub struct DelegationLinkInput {
28 pub issuer: String,
29 pub subject: String,
30 pub intent: Value,
31 pub valid_from: Option<String>,
32 pub valid_until: Option<String>,
33 pub parent_proof_value: Option<String>,
34}
35
36pub fn build_delegation_link(input: &DelegationLinkInput) -> Value {
38 crate::nesting::deep_guard!(Value::Null; input);
39 let mut link = Map::new();
40 link.insert("issuer".into(), json!(input.issuer));
41 link.insert("subject".into(), json!(input.subject));
42 link.insert("intent".into(), input.intent.clone());
43 if let Some(vf) = &input.valid_from {
44 link.insert("validFrom".into(), json!(vf));
45 }
46 if let Some(vu) = &input.valid_until {
47 link.insert("validUntil".into(), json!(vu));
48 }
49 if let Some(pp) = &input.parent_proof_value {
50 link.insert("parentProofValue".into(), json!(pp));
51 }
52 Value::Object(link)
53}
54
55fn link_bound(obj: &Map<String, Value>, key: &str) -> Result<Option<i128>> {
58 match obj.get(key) {
59 None => Ok(None),
60 Some(Value::String(s)) => Ok(Some(parse_protocol_time_ns(s)?)),
61 Some(_) => Err(CoreError::Json(format!(
62 "delegation link {key} must be a time string"
63 ))),
64 }
65}
66
67fn link_window(link: &Value) -> Result<(Option<i128>, Option<i128>)> {
68 let obj = link
69 .as_object()
70 .ok_or_else(|| CoreError::Json("delegation link must be an object".into()))?;
71 Ok((
72 link_bound(obj, "validFrom")?,
73 link_bound(obj, "validUntil")?,
74 ))
75}
76
77pub fn verify_chain_time_bound(
85 chain: &[Value],
86 now_iso: &str,
87 clock_skew_seconds: i64,
88) -> Result<bool> {
89 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); chain);
90 let skew = check_clock_skew(clock_skew_seconds)?;
91 let now = parse_protocol_time_ns(now_iso)?;
92 let mut eff_from: Option<i128> = None;
93 let mut eff_until: Option<i128> = None;
94
95 for link in chain {
96 let (vf, vu) = link_window(link)?;
97 if let (Some(f), Some(u)) = (vf, vu) {
98 if f > u {
99 return Ok(false); }
101 }
102 if let (Some(f), Some(ef)) = (vf, eff_from) {
103 if f < ef {
104 return Ok(false); }
106 }
107 if let (Some(u), Some(eu)) = (vu, eff_until) {
108 if u > eu {
109 return Ok(false); }
111 }
112 if let Some(f) = vf {
113 eff_from = Some(eff_from.map_or(f, |cur| cur.max(f)));
114 }
115 if let Some(u) = vu {
116 eff_until = Some(eff_until.map_or(u, |cur| cur.min(u)));
117 }
118 }
119 Ok(window_state_ns(now, eff_from, eff_until, skew) == WindowState::Ok)
120}
121
122pub fn capability_view(credential: &Value, include_time: bool) -> Value {
135 crate::nesting::deep_guard!(Value::Null; credential);
136 let intent = credential
137 .get("credentialSubject")
138 .and_then(|s| s.get("intent"))
139 .and_then(|i| i.as_object())
140 .cloned()
141 .unwrap_or_default();
142 let mut view = Map::new();
143 view.insert(
144 "issuer".into(),
145 issuer_did(credential)
146 .map(Value::String)
147 .unwrap_or(Value::Null),
148 );
149 view.insert(
150 "subject".into(),
151 intent.get("delegatee").cloned().unwrap_or(Value::Null),
152 );
153 let mut dims = Map::new();
154 for k in ["action", "target", "resource", "amount"] {
155 if let Some(v) = intent.get(k) {
156 dims.insert(k.into(), v.clone());
157 }
158 }
159 view.insert("intent".into(), Value::Object(dims));
160 if include_time {
161 for k in ["validFrom", "validUntil"] {
162 if let Some(v) = credential.get(k) {
163 view.insert(k.into(), v.clone());
164 }
165 }
166 }
167 for k in ["rate", "policy"] {
168 if let Some(v) = intent.get(k) {
169 view.insert(k.into(), v.clone());
170 }
171 }
172 Value::Object(view)
173}
174
175fn issuer_did(credential: &Value) -> Option<String> {
178 crate::credentials::issuer_did(credential).map(String::from)
179}
180
181fn resolve_chain_key(did: &str, root_keys: &BTreeMap<String, Vec<u8>>) -> Option<Vec<u8>> {
186 let from_did = match did.strip_prefix("did:key:") {
187 Some(mk) => {
188 let decoded = multikey::decode(mk).ok()?;
189 if decoded.algorithm != "Ed25519" {
190 return None;
191 }
192 Some(decoded.raw_key)
193 }
194 None => None,
195 };
196 let given = root_keys.get(did);
199 if given.is_some_and(|k| crate::keys::strict_verifying_key(k).is_err()) {
200 return None;
201 }
202 match (given, from_did) {
203 (Some(k), Some(d)) => (k == &d).then_some(d),
204 (Some(k), None) => Some(k.clone()),
205 (None, d) => d,
206 }
207}
208
209struct GrantIssuerKeys {
211 ed25519: Vec<u8>,
212 mldsa44: Option<Vec<u8>>,
213 slhdsa128: Option<Vec<u8>>,
214 requires: hybrid::Required,
217}
218
219fn grant_issuer_keys(
229 issuer: &str,
230 grant: &Value,
231 grant_keys: &BTreeMap<String, Vec<u8>>,
232 opts: &ChainOptions,
233) -> Option<GrantIssuerKeys> {
234 let given_requires = hybrid::Required {
239 post_quantum: false,
240 mldsa44: opts.mldsa_keys.is_some_and(|m| m.contains_key(issuer)),
241 slhdsa128: opts.slhdsa_keys.is_some_and(|m| m.contains_key(issuer)),
242 };
243 let given_mldsa = opts
244 .mldsa_keys
245 .and_then(|m| m.get(issuer))
246 .filter(|k| !k.is_empty())
247 .cloned();
248 let given_slhdsa = opts
249 .slhdsa_keys
250 .and_then(|m| m.get(issuer))
251 .filter(|k| !k.is_empty())
252 .cloned();
253 if let Some(ed25519) = resolve_chain_key(issuer, grant_keys) {
254 return Some(GrantIssuerKeys {
255 ed25519,
256 mldsa44: given_mldsa,
257 slhdsa128: given_slhdsa,
258 requires: given_requires,
259 });
260 }
261 if grant_keys.contains_key(issuer) {
262 return None;
263 }
264 let fetched = opts
265 .grant_documents
266 .filter(|_| issuer.starts_with("did:web:") || crate::did_webvh::is_did_webvh(issuer))
267 .and_then(|docs| docs.get(issuer));
268 let state = match fetched {
269 Some(document) => document.clone(),
270 None if crate::did_webvh::is_did_webvh(issuer) => {
271 opts.grant_logs?.resolve(issuer)?.ok()?.document
272 }
273 None => return None,
274 };
275 let methods = crate::credentials::proof_methods(grant);
276 let keys = crate::did_document::proof_keys_for(
277 &state,
278 issuer,
279 crate::did_document::ProofMethodRefs {
280 ed25519: methods.ed25519.as_deref(),
281 mldsa44: methods.mldsa44.as_deref(),
282 slhdsa128: methods.slhdsa128.as_deref(),
283 },
284 );
285 let published = keys.required();
286 let requires = hybrid::Required {
287 post_quantum: published.post_quantum,
288 mldsa44: published.mldsa44 || given_requires.mldsa44,
289 slhdsa128: published.slhdsa128 || given_requires.slhdsa128,
290 };
291 Some(GrantIssuerKeys {
292 ed25519: keys.ed25519?,
293 mldsa44: given_mldsa.or(keys.mldsa44),
294 slhdsa128: given_slhdsa.or(keys.slhdsa128),
295 requires,
296 })
297}
298
299pub(crate) fn parent_proof_binding_value(grant: &Value) -> String {
302 match grant.get("proof") {
303 Some(Value::Array(items)) => {
304 for p in items {
305 if p.get("cryptosuite").and_then(|v| v.as_str())
306 == Some(data_integrity::CRYPTOSUITE_ID)
307 {
308 return p
309 .get("proofValue")
310 .and_then(|v| v.as_str())
311 .unwrap_or("")
312 .to_string();
313 }
314 }
315 for p in items {
316 if let Some(v) = p.get("proofValue").and_then(|v| v.as_str()) {
317 if !v.is_empty() {
318 return v.to_string();
319 }
320 }
321 }
322 String::new()
323 }
324 Some(Value::Object(p)) => p
325 .get("proofValue")
326 .and_then(|v| v.as_str())
327 .unwrap_or("")
328 .to_string(),
329 _ => String::new(),
330 }
331}
332
333#[allow(clippy::too_many_arguments)]
347fn verify_grant_proof(
348 grant: &Value,
349 issuer: &str,
350 key: &[u8],
351 mldsa_key: Option<&[u8]>,
352 slhdsa_key: Option<&[u8]>,
353 required: hybrid::Required,
354 now: i128,
355 skew: i128,
356) -> bool {
357 if !grant_proof_well_formed(grant, issuer, now, skew) {
358 return false;
359 }
360 match grant.get("proof") {
361 Some(Value::Object(_)) => {
362 !required.any() && matches!(data_integrity::verify_proof(grant, key), Ok(true))
363 }
364 Some(Value::Array(items)) => {
365 let Some(members) = hybrid::set_members(items) else {
366 return false;
367 };
368 if !required.met_by(&members.suites()) {
369 return false;
370 }
371 let verdict = if required.any() {
372 hybrid::verify_set(grant, key, mldsa_key, slhdsa_key)
373 } else {
374 hybrid::verify_set_known_keys(grant, key, mldsa_key, slhdsa_key)
377 };
378 matches!(verdict, Ok(true))
379 }
380 _ => false,
381 }
382}
383
384fn grant_proof_well_formed(grant: &Value, issuer: &str, now: i128, skew: i128) -> bool {
389 let Some(proof) = grant.get("proof") else {
390 return false;
391 };
392 let members: Vec<&Value> = match proof {
393 Value::Array(items) => items.iter().collect(),
394 other => vec![other],
395 };
396 if members.is_empty()
397 || !members
398 .iter()
399 .all(|m| crate::credentials::proof_member_ok(m, issuer, now, skew))
400 {
401 return false;
402 }
403 match proof {
404 Value::Object(_) => hybrid::Suite::of_proof(proof) == Some(hybrid::Suite::Eddsa),
405 Value::Array(items) => hybrid::set_members(items).is_some(),
406 _ => false,
407 }
408}
409
410fn first_64(s: &str) -> String {
411 s.chars().take(64).collect()
412}
413
414pub const REASON_TRUSTED_ROOTS_REQUIRED: &str =
417 "the chain's starting point is not trusted: pass trusted roots";
418
419pub const REASON_BUDGET_EXCEEDED: &str = "verifier_budget_exceeded";
422
423pub const MAX_CHAIN_BYTES: usize = attenuation::MAX_CHAIN_BYTES;
428
429pub fn root_did(root: &str) -> Option<String> {
435 crate::did_web::normalize_root(root).ok()
436}
437
438pub fn root_matches(root: &str, issuer: &str) -> bool {
441 root_did(root).as_deref() == Some(issuer)
442}
443
444#[derive(Debug, Clone, Copy, Default)]
446pub struct ChainOptions<'a> {
447 pub trusted_roots: Option<&'a [String]>,
453 pub grant_keys: Option<&'a BTreeMap<String, Vec<u8>>>,
457 pub mldsa_keys: Option<&'a BTreeMap<String, Vec<u8>>>,
460 pub slhdsa_keys: Option<&'a BTreeMap<String, Vec<u8>>>,
463 pub slhdsa128_key: Option<&'a [u8]>,
468 pub grant_logs: Option<&'a crate::did_webvh::LogSet>,
477 pub grant_documents: Option<&'a BTreeMap<String, Value>>,
482 pub require_pq: bool,
486 pub require_suites: &'a [hybrid::Suite],
492 pub max_depth: Option<usize>,
495 pub through_link: Option<usize>,
501}
502
503pub fn verify_delegation_chain(
512 credential: &Value,
513 now_iso: &str,
514 clock_skew_seconds: i64,
515 root_keys: &BTreeMap<String, Vec<u8>>,
516 root_dids: Option<&[String]>,
517) -> Option<String> {
518 crate::nesting::deep_guard!(Some(crate::nesting::TOO_DEEP.into()); credential);
519 let opts = ChainOptions {
520 trusted_roots: root_dids,
521 grant_keys: Some(root_keys),
522 ..Default::default()
523 };
524 verify_delegation_chain_with(credential, now_iso, clock_skew_seconds, &opts)
525}
526
527pub fn chain_links_problem(
535 credential: &Value,
536 now_iso: &str,
537 clock_skew_seconds: i64,
538 opts: &ChainOptions,
539) -> Option<String> {
540 crate::nesting::deep_guard!(Some(crate::nesting::TOO_DEEP.into()); credential, opts);
541 let malformed = || Some("malformed_delegation".to_string());
542 if !credential.is_object() {
543 return malformed();
544 }
545 if let Some(reason) = grant_chain::binding_fields_problem(&credential["credentialSubject"]) {
549 return Some(reason.into());
550 }
551 let chain_value = match credential
552 .get("credentialSubject")
553 .and_then(|s| s.get("delegationChain"))
554 {
555 None => return None,
556 Some(Value::Array(a)) if a.is_empty() => return None,
557 Some(v @ Value::Array(_)) => v,
558 Some(_) => return malformed(),
560 };
561 let chain = chain_value.as_array().expect("checked above");
562 match attenuation::chain_budget_exceeded(chain_value, opts.max_depth) {
563 Ok(None) => {}
564 Ok(Some(_)) => return Some(REASON_BUDGET_EXCEEDED.into()),
565 Err(_) => return malformed(),
566 }
567 let Some(roots) = opts.trusted_roots else {
568 return Some(REASON_TRUSTED_ROOTS_REQUIRED.into());
569 };
570 if check_clock_skew(clock_skew_seconds).is_err() || parse_protocol_time_ns(now_iso).is_err() {
571 return malformed();
572 }
573
574 for link in chain {
576 let shape_ok = link.get("issuer").is_some_and(|v| v.is_string())
577 && link.get("subject").is_some_and(|v| v.is_string());
578 if !shape_ok {
579 return malformed();
580 }
581 }
582 for i in 1..chain.len() {
583 if chain[i - 1].get("subject") != chain[i].get("issuer") {
584 return Some("delegation_subject_issuer_mismatch".into());
585 }
586 }
587 let last_subject = chain[chain.len() - 1]
588 .get("subject")
589 .and_then(|v| v.as_str());
590 if last_subject.map(String::from) != issuer_did(credential) {
591 return Some("delegation_subject_issuer_mismatch".into());
592 }
593 let root = chain[0]
594 .get("issuer")
595 .and_then(|v| v.as_str())
596 .unwrap_or("");
597 if !roots.iter().any(|d| root_matches(d, root)) {
598 return Some("untrusted_principal".into());
599 }
600 if chain
605 .iter()
606 .all(|link| matches!(link.get("parentCredential"), Some(Value::Object(_))))
607 {
608 if let Some(reason) = grant_chain::chain_binding_problem(chain) {
609 return Some(reason.into());
610 }
611 }
612
613 None
614}
615
616pub fn verify_delegation_chain_with(
646 credential: &Value,
647 now_iso: &str,
648 clock_skew_seconds: i64,
649 opts: &ChainOptions,
650) -> Option<String> {
651 crate::nesting::deep_guard!(Some(crate::nesting::TOO_DEEP.into()); credential, opts);
652 let malformed = || Some("malformed_delegation".to_string());
653 if let Some(reason) = chain_links_problem(credential, now_iso, clock_skew_seconds, opts) {
654 return Some(reason);
655 }
656 let chain = credential
657 .get("credentialSubject")
658 .and_then(|s| s.get("delegationChain"))
659 .and_then(Value::as_array)
660 .filter(|c| !c.is_empty())?;
661 let (Ok(skew), Ok(now)) = (
662 check_clock_skew(clock_skew_seconds),
663 parse_protocol_time_ns(now_iso),
664 ) else {
665 return malformed();
666 };
667
668 let empty = BTreeMap::new();
669 let grant_keys = opts.grant_keys.unwrap_or(&empty);
670
671 let mut grants: Vec<&Value> = Vec::with_capacity(chain.len());
672 for (index, link) in chain.iter().enumerate() {
673 if opts.through_link == Some(index) {
674 return None;
675 }
676 let link_issuer = link["issuer"].as_str().unwrap_or_default();
677 let link_subject = link["subject"].as_str().unwrap_or_default();
678 let Some(grant) = link.get("parentCredential").filter(|g| g.is_object()) else {
679 return Some("delegation_link_unsigned".into());
680 };
681 if !matches!(
682 grant.get("proof"),
683 Some(Value::Object(_)) | Some(Value::Array(_))
684 ) {
685 return Some("delegation_link_unsigned".into());
686 }
687 let grant_issuer = issuer_did(grant);
688 if grant_issuer.as_deref() != Some(link_issuer) {
689 return Some("delegation_link_issuer_mismatch".into());
690 }
691 if !grant_proof_well_formed(grant, link_issuer, now, skew) {
694 return Some("delegation_signature_invalid".into());
695 }
696 if !opts.require_suites.is_empty() {
699 let carried = hybrid::proof_suites(grant);
700 if opts.require_suites.iter().any(|s| !carried.contains(s)) {
701 return Some("delegation_signature_invalid".into());
702 }
703 }
704 let Some(keys) = grant_issuer_keys(link_issuer, grant, grant_keys, opts) else {
705 return Some("delegation_issuer_key_unresolved".into());
706 };
707 if !verify_grant_proof(
711 grant,
712 link_issuer,
713 &keys.ed25519,
714 keys.mldsa44.as_deref(),
715 keys.slhdsa128.as_deref(),
716 hybrid::Required {
717 post_quantum: opts.require_pq
718 || keys.requires.post_quantum
719 || opts
720 .require_suites
721 .iter()
722 .any(|s| *s != hybrid::Suite::Eddsa),
723 mldsa44: keys.requires.mldsa44
724 || opts.require_suites.contains(&hybrid::Suite::Mldsa44),
725 slhdsa128: keys.requires.slhdsa128
726 || opts.require_suites.contains(&hybrid::Suite::Slhdsa128),
727 },
728 now,
729 skew,
730 ) {
731 return Some("delegation_signature_invalid".into());
732 }
733 if let Some(bound) = link.get("parentProofValue") {
734 let Some(bound) = bound.as_str() else {
736 return malformed();
737 };
738 if bound != first_64(&parent_proof_binding_value(grant)) {
739 return Some("delegation_link_tampered".into());
740 }
741 }
742 let delegatee = grant
743 .get("credentialSubject")
744 .and_then(|s| s.get("intent"))
745 .and_then(|i| i.get("delegatee"))
746 .and_then(|d| d.as_str())
747 .filter(|d| !d.is_empty());
748 let Some(delegatee) = delegatee else {
749 return Some("delegation_no_delegatee".into());
750 };
751 if delegatee != link_subject {
752 return Some("delegation_subject_mismatch".into());
753 }
754 let window = (
755 grant
756 .get("validFrom")
757 .and_then(|v| v.as_str())
758 .map(parse_protocol_time_ns),
759 grant
760 .get("validUntil")
761 .and_then(|v| v.as_str())
762 .map(parse_protocol_time_ns),
763 );
764 let (Some(Ok(from)), Some(Ok(until))) = window else {
765 return malformed();
766 };
767 match window_state_ns(now, Some(from), Some(until), skew) {
768 WindowState::Ok => {}
769 WindowState::Expired => return Some("delegation_expired".into()),
770 WindowState::NotYetValid => return Some("delegation_not_yet_valid".into()),
771 WindowState::Inverted => return malformed(),
772 }
773 grants.push(grant);
774 }
775
776 let last_subject = chain[chain.len() - 1]
777 .get("subject")
778 .and_then(|v| v.as_str());
779 if last_subject.map(String::from) != issuer_did(credential) {
780 return Some("delegation_subject_issuer_mismatch".into());
781 }
782
783 let mut views: Vec<Value> = grants.iter().map(|g| capability_view(g, true)).collect();
784 views.push(capability_view(credential, true));
785 if let Err(dim) = attenuation::first_broader_step(&views) {
786 return Some(format!("scope_exceeds_parent:{}", dim.as_str()));
787 }
788 None
789}
790
791crate::nesting::nested_fields!(DelegationLinkInput; intent);
793crate::nesting::nested_fields!(ChainOptions<'_>; grant_documents);
794
795#[cfg(test)]
796mod tests {
797 use super::*;
798
799 fn link(vf: &str, vu: &str) -> Value {
800 build_delegation_link(&DelegationLinkInput {
801 issuer: "did:web:a".into(),
802 subject: "did:web:b".into(),
803 intent: json!({"action":"read","target":"t","resource":"https://x/y"}),
804 valid_from: Some(vf.into()),
805 valid_until: Some(vu.into()),
806 parent_proof_value: None,
807 })
808 }
809
810 #[test]
811 fn nested_windows_pass() {
812 let chain = vec![
813 link("2026-04-26T09:00:00Z", "2026-04-26T12:00:00Z"),
814 link("2026-04-26T10:00:00Z", "2026-04-26T11:00:00Z"),
815 ];
816 assert!(verify_chain_time_bound(&chain, "2026-04-26T10:30:00Z", 30).unwrap());
817 }
818
819 #[test]
820 fn child_wider_than_parent_fails() {
821 let chain = vec![
822 link("2026-04-26T10:00:00Z", "2026-04-26T11:00:00Z"),
823 link("2026-04-26T09:00:00Z", "2026-04-26T12:00:00Z"), ];
825 assert!(!verify_chain_time_bound(&chain, "2026-04-26T10:30:00Z", 30).unwrap());
826 }
827
828 #[test]
829 fn now_outside_leaf_window_fails() {
830 let chain = vec![link("2026-04-26T10:00:00Z", "2026-04-26T11:00:00Z")];
831 assert!(!verify_chain_time_bound(&chain, "2026-04-26T12:00:00Z", 30).unwrap());
832 }
833
834 #[test]
835 fn a_window_less_middle_link_stays_bounded_by_the_root() {
836 let root = json!({"issuer":"did:web:root","subject":"did:web:a","intent":{},
837 "validFrom":"2026-04-26T09:00:00Z","validUntil":"2026-04-26T11:00:00Z"});
838 let mid = json!({"issuer":"did:web:a","subject":"did:web:b","intent":{}});
839 let leaf = json!({"issuer":"did:web:b","subject":"did:web:c","intent":{},
840 "validFrom":"2026-04-26T09:00:00Z","validUntil":"2099-01-01T00:00:00Z"});
841 let chain = vec![root.clone(), mid, leaf];
842 assert!(!verify_chain_time_bound(&chain, "2030-01-01T00:00:00Z", 30).unwrap());
843 assert!(!verify_chain_time_bound(&chain, "2026-04-26T10:00:00Z", 30).unwrap());
844 let bad = json!({"issuer":"did:web:a","subject":"did:web:b","intent":{},
846 "validFrom":"2026-04-26T09:00:00Z","validUntil":0});
847 assert!(verify_chain_time_bound(&[root.clone(), bad], "2026-04-26T10:00:00Z", 30).is_err());
848 let inv = link("2026-04-26T11:00:00Z", "2026-04-26T10:00:00Z");
850 assert!(!verify_chain_time_bound(&[inv], "2026-04-26T10:30:00Z", 120).unwrap());
851 assert!(verify_chain_time_bound(&[root], "2026-04-26T10:00:00Z", 121).is_err());
852 }
853
854 struct Party {
857 seed: [u8; 32],
858 did: String,
859 }
860
861 fn party(n: u8) -> Party {
862 let seed = [n; 32];
863 let did = crate::keys::Ed25519KeyPair::from_seed(&seed).did_key();
864 Party { seed, did }
865 }
866
867 fn vm(p: &Party) -> String {
868 format!("{}#{}", p.did, p.did.trim_start_matches("did:key:"))
869 }
870
871 fn grant_body(from: &Party, to: &Party) -> Value {
872 json!({
873 "@context": ["https://www.w3.org/ns/credentials/v2"],
874 "type": ["VerifiableCredential", "VouchCredential"],
875 "issuer": from.did,
876 "validFrom": "2026-04-26T09:00:00Z",
877 "validUntil": "2026-04-26T12:00:00Z",
878 "credentialSubject": {"id": from.did, "vouchVersion": "1.0", "intent": {
879 "action": "read", "target": "t", "resource": "https://x/a", "delegatee": to.did}}
880 })
881 }
882
883 fn leaf_credential(leaf: &Party, link: Value) -> Value {
884 json!({
885 "@context": ["https://www.w3.org/ns/credentials/v2"],
886 "type": ["VerifiableCredential", "VouchCredential"],
887 "issuer": leaf.did,
888 "validFrom": "2026-04-26T10:00:00Z",
889 "validUntil": "2026-04-26T10:05:00Z",
890 "credentialSubject": {"id": leaf.did, "vouchVersion": "1.0",
891 "intent": {"action": "read", "target": "t", "resource": "https://x/a/b"},
892 "delegationChain": [link]}
893 })
894 }
895
896 const NOW: &str = "2026-04-26T10:01:00Z";
897
898 fn opts_with<'a>(roots: &'a [String]) -> ChainOptions<'a> {
899 ChainOptions {
900 trusted_roots: Some(roots),
901 ..Default::default()
902 }
903 }
904
905 #[test]
906 fn signed_chain_needs_roots_and_respects_the_size_guard() {
907 let (root, leaf) = (party(1), party(2));
908 let grant = data_integrity::sign(
909 &grant_body(&root, &leaf),
910 &root.seed,
911 &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
912 )
913 .unwrap();
914 let link = json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant});
915 let cred = leaf_credential(&leaf, link.clone());
916 let roots = vec![root.did.clone()];
917 assert_eq!(
918 verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&roots)),
919 None
920 );
921 assert_eq!(
922 verify_delegation_chain_with(&cred, NOW, 30, &ChainOptions::default()),
923 Some(REASON_TRUSTED_ROOTS_REQUIRED.into())
924 );
925 assert_eq!(
927 verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&[])),
928 Some("untrusted_principal".into())
929 );
930 let bare = vec![root.did.trim_start_matches("did:key:").to_string()];
932 assert_eq!(
933 verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&bare)),
934 Some("untrusted_principal".into())
935 );
936 assert!(root_matches("yourcompany.com", "did:web:yourcompany.com"));
937 assert!(!root_matches(
938 "yourcompany.com",
939 "did:web:yourcompany.com.evil"
940 ));
941 assert!(!root_matches("yourcompany.com", "did:key:yourcompany.com"));
942 assert_eq!(
943 root_did("yourcompany.com").as_deref(),
944 Some("did:web:yourcompany.com")
945 );
946 assert_eq!(
947 root_did("yourcompany.com:8443").as_deref(),
948 Some("did:web:yourcompany.com%3A8443")
949 );
950 assert!(root_did("127.0.0.1").is_none());
951 let other = vec!["did:web:someone-else".to_string()];
952 assert_eq!(
953 verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&other)),
954 Some("untrusted_principal".into())
955 );
956 let budget = ChainOptions {
958 max_depth: Some(0),
959 ..opts_with(&roots)
960 };
961 assert_eq!(
962 verify_delegation_chain_with(&cred, NOW, 30, &budget),
963 Some(REASON_BUDGET_EXCEEDED.into())
964 );
965 let mut big = link;
967 big["note"] = json!("a".repeat(MAX_CHAIN_BYTES));
968 let cred = leaf_credential(&leaf, big);
969 assert_eq!(
970 verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&roots)),
971 Some(REASON_BUDGET_EXCEEDED.into())
972 );
973 }
974
975 #[test]
976 #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
977 fn post_quantum_profile_requires_a_valid_dual_proof_on_every_grant() {
978 let (root, leaf) = (party(3), party(4));
979 let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
980 let body = grant_body(&root, &leaf);
981 let dual = hybrid::sign_dual(
982 &body,
983 &root.seed,
984 &ml,
985 &vm(&root),
986 &format!("{}#mldsa", root.did),
987 "2026-04-26T09:00:00Z",
988 )
989 .unwrap();
990 let single = data_integrity::sign(
991 &body,
992 &root.seed,
993 &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
994 )
995 .unwrap();
996 let roots = vec![root.did.clone()];
997 let mut mldsa_keys = BTreeMap::new();
998 mldsa_keys.insert(root.did.clone(), ml.public_key().to_vec());
999 let pq = ChainOptions {
1000 trusted_roots: Some(&roots),
1001 mldsa_keys: Some(&mldsa_keys),
1002 require_pq: true,
1003 ..Default::default()
1004 };
1005 let chain_of = |grant: &Value| {
1006 leaf_credential(
1007 &leaf,
1008 json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
1009 )
1010 };
1011 assert_eq!(
1012 verify_delegation_chain_with(&chain_of(&dual), NOW, 30, &pq),
1013 None
1014 );
1015 assert_eq!(
1017 verify_delegation_chain_with(&chain_of(&single), NOW, 30, &pq),
1018 Some("delegation_signature_invalid".into())
1019 );
1020 let mut broken = dual.clone();
1022 broken["proof"][1]["proofValue"] = dual["proof"][0]["proofValue"].clone();
1023 assert_eq!(
1024 verify_delegation_chain_with(&chain_of(&broken), NOW, 30, &pq),
1025 Some("delegation_signature_invalid".into())
1026 );
1027 let none = ChainOptions {
1029 mldsa_keys: None,
1030 ..pq
1031 };
1032 assert_eq!(
1033 verify_delegation_chain_with(&chain_of(&dual), NOW, 30, &none),
1034 Some("delegation_signature_invalid".into())
1035 );
1036 assert_eq!(
1038 verify_delegation_chain_with(&chain_of(&dual), NOW, 30, &opts_with(&roots)),
1039 None
1040 );
1041 let mut foreign = dual.clone();
1043 foreign["proof"][1]["verificationMethod"] = json!("did:web:someone-else#k");
1044 assert_eq!(
1045 verify_delegation_chain_with(&chain_of(&foreign), NOW, 30, &opts_with(&roots)),
1046 Some("delegation_signature_invalid".into())
1047 );
1048 }
1049
1050 fn chain_with_proof(root: &Party, leaf: &Party, proof: Value) -> Value {
1052 let mut grant = grant_body(root, leaf);
1053 grant["proof"] = proof;
1054 leaf_credential(
1055 leaf,
1056 json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
1057 )
1058 }
1059
1060 fn eddsa_proof(root: &Party, leaf: &Party, opts: data_integrity::BuildProofOptions) -> Value {
1061 data_integrity::build_proof(&grant_body(root, leaf), &root.seed, &opts).unwrap()
1062 }
1063
1064 #[test]
1065 fn grant_proofs_follow_the_top_level_rules() {
1066 let (root, leaf) = (party(5), party(6));
1067 let roots = vec![root.did.clone()];
1068 let o = opts_with(&roots);
1069 let base = || data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z");
1070 let good = eddsa_proof(&root, &leaf, base());
1071 let check = |proof: Value| {
1072 verify_delegation_chain_with(&chain_with_proof(&root, &leaf, proof), NOW, 30, &o)
1073 };
1074 assert_eq!(check(good.clone()), None);
1075 let invalid = Some("delegation_signature_invalid".to_string());
1076 for expires in [json!("2026-04-26T09:30:00Z"), Value::Null, json!(5)] {
1078 let mut p = good.clone();
1079 p["expires"] = expires.clone();
1080 let mut unsigned = p.clone();
1081 unsigned.as_object_mut().unwrap().remove("proofValue");
1082 let input =
1083 data_integrity::hash_data(&grant_body(&root, &leaf), unsigned.as_object().unwrap())
1084 .unwrap();
1085 let sig = crate::keys::Ed25519KeyPair::from_seed(&root.seed).sign(&input);
1086 p["proofValue"] = json!(format!("z{}", bs58::encode(sig).into_string()));
1087 assert_eq!(check(p), invalid, "expires {expires}");
1088 }
1089 let mut opts = base();
1091 opts.created = "yesterday".into();
1092 assert_eq!(check(eddsa_proof(&root, &leaf, opts)), invalid);
1093 let mut p = good.clone();
1095 p["cryptosuite"] = json!("some-unregistered-suite-2030");
1096 assert_eq!(check(p), invalid);
1097 let mut p = good.clone();
1098 p.as_object_mut().unwrap().remove("proofValue");
1099 assert_eq!(check(p), invalid);
1100 assert_eq!(check(json!([good.clone(), 7])), invalid);
1101 assert_eq!(check(json!([good.clone()])), invalid);
1103 assert_eq!(check(json!([good.clone(), good.clone()])), invalid);
1104 }
1105
1106 #[test]
1107 fn grant_issuer_is_a_did_string_or_id() {
1108 let (root, leaf) = (party(7), party(8));
1109 let roots = vec![root.did.clone()];
1110 let mut body = grant_body(&root, &leaf);
1111 body["issuer"] = json!([root.did.clone()]);
1112 let grant = data_integrity::sign(
1113 &body,
1114 &root.seed,
1115 &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
1116 )
1117 .unwrap();
1118 let cred = leaf_credential(
1119 &leaf,
1120 json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
1121 );
1122 assert_eq!(
1123 verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&roots)),
1124 Some("delegation_link_issuer_mismatch".into())
1125 );
1126 }
1127
1128 #[test]
1129 #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
1130 fn a_known_mldsa_key_checks_the_grant_member() {
1131 let (root, leaf) = (party(9), party(10));
1132 let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
1133 let body = grant_body(&root, &leaf);
1134 let dual = hybrid::sign_dual(
1135 &body,
1136 &root.seed,
1137 &ml,
1138 &vm(&root),
1139 &format!("{}#mldsa", root.did),
1140 "2026-04-26T09:00:00Z",
1141 )
1142 .unwrap();
1143 let roots = vec![root.did.clone()];
1144 let mut keys = BTreeMap::new();
1145 keys.insert(root.did.clone(), ml.public_key().to_vec());
1146 let known = ChainOptions {
1147 trusted_roots: Some(&roots),
1148 mldsa_keys: Some(&keys),
1149 ..Default::default()
1150 };
1151 let link = |g: &Value| {
1152 leaf_credential(
1153 &leaf,
1154 json!({"issuer": root.did, "subject": leaf.did, "parentCredential": g}),
1155 )
1156 };
1157 assert_eq!(
1158 verify_delegation_chain_with(&link(&dual), NOW, 30, &known),
1159 None
1160 );
1161 let mut broken = dual.clone();
1163 broken["proof"][1]["proofValue"] = dual["proof"][0]["proofValue"].clone();
1164 assert_eq!(
1165 verify_delegation_chain_with(&link(&broken), NOW, 30, &known),
1166 Some("delegation_signature_invalid".into())
1167 );
1168 let composite =
1171 hybrid::composite_for_tests(&body, &root.seed, &ml, &vm(&root), "2026-04-26T09:00:00Z");
1172 assert_eq!(
1173 verify_delegation_chain_with(&link(&composite), NOW, 30, &known),
1174 Some("delegation_signature_invalid".into())
1175 );
1176 assert_eq!(
1177 verify_delegation_chain_with(&link(&composite), NOW, 30, &opts_with(&roots)),
1178 Some("delegation_signature_invalid".into())
1179 );
1180 }
1181
1182 #[test]
1183 #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
1184 fn a_grant_may_carry_an_slhdsa_proof() {
1185 let (root, leaf) = (party(21), party(22));
1186 let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
1187 let slh = crate::slh::SlhDsa128KeyPair::generate().unwrap();
1188 let body = grant_body(&root, &leaf);
1189 let ed_vm = vm(&root);
1190 let sign = |with_ml: bool| {
1191 hybrid::sign_set(
1192 &body,
1193 &root.seed,
1194 &ed_vm,
1195 with_ml.then_some(hybrid::PqSigner {
1196 key: &ml,
1197 verification_method: &crate::issuance::mldsa44_verification_method(&ed_vm),
1198 }),
1199 Some(hybrid::PqSigner {
1200 key: &slh,
1201 verification_method: &crate::issuance::slhdsa128_verification_method(&ed_vm),
1202 }),
1203 "2026-04-26T09:00:00Z",
1204 )
1205 .unwrap()
1206 };
1207 let roots = vec![root.did.clone()];
1208 let ml_keys = BTreeMap::from([(root.did.clone(), ml.public_key().to_vec())]);
1209 let slh_keys = BTreeMap::from([(root.did.clone(), slh.public_key().to_vec())]);
1210 let link = |g: &Value| {
1211 leaf_credential(
1212 &leaf,
1213 json!({"issuer": root.did, "subject": leaf.did, "parentCredential": g}),
1214 )
1215 };
1216 let all = ChainOptions {
1217 trusted_roots: Some(&roots),
1218 mldsa_keys: Some(&ml_keys),
1219 slhdsa_keys: Some(&slh_keys),
1220 ..Default::default()
1221 };
1222 let slh_only = ChainOptions {
1223 mldsa_keys: None,
1224 ..all
1225 };
1226 let invalid = Some("delegation_signature_invalid".to_string());
1227 for with_ml in [true, false] {
1228 let grant = sign(with_ml);
1229 if !with_ml {
1232 assert_eq!(
1233 verify_delegation_chain_with(&link(&grant), NOW, 30, &all),
1234 invalid
1235 );
1236 }
1237 let all = if with_ml { all } else { slh_only };
1238 assert_eq!(
1239 verify_delegation_chain_with(&link(&grant), NOW, 30, &all),
1240 None
1241 );
1242 let required = ChainOptions {
1244 require_pq: true,
1245 ..all
1246 };
1247 assert_eq!(
1248 verify_delegation_chain_with(&link(&grant), NOW, 30, &required),
1249 None
1250 );
1251 let no_slh = ChainOptions {
1252 slhdsa_keys: None,
1253 ..required
1254 };
1255 assert_eq!(
1256 verify_delegation_chain_with(&link(&grant), NOW, 30, &no_slh),
1257 invalid
1258 );
1259 let mut broken = grant.clone();
1261 let last = broken["proof"].as_array().unwrap().len() - 1;
1262 let value = broken["proof"][last]["proofValue"]
1263 .as_str()
1264 .unwrap()
1265 .to_string();
1266 let flipped = if value.ends_with('A') { "Q" } else { "A" };
1267 broken["proof"][last]["proofValue"] =
1268 json!(format!("{}{flipped}", &value[..value.len() - 1]));
1269 assert_eq!(
1270 verify_delegation_chain_with(&link(&broken), NOW, 30, &all),
1271 invalid
1272 );
1273 }
1274 }
1275
1276 #[test]
1277 fn a_did_key_grant_issuer_keeps_its_own_key() {
1278 let (root, leaf, other) = (party(11), party(12), party(13));
1279 let grant = data_integrity::sign(
1280 &grant_body(&root, &leaf),
1281 &root.seed,
1282 &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
1283 )
1284 .unwrap();
1285 let cred = leaf_credential(
1286 &leaf,
1287 json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
1288 );
1289 let roots = vec![root.did.clone()];
1290 let mut keys = BTreeMap::new();
1291 keys.insert(
1292 root.did.clone(),
1293 crate::keys::Ed25519KeyPair::from_seed(&other.seed)
1294 .public_key()
1295 .to_vec(),
1296 );
1297 let pinned = ChainOptions {
1298 trusted_roots: Some(&roots),
1299 grant_keys: Some(&keys),
1300 ..Default::default()
1301 };
1302 assert_eq!(
1303 verify_delegation_chain_with(&cred, NOW, 30, &pinned),
1304 Some("delegation_issuer_key_unresolved".into())
1305 );
1306 }
1307
1308 #[test]
1309 fn link_fields_are_checked_before_any_key() {
1310 let link = |iss: &str, sub: &str| {
1313 json!({"issuer": iss, "subject": sub,
1314 "parentCredential": {"issuer": iss, "proof": {"type": "DataIntegrityProof"}}})
1315 };
1316 let cred = |chain: Value| json!({"issuer": "did:web:c", "credentialSubject": {"delegationChain": chain}});
1317 let roots = vec!["did:web:root".to_string()];
1318 assert_eq!(
1319 verify_delegation_chain_with(
1320 &cred(json!([link("did:web:other", "did:web:c")])),
1321 NOW,
1322 30,
1323 &opts_with(&roots)
1324 ),
1325 Some("untrusted_principal".into())
1326 );
1327 assert_eq!(
1328 verify_delegation_chain_with(
1329 &cred(json!([
1330 link("did:web:root", "did:web:a"),
1331 link("did:web:b", "did:web:c")
1332 ])),
1333 NOW,
1334 30,
1335 &opts_with(&roots)
1336 ),
1337 Some("delegation_subject_issuer_mismatch".into())
1338 );
1339 assert_eq!(
1341 verify_delegation_chain_with(
1342 &cred(json!([link("did:web:root", "did:web:other")])),
1343 NOW,
1344 30,
1345 &opts_with(&roots)
1346 ),
1347 Some("delegation_subject_issuer_mismatch".into())
1348 );
1349 assert_eq!(
1352 verify_delegation_chain_with(
1353 &cred(json!([link("did:web:root", "did:web:c")])),
1354 NOW,
1355 30,
1356 &opts_with(&roots)
1357 ),
1358 Some("delegation_signature_invalid".into())
1359 );
1360 for chain in [Value::Null, json!({}), json!(""), json!(0), json!(false)] {
1362 assert_eq!(
1363 verify_delegation_chain_with(&cred(chain.clone()), NOW, 30, &opts_with(&roots)),
1364 Some("malformed_delegation".into()),
1365 "{chain}"
1366 );
1367 }
1368 let big =
1370 cred(json!([{"issuer": "x", "subject": "y", "pad": "a".repeat(MAX_CHAIN_BYTES)}]));
1371 assert_eq!(
1372 verify_delegation_chain_with(&big, NOW, 30, &ChainOptions::default()),
1373 Some(REASON_BUDGET_EXCEEDED.into())
1374 );
1375 }
1376
1377 #[test]
1378 fn grant_binding_is_checked_before_any_key() {
1379 let grant = |iss: &str, sub: &str, extra: Value| {
1382 let mut g = json!({"issuer": iss, "proof": {"type": "DataIntegrityProof"},
1383 "credentialSubject": {"intent": {"delegatee": sub}}});
1384 for (k, v) in extra.as_object().unwrap() {
1385 g["credentialSubject"][k] = v.clone();
1386 }
1387 g
1388 };
1389 let link = |g: &Value| {
1390 json!({"issuer": g["issuer"], "subject": g["credentialSubject"]["intent"]["delegatee"],
1391 "parentCredential": g})
1392 };
1393 let cred = |chain: Vec<Value>| json!({"issuer": "did:web:c", "credentialSubject": {"delegationChain": chain}});
1394 let roots = vec!["did:web:root".to_string()];
1395 let check = |chain: Vec<Value>| {
1396 verify_delegation_chain_with(&cred(chain), NOW, 30, &opts_with(&roots))
1397 };
1398 let g1 = grant("did:web:root", "did:web:a", json!({}));
1399 let digest = grant_chain::grant_digest(&g1).unwrap();
1400 let bound = grant(
1401 "did:web:a",
1402 "did:web:c",
1403 json!({ "parentGrantDigest": digest }),
1404 );
1405 let unbound = grant("did:web:a", "did:web:c", json!({}));
1406 assert_eq!(
1408 check(vec![link(&g1), link(&bound)]),
1409 Some("delegation_signature_invalid".into())
1410 );
1411 assert_eq!(
1412 check(vec![link(&g1), link(&unbound)]),
1413 Some("delegation_parent_mismatch".into())
1414 );
1415 let cut = grant(
1417 "did:web:root",
1418 "did:web:c",
1419 json!({ "parentGrantDigest": "uEiAAAA" }),
1420 );
1421 assert_eq!(
1422 check(vec![link(&cut)]),
1423 Some("delegation_parent_mismatch".into())
1424 );
1425 for extra in [
1427 json!({ "parentGrantDigest": null }),
1428 json!({ "delegationChain": null }),
1429 json!({ "parentGrantDigest": digest, "delegationChain": [link(&g1)] }),
1430 ] {
1431 let g2 = grant("did:web:a", "did:web:c", extra.clone());
1432 assert_eq!(
1433 check(vec![link(&g1), link(&g2)]),
1434 Some("malformed_delegation".into()),
1435 "{extra}"
1436 );
1437 }
1438 assert_eq!(
1440 verify_delegation_chain_with(
1441 &cred(vec![link(&g1), link(&unbound)]),
1442 NOW,
1443 30,
1444 &opts_with(&["did:web:other".to_string()])
1445 ),
1446 Some("untrusted_principal".into())
1447 );
1448 for missing in [None, Some(json!("grant")), Some(Value::Null)] {
1451 let mut first = link(&g1);
1452 match &missing {
1453 None => {
1454 first.as_object_mut().unwrap().remove("parentCredential");
1455 }
1456 Some(v) => first["parentCredential"] = v.clone(),
1457 }
1458 assert_eq!(
1459 check(vec![first, link(&unbound)]),
1460 Some("delegation_link_unsigned".into()),
1461 "{missing:?}"
1462 );
1463 }
1464 }
1465}