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