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 requires_post_quantum: bool,
210}
211
212fn grant_issuer_keys(
219 issuer: &str,
220 grant: &Value,
221 grant_keys: &BTreeMap<String, Vec<u8>>,
222 opts: &ChainOptions,
223) -> Option<GrantIssuerKeys> {
224 let given_mldsa = opts.mldsa_keys.and_then(|m| m.get(issuer)).cloned();
225 if let Some(ed25519) = resolve_chain_key(issuer, grant_keys) {
226 return Some(GrantIssuerKeys {
227 ed25519,
228 mldsa44: given_mldsa,
229 requires_post_quantum: false,
230 });
231 }
232 if grant_keys.contains_key(issuer) {
233 return None;
234 }
235 let fetched = opts
236 .grant_documents
237 .filter(|_| issuer.starts_with("did:web:") || crate::did_webvh::is_did_webvh(issuer))
238 .and_then(|docs| docs.get(issuer));
239 let state = match fetched {
240 Some(document) => document.clone(),
241 None if crate::did_webvh::is_did_webvh(issuer) => {
242 opts.grant_logs?.resolve(issuer)?.ok()?.document
243 }
244 None => return None,
245 };
246 let (ed_vm, ml_vm) = crate::credentials::proof_methods(grant);
247 let keys = crate::did_document::proof_keys(&state, issuer, ed_vm.as_deref(), ml_vm.as_deref());
248 Some(GrantIssuerKeys {
249 ed25519: keys.ed25519?,
250 mldsa44: given_mldsa.or(keys.mldsa44),
251 requires_post_quantum: keys.requires_post_quantum,
252 })
253}
254
255pub(crate) fn parent_proof_binding_value(grant: &Value) -> String {
258 match grant.get("proof") {
259 Some(Value::Array(items)) => {
260 for p in items {
261 if p.get("cryptosuite").and_then(|v| v.as_str())
262 == Some(data_integrity::CRYPTOSUITE_ID)
263 {
264 return p
265 .get("proofValue")
266 .and_then(|v| v.as_str())
267 .unwrap_or("")
268 .to_string();
269 }
270 }
271 for p in items {
272 if let Some(v) = p.get("proofValue").and_then(|v| v.as_str()) {
273 if !v.is_empty() {
274 return v.to_string();
275 }
276 }
277 }
278 String::new()
279 }
280 Some(Value::Object(p)) => p
281 .get("proofValue")
282 .and_then(|v| v.as_str())
283 .unwrap_or("")
284 .to_string(),
285 _ => String::new(),
286 }
287}
288
289fn verify_grant_proof(
301 grant: &Value,
302 issuer: &str,
303 key: &[u8],
304 mldsa_key: Option<&[u8]>,
305 require_pq: bool,
306 now: i128,
307 skew: i128,
308) -> bool {
309 let Some(proof) = grant.get("proof") else {
310 return false;
311 };
312 let members: Vec<&Value> = match proof {
313 Value::Array(items) => items.iter().collect(),
314 other => vec![other],
315 };
316 if members.is_empty()
317 || !members
318 .iter()
319 .all(|m| crate::credentials::proof_member_ok(m, issuer, now, skew))
320 {
321 return false;
322 }
323 let suite = |p: &Value| {
324 p.get("cryptosuite")
325 .and_then(|v| v.as_str())
326 .unwrap_or_default()
327 .to_string()
328 };
329 match proof {
330 Value::Object(_) => match suite(proof).as_str() {
331 data_integrity::CRYPTOSUITE_ID => {
332 !require_pq && matches!(data_integrity::verify_proof(grant, key), Ok(true))
333 }
334 hybrid::HYBRID_COMPOSITE_CRYPTOSUITE_ID => match mldsa_key {
335 Some(ml) => matches!(hybrid::verify_composite(grant, key, ml), Ok(true)),
336 None => false,
337 },
338 _ => false,
339 },
340 Value::Array(items) => {
341 let mut suites: Vec<String> = items
342 .iter()
343 .map(|p| {
344 let s = suite(p);
345 if s == hybrid::MLDSA44_LEGACY_CRYPTOSUITE_ID {
346 hybrid::MLDSA44_CRYPTOSUITE_ID.to_string()
347 } else {
348 s
349 }
350 })
351 .collect();
352 suites.sort();
353 if suites != [hybrid::EDDSA_CRYPTOSUITE_ID, hybrid::MLDSA44_CRYPTOSUITE_ID] {
354 return false;
355 }
356 match mldsa_key {
357 Some(ml) => matches!(hybrid::verify_dual(grant, key, ml), Ok(true)),
358 None if require_pq => false,
359 None => {
360 let Some(ed) = items
362 .iter()
363 .find(|p| suite(p) == data_integrity::CRYPTOSUITE_ID)
364 else {
365 return false;
366 };
367 let mut single = grant.clone();
368 single["proof"] = (*ed).clone();
369 matches!(data_integrity::verify_proof(&single, key), Ok(true))
370 }
371 }
372 }
373 _ => false,
374 }
375}
376
377fn grant_proof_well_formed(grant: &Value, issuer: &str, now: i128, skew: i128) -> bool {
382 let Some(proof) = grant.get("proof") else {
383 return false;
384 };
385 let members: Vec<&Value> = match proof {
386 Value::Array(items) => items.iter().collect(),
387 other => vec![other],
388 };
389 if members.is_empty()
390 || !members
391 .iter()
392 .all(|m| crate::credentials::proof_member_ok(m, issuer, now, skew))
393 {
394 return false;
395 }
396 let suite = |p: &Value| {
397 let s = p
398 .get("cryptosuite")
399 .and_then(|v| v.as_str())
400 .unwrap_or_default();
401 if s == hybrid::MLDSA44_LEGACY_CRYPTOSUITE_ID {
402 hybrid::MLDSA44_CRYPTOSUITE_ID.to_string()
403 } else {
404 s.to_string()
405 }
406 };
407 match proof {
408 Value::Object(_) => matches!(
409 suite(proof).as_str(),
410 data_integrity::CRYPTOSUITE_ID | hybrid::HYBRID_COMPOSITE_CRYPTOSUITE_ID
411 ),
412 Value::Array(items) => {
413 let mut suites: Vec<String> = items.iter().map(suite).collect();
414 suites.sort();
415 suites == [hybrid::EDDSA_CRYPTOSUITE_ID, hybrid::MLDSA44_CRYPTOSUITE_ID]
416 }
417 _ => false,
418 }
419}
420
421fn first_64(s: &str) -> String {
422 s.chars().take(64).collect()
423}
424
425pub const REASON_TRUSTED_ROOTS_REQUIRED: &str =
428 "the chain's starting point is not trusted: pass trusted roots";
429
430pub const REASON_BUDGET_EXCEEDED: &str = "verifier_budget_exceeded";
433
434pub const MAX_CHAIN_BYTES: usize = attenuation::MAX_CHAIN_BYTES;
439
440pub fn root_did(root: &str) -> Option<String> {
446 crate::did_web::normalize_root(root).ok()
447}
448
449pub fn root_matches(root: &str, issuer: &str) -> bool {
452 root_did(root).as_deref() == Some(issuer)
453}
454
455#[derive(Debug, Clone, Copy, Default)]
457pub struct ChainOptions<'a> {
458 pub trusted_roots: Option<&'a [String]>,
464 pub grant_keys: Option<&'a BTreeMap<String, Vec<u8>>>,
468 pub mldsa_keys: Option<&'a BTreeMap<String, Vec<u8>>>,
472 pub grant_logs: Option<&'a crate::did_webvh::LogSet>,
481 pub grant_documents: Option<&'a BTreeMap<String, Value>>,
486 pub require_pq: bool,
489 pub max_depth: Option<usize>,
492}
493
494pub fn verify_delegation_chain(
503 credential: &Value,
504 now_iso: &str,
505 clock_skew_seconds: i64,
506 root_keys: &BTreeMap<String, Vec<u8>>,
507 root_dids: Option<&[String]>,
508) -> Option<String> {
509 let opts = ChainOptions {
510 trusted_roots: root_dids,
511 grant_keys: Some(root_keys),
512 ..Default::default()
513 };
514 verify_delegation_chain_with(credential, now_iso, clock_skew_seconds, &opts)
515}
516
517pub fn verify_delegation_chain_with(
547 credential: &Value,
548 now_iso: &str,
549 clock_skew_seconds: i64,
550 opts: &ChainOptions,
551) -> Option<String> {
552 let malformed = || Some("malformed_delegation".to_string());
553 if !credential.is_object() {
554 return malformed();
555 }
556 if let Some(reason) = grant_chain::binding_fields_problem(&credential["credentialSubject"]) {
560 return Some(reason.into());
561 }
562 let chain_value = match credential
563 .get("credentialSubject")
564 .and_then(|s| s.get("delegationChain"))
565 {
566 None => return None,
567 Some(Value::Array(a)) if a.is_empty() => return None,
568 Some(v @ Value::Array(_)) => v,
569 Some(_) => return malformed(),
571 };
572 let chain = chain_value.as_array().expect("checked above");
573 match attenuation::chain_budget_exceeded(chain_value, opts.max_depth) {
574 Ok(None) => {}
575 Ok(Some(_)) => return Some(REASON_BUDGET_EXCEEDED.into()),
576 Err(_) => return malformed(),
577 }
578 let Some(roots) = opts.trusted_roots else {
579 return Some(REASON_TRUSTED_ROOTS_REQUIRED.into());
580 };
581 let Ok(skew) = check_clock_skew(clock_skew_seconds) else {
582 return malformed();
583 };
584 let Ok(now) = parse_protocol_time_ns(now_iso) else {
585 return malformed();
586 };
587
588 for link in chain {
590 let shape_ok = link.get("issuer").is_some_and(|v| v.is_string())
591 && link.get("subject").is_some_and(|v| v.is_string());
592 if !shape_ok {
593 return malformed();
594 }
595 }
596 for i in 1..chain.len() {
597 if chain[i - 1].get("subject") != chain[i].get("issuer") {
598 return Some("delegation_subject_issuer_mismatch".into());
599 }
600 }
601 let last_subject = chain[chain.len() - 1]
602 .get("subject")
603 .and_then(|v| v.as_str());
604 if last_subject.map(String::from) != issuer_did(credential) {
605 return Some("delegation_subject_issuer_mismatch".into());
606 }
607 let root = chain[0]
608 .get("issuer")
609 .and_then(|v| v.as_str())
610 .unwrap_or("");
611 if !roots.iter().any(|d| root_matches(d, root)) {
612 return Some("untrusted_principal".into());
613 }
614 if chain
619 .iter()
620 .all(|link| matches!(link.get("parentCredential"), Some(Value::Object(_))))
621 {
622 if let Some(reason) = grant_chain::chain_binding_problem(chain) {
623 return Some(reason.into());
624 }
625 }
626
627 let empty = BTreeMap::new();
628 let grant_keys = opts.grant_keys.unwrap_or(&empty);
629
630 let mut grants: Vec<&Value> = Vec::with_capacity(chain.len());
631 for link in chain {
632 let link_issuer = link["issuer"].as_str().unwrap_or_default();
633 let link_subject = link["subject"].as_str().unwrap_or_default();
634 let Some(grant) = link.get("parentCredential").filter(|g| g.is_object()) else {
635 return Some("delegation_link_unsigned".into());
636 };
637 if !matches!(
638 grant.get("proof"),
639 Some(Value::Object(_)) | Some(Value::Array(_))
640 ) {
641 return Some("delegation_link_unsigned".into());
642 }
643 let grant_issuer = issuer_did(grant);
644 if grant_issuer.as_deref() != Some(link_issuer) {
645 return Some("delegation_link_issuer_mismatch".into());
646 }
647 if !grant_proof_well_formed(grant, link_issuer, now, skew) {
650 return Some("delegation_signature_invalid".into());
651 }
652 let Some(keys) = grant_issuer_keys(link_issuer, grant, grant_keys, opts) else {
653 return Some("delegation_issuer_key_unresolved".into());
654 };
655 if !verify_grant_proof(
658 grant,
659 link_issuer,
660 &keys.ed25519,
661 keys.mldsa44.as_deref(),
662 opts.require_pq || keys.requires_post_quantum,
663 now,
664 skew,
665 ) {
666 return Some("delegation_signature_invalid".into());
667 }
668 if let Some(bound) = link.get("parentProofValue") {
669 let Some(bound) = bound.as_str() else {
671 return malformed();
672 };
673 if bound != first_64(&parent_proof_binding_value(grant)) {
674 return Some("delegation_link_tampered".into());
675 }
676 }
677 let delegatee = grant
678 .get("credentialSubject")
679 .and_then(|s| s.get("intent"))
680 .and_then(|i| i.get("delegatee"))
681 .and_then(|d| d.as_str())
682 .filter(|d| !d.is_empty());
683 let Some(delegatee) = delegatee else {
684 return Some("delegation_no_delegatee".into());
685 };
686 if delegatee != link_subject {
687 return Some("delegation_subject_mismatch".into());
688 }
689 let window = (
690 grant
691 .get("validFrom")
692 .and_then(|v| v.as_str())
693 .map(parse_protocol_time_ns),
694 grant
695 .get("validUntil")
696 .and_then(|v| v.as_str())
697 .map(parse_protocol_time_ns),
698 );
699 let (Some(Ok(from)), Some(Ok(until))) = window else {
700 return malformed();
701 };
702 match window_state_ns(now, Some(from), Some(until), skew) {
703 WindowState::Ok => {}
704 WindowState::Expired => return Some("delegation_expired".into()),
705 WindowState::NotYetValid => return Some("delegation_not_yet_valid".into()),
706 WindowState::Inverted => return malformed(),
707 }
708 grants.push(grant);
709 }
710
711 let last_subject = chain[chain.len() - 1]
712 .get("subject")
713 .and_then(|v| v.as_str());
714 if last_subject.map(String::from) != issuer_did(credential) {
715 return Some("delegation_subject_issuer_mismatch".into());
716 }
717
718 let mut views: Vec<Value> = grants.iter().map(|g| capability_view(g, true)).collect();
719 views.push(capability_view(credential, true));
720 if let Err(dim) = attenuation::first_broader_step(&views) {
721 return Some(format!("scope_exceeds_parent:{}", dim.as_str()));
722 }
723 None
724}
725
726#[cfg(test)]
727mod tests {
728 use super::*;
729
730 fn link(vf: &str, vu: &str) -> Value {
731 build_delegation_link(&DelegationLinkInput {
732 issuer: "did:web:a".into(),
733 subject: "did:web:b".into(),
734 intent: json!({"action":"read","target":"t","resource":"https://x/y"}),
735 valid_from: Some(vf.into()),
736 valid_until: Some(vu.into()),
737 parent_proof_value: None,
738 })
739 }
740
741 #[test]
742 fn nested_windows_pass() {
743 let chain = vec![
744 link("2026-04-26T09:00:00Z", "2026-04-26T12:00:00Z"),
745 link("2026-04-26T10:00:00Z", "2026-04-26T11:00:00Z"),
746 ];
747 assert!(verify_chain_time_bound(&chain, "2026-04-26T10:30:00Z", 30).unwrap());
748 }
749
750 #[test]
751 fn child_wider_than_parent_fails() {
752 let chain = vec![
753 link("2026-04-26T10:00:00Z", "2026-04-26T11:00:00Z"),
754 link("2026-04-26T09:00:00Z", "2026-04-26T12:00:00Z"), ];
756 assert!(!verify_chain_time_bound(&chain, "2026-04-26T10:30:00Z", 30).unwrap());
757 }
758
759 #[test]
760 fn now_outside_leaf_window_fails() {
761 let chain = vec![link("2026-04-26T10:00:00Z", "2026-04-26T11:00:00Z")];
762 assert!(!verify_chain_time_bound(&chain, "2026-04-26T12:00:00Z", 30).unwrap());
763 }
764
765 #[test]
766 fn a_window_less_middle_link_stays_bounded_by_the_root() {
767 let root = json!({"issuer":"did:web:root","subject":"did:web:a","intent":{},
768 "validFrom":"2026-04-26T09:00:00Z","validUntil":"2026-04-26T11:00:00Z"});
769 let mid = json!({"issuer":"did:web:a","subject":"did:web:b","intent":{}});
770 let leaf = json!({"issuer":"did:web:b","subject":"did:web:c","intent":{},
771 "validFrom":"2026-04-26T09:00:00Z","validUntil":"2099-01-01T00:00:00Z"});
772 let chain = vec![root.clone(), mid, leaf];
773 assert!(!verify_chain_time_bound(&chain, "2030-01-01T00:00:00Z", 30).unwrap());
774 assert!(!verify_chain_time_bound(&chain, "2026-04-26T10:00:00Z", 30).unwrap());
775 let bad = json!({"issuer":"did:web:a","subject":"did:web:b","intent":{},
777 "validFrom":"2026-04-26T09:00:00Z","validUntil":0});
778 assert!(verify_chain_time_bound(&[root.clone(), bad], "2026-04-26T10:00:00Z", 30).is_err());
779 let inv = link("2026-04-26T11:00:00Z", "2026-04-26T10:00:00Z");
781 assert!(!verify_chain_time_bound(&[inv], "2026-04-26T10:30:00Z", 120).unwrap());
782 assert!(verify_chain_time_bound(&[root], "2026-04-26T10:00:00Z", 121).is_err());
783 }
784
785 struct Party {
788 seed: [u8; 32],
789 did: String,
790 }
791
792 fn party(n: u8) -> Party {
793 let seed = [n; 32];
794 let did = crate::keys::Ed25519KeyPair::from_seed(&seed).did_key();
795 Party { seed, did }
796 }
797
798 fn vm(p: &Party) -> String {
799 format!("{}#{}", p.did, p.did.trim_start_matches("did:key:"))
800 }
801
802 fn grant_body(from: &Party, to: &Party) -> Value {
803 json!({
804 "@context": ["https://www.w3.org/ns/credentials/v2"],
805 "type": ["VerifiableCredential", "VouchCredential"],
806 "issuer": from.did,
807 "validFrom": "2026-04-26T09:00:00Z",
808 "validUntil": "2026-04-26T12:00:00Z",
809 "credentialSubject": {"id": from.did, "vouchVersion": "1.0", "intent": {
810 "action": "read", "target": "t", "resource": "https://x/a", "delegatee": to.did}}
811 })
812 }
813
814 fn leaf_credential(leaf: &Party, link: Value) -> Value {
815 json!({
816 "@context": ["https://www.w3.org/ns/credentials/v2"],
817 "type": ["VerifiableCredential", "VouchCredential"],
818 "issuer": leaf.did,
819 "validFrom": "2026-04-26T10:00:00Z",
820 "validUntil": "2026-04-26T10:05:00Z",
821 "credentialSubject": {"id": leaf.did, "vouchVersion": "1.0",
822 "intent": {"action": "read", "target": "t", "resource": "https://x/a/b"},
823 "delegationChain": [link]}
824 })
825 }
826
827 const NOW: &str = "2026-04-26T10:01:00Z";
828
829 fn opts_with<'a>(roots: &'a [String]) -> ChainOptions<'a> {
830 ChainOptions {
831 trusted_roots: Some(roots),
832 ..Default::default()
833 }
834 }
835
836 #[test]
837 fn signed_chain_needs_roots_and_respects_the_size_guard() {
838 let (root, leaf) = (party(1), party(2));
839 let grant = data_integrity::sign(
840 &grant_body(&root, &leaf),
841 &root.seed,
842 &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
843 )
844 .unwrap();
845 let link = json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant});
846 let cred = leaf_credential(&leaf, link.clone());
847 let roots = vec![root.did.clone()];
848 assert_eq!(
849 verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&roots)),
850 None
851 );
852 assert_eq!(
853 verify_delegation_chain_with(&cred, NOW, 30, &ChainOptions::default()),
854 Some(REASON_TRUSTED_ROOTS_REQUIRED.into())
855 );
856 assert_eq!(
858 verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&[])),
859 Some("untrusted_principal".into())
860 );
861 let bare = vec![root.did.trim_start_matches("did:key:").to_string()];
863 assert_eq!(
864 verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&bare)),
865 Some("untrusted_principal".into())
866 );
867 assert!(root_matches("yourcompany.com", "did:web:yourcompany.com"));
868 assert!(!root_matches(
869 "yourcompany.com",
870 "did:web:yourcompany.com.evil"
871 ));
872 assert!(!root_matches("yourcompany.com", "did:key:yourcompany.com"));
873 assert_eq!(
874 root_did("yourcompany.com").as_deref(),
875 Some("did:web:yourcompany.com")
876 );
877 assert_eq!(
878 root_did("yourcompany.com:8443").as_deref(),
879 Some("did:web:yourcompany.com%3A8443")
880 );
881 assert!(root_did("127.0.0.1").is_none());
882 let other = vec!["did:web:someone-else".to_string()];
883 assert_eq!(
884 verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&other)),
885 Some("untrusted_principal".into())
886 );
887 let budget = ChainOptions {
889 max_depth: Some(0),
890 ..opts_with(&roots)
891 };
892 assert_eq!(
893 verify_delegation_chain_with(&cred, NOW, 30, &budget),
894 Some(REASON_BUDGET_EXCEEDED.into())
895 );
896 let mut big = link;
898 big["note"] = json!("a".repeat(MAX_CHAIN_BYTES));
899 let cred = leaf_credential(&leaf, big);
900 assert_eq!(
901 verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&roots)),
902 Some(REASON_BUDGET_EXCEEDED.into())
903 );
904 }
905
906 #[test]
907 fn post_quantum_profile_requires_a_valid_dual_proof_on_every_grant() {
908 let (root, leaf) = (party(3), party(4));
909 let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
910 let body = grant_body(&root, &leaf);
911 let dual = hybrid::sign_dual(
912 &body,
913 &root.seed,
914 &ml,
915 &vm(&root),
916 &format!("{}#mldsa", root.did),
917 "2026-04-26T09:00:00Z",
918 )
919 .unwrap();
920 let single = data_integrity::sign(
921 &body,
922 &root.seed,
923 &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
924 )
925 .unwrap();
926 let roots = vec![root.did.clone()];
927 let mut mldsa_keys = BTreeMap::new();
928 mldsa_keys.insert(root.did.clone(), ml.public_key().to_vec());
929 let pq = ChainOptions {
930 trusted_roots: Some(&roots),
931 mldsa_keys: Some(&mldsa_keys),
932 require_pq: true,
933 ..Default::default()
934 };
935 let chain_of = |grant: &Value| {
936 leaf_credential(
937 &leaf,
938 json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
939 )
940 };
941 assert_eq!(
942 verify_delegation_chain_with(&chain_of(&dual), NOW, 30, &pq),
943 None
944 );
945 assert_eq!(
947 verify_delegation_chain_with(&chain_of(&single), NOW, 30, &pq),
948 Some("delegation_signature_invalid".into())
949 );
950 let mut broken = dual.clone();
952 broken["proof"][1]["proofValue"] = dual["proof"][0]["proofValue"].clone();
953 assert_eq!(
954 verify_delegation_chain_with(&chain_of(&broken), NOW, 30, &pq),
955 Some("delegation_signature_invalid".into())
956 );
957 let none = ChainOptions {
959 mldsa_keys: None,
960 ..pq
961 };
962 assert_eq!(
963 verify_delegation_chain_with(&chain_of(&dual), NOW, 30, &none),
964 Some("delegation_signature_invalid".into())
965 );
966 assert_eq!(
968 verify_delegation_chain_with(&chain_of(&dual), NOW, 30, &opts_with(&roots)),
969 None
970 );
971 let mut foreign = dual.clone();
973 foreign["proof"][1]["verificationMethod"] = json!("did:web:someone-else#k");
974 assert_eq!(
975 verify_delegation_chain_with(&chain_of(&foreign), NOW, 30, &opts_with(&roots)),
976 Some("delegation_signature_invalid".into())
977 );
978 }
979
980 fn chain_with_proof(root: &Party, leaf: &Party, proof: Value) -> Value {
982 let mut grant = grant_body(root, leaf);
983 grant["proof"] = proof;
984 leaf_credential(
985 leaf,
986 json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
987 )
988 }
989
990 fn eddsa_proof(root: &Party, leaf: &Party, opts: data_integrity::BuildProofOptions) -> Value {
991 data_integrity::build_proof(&grant_body(root, leaf), &root.seed, &opts).unwrap()
992 }
993
994 #[test]
995 fn grant_proofs_follow_the_top_level_rules() {
996 let (root, leaf) = (party(5), party(6));
997 let roots = vec![root.did.clone()];
998 let o = opts_with(&roots);
999 let base = || data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z");
1000 let good = eddsa_proof(&root, &leaf, base());
1001 let check = |proof: Value| {
1002 verify_delegation_chain_with(&chain_with_proof(&root, &leaf, proof), NOW, 30, &o)
1003 };
1004 assert_eq!(check(good.clone()), None);
1005 let invalid = Some("delegation_signature_invalid".to_string());
1006 for expires in [json!("2026-04-26T09:30:00Z"), Value::Null, json!(5)] {
1008 let mut p = good.clone();
1009 p["expires"] = expires.clone();
1010 let mut unsigned = p.clone();
1011 unsigned.as_object_mut().unwrap().remove("proofValue");
1012 let input =
1013 data_integrity::hash_data(&grant_body(&root, &leaf), unsigned.as_object().unwrap())
1014 .unwrap();
1015 let sig = crate::keys::Ed25519KeyPair::from_seed(&root.seed).sign(&input);
1016 p["proofValue"] = json!(format!("z{}", bs58::encode(sig).into_string()));
1017 assert_eq!(check(p), invalid, "expires {expires}");
1018 }
1019 let mut opts = base();
1021 opts.created = "yesterday".into();
1022 assert_eq!(check(eddsa_proof(&root, &leaf, opts)), invalid);
1023 let mut p = good.clone();
1025 p["cryptosuite"] = json!("some-unregistered-suite-2030");
1026 assert_eq!(check(p), invalid);
1027 let mut p = good.clone();
1028 p.as_object_mut().unwrap().remove("proofValue");
1029 assert_eq!(check(p), invalid);
1030 assert_eq!(check(json!([good.clone(), 7])), invalid);
1031 assert_eq!(check(json!([good.clone()])), invalid);
1033 assert_eq!(check(json!([good.clone(), good.clone()])), invalid);
1034 }
1035
1036 #[test]
1037 fn grant_issuer_is_a_did_string_or_id() {
1038 let (root, leaf) = (party(7), party(8));
1039 let roots = vec![root.did.clone()];
1040 let mut body = grant_body(&root, &leaf);
1041 body["issuer"] = json!([root.did.clone()]);
1042 let grant = data_integrity::sign(
1043 &body,
1044 &root.seed,
1045 &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
1046 )
1047 .unwrap();
1048 let cred = leaf_credential(
1049 &leaf,
1050 json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
1051 );
1052 assert_eq!(
1053 verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&roots)),
1054 Some("delegation_link_issuer_mismatch".into())
1055 );
1056 }
1057
1058 #[test]
1059 fn a_known_mldsa_key_checks_the_grant_member() {
1060 let (root, leaf) = (party(9), party(10));
1061 let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
1062 let body = grant_body(&root, &leaf);
1063 let dual = hybrid::sign_dual(
1064 &body,
1065 &root.seed,
1066 &ml,
1067 &vm(&root),
1068 &format!("{}#mldsa", root.did),
1069 "2026-04-26T09:00:00Z",
1070 )
1071 .unwrap();
1072 let roots = vec![root.did.clone()];
1073 let mut keys = BTreeMap::new();
1074 keys.insert(root.did.clone(), ml.public_key().to_vec());
1075 let known = ChainOptions {
1076 trusted_roots: Some(&roots),
1077 mldsa_keys: Some(&keys),
1078 ..Default::default()
1079 };
1080 let link = |g: &Value| {
1081 leaf_credential(
1082 &leaf,
1083 json!({"issuer": root.did, "subject": leaf.did, "parentCredential": g}),
1084 )
1085 };
1086 assert_eq!(
1087 verify_delegation_chain_with(&link(&dual), NOW, 30, &known),
1088 None
1089 );
1090 let mut broken = dual.clone();
1092 broken["proof"][1]["proofValue"] = dual["proof"][0]["proofValue"].clone();
1093 assert_eq!(
1094 verify_delegation_chain_with(&link(&broken), NOW, 30, &known),
1095 Some("delegation_signature_invalid".into())
1096 );
1097 #[allow(deprecated)]
1100 let composite =
1101 hybrid::sign_composite(&body, &root.seed, &ml, &vm(&root), "2026-04-26T09:00:00Z")
1102 .unwrap();
1103 assert_eq!(
1104 verify_delegation_chain_with(&link(&composite), NOW, 30, &known),
1105 Some("delegation_signature_invalid".into())
1106 );
1107 assert_eq!(
1108 verify_delegation_chain_with(&link(&composite), NOW, 30, &opts_with(&roots)),
1109 Some("delegation_signature_invalid".into())
1110 );
1111 }
1112
1113 #[test]
1114 fn a_did_key_grant_issuer_keeps_its_own_key() {
1115 let (root, leaf, other) = (party(11), party(12), party(13));
1116 let grant = data_integrity::sign(
1117 &grant_body(&root, &leaf),
1118 &root.seed,
1119 &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
1120 )
1121 .unwrap();
1122 let cred = leaf_credential(
1123 &leaf,
1124 json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
1125 );
1126 let roots = vec![root.did.clone()];
1127 let mut keys = BTreeMap::new();
1128 keys.insert(
1129 root.did.clone(),
1130 crate::keys::Ed25519KeyPair::from_seed(&other.seed)
1131 .public_key()
1132 .to_vec(),
1133 );
1134 let pinned = ChainOptions {
1135 trusted_roots: Some(&roots),
1136 grant_keys: Some(&keys),
1137 ..Default::default()
1138 };
1139 assert_eq!(
1140 verify_delegation_chain_with(&cred, NOW, 30, &pinned),
1141 Some("delegation_issuer_key_unresolved".into())
1142 );
1143 }
1144
1145 #[test]
1146 fn link_fields_are_checked_before_any_key() {
1147 let link = |iss: &str, sub: &str| {
1150 json!({"issuer": iss, "subject": sub,
1151 "parentCredential": {"issuer": iss, "proof": {"type": "DataIntegrityProof"}}})
1152 };
1153 let cred = |chain: Value| json!({"issuer": "did:web:c", "credentialSubject": {"delegationChain": chain}});
1154 let roots = vec!["did:web:root".to_string()];
1155 assert_eq!(
1156 verify_delegation_chain_with(
1157 &cred(json!([link("did:web:other", "did:web:c")])),
1158 NOW,
1159 30,
1160 &opts_with(&roots)
1161 ),
1162 Some("untrusted_principal".into())
1163 );
1164 assert_eq!(
1165 verify_delegation_chain_with(
1166 &cred(json!([
1167 link("did:web:root", "did:web:a"),
1168 link("did:web:b", "did:web:c")
1169 ])),
1170 NOW,
1171 30,
1172 &opts_with(&roots)
1173 ),
1174 Some("delegation_subject_issuer_mismatch".into())
1175 );
1176 assert_eq!(
1178 verify_delegation_chain_with(
1179 &cred(json!([link("did:web:root", "did:web:other")])),
1180 NOW,
1181 30,
1182 &opts_with(&roots)
1183 ),
1184 Some("delegation_subject_issuer_mismatch".into())
1185 );
1186 assert_eq!(
1189 verify_delegation_chain_with(
1190 &cred(json!([link("did:web:root", "did:web:c")])),
1191 NOW,
1192 30,
1193 &opts_with(&roots)
1194 ),
1195 Some("delegation_signature_invalid".into())
1196 );
1197 for chain in [Value::Null, json!({}), json!(""), json!(0), json!(false)] {
1199 assert_eq!(
1200 verify_delegation_chain_with(&cred(chain.clone()), NOW, 30, &opts_with(&roots)),
1201 Some("malformed_delegation".into()),
1202 "{chain}"
1203 );
1204 }
1205 let big =
1207 cred(json!([{"issuer": "x", "subject": "y", "pad": "a".repeat(MAX_CHAIN_BYTES)}]));
1208 assert_eq!(
1209 verify_delegation_chain_with(&big, NOW, 30, &ChainOptions::default()),
1210 Some(REASON_BUDGET_EXCEEDED.into())
1211 );
1212 }
1213
1214 #[test]
1215 fn grant_binding_is_checked_before_any_key() {
1216 let grant = |iss: &str, sub: &str, extra: Value| {
1219 let mut g = json!({"issuer": iss, "proof": {"type": "DataIntegrityProof"},
1220 "credentialSubject": {"intent": {"delegatee": sub}}});
1221 for (k, v) in extra.as_object().unwrap() {
1222 g["credentialSubject"][k] = v.clone();
1223 }
1224 g
1225 };
1226 let link = |g: &Value| {
1227 json!({"issuer": g["issuer"], "subject": g["credentialSubject"]["intent"]["delegatee"],
1228 "parentCredential": g})
1229 };
1230 let cred = |chain: Vec<Value>| json!({"issuer": "did:web:c", "credentialSubject": {"delegationChain": chain}});
1231 let roots = vec!["did:web:root".to_string()];
1232 let check = |chain: Vec<Value>| {
1233 verify_delegation_chain_with(&cred(chain), NOW, 30, &opts_with(&roots))
1234 };
1235 let g1 = grant("did:web:root", "did:web:a", json!({}));
1236 let digest = grant_chain::grant_digest(&g1).unwrap();
1237 let bound = grant(
1238 "did:web:a",
1239 "did:web:c",
1240 json!({ "parentGrantDigest": digest }),
1241 );
1242 let unbound = grant("did:web:a", "did:web:c", json!({}));
1243 assert_eq!(
1245 check(vec![link(&g1), link(&bound)]),
1246 Some("delegation_signature_invalid".into())
1247 );
1248 assert_eq!(
1249 check(vec![link(&g1), link(&unbound)]),
1250 Some("delegation_parent_mismatch".into())
1251 );
1252 let cut = grant(
1254 "did:web:root",
1255 "did:web:c",
1256 json!({ "parentGrantDigest": "uEiAAAA" }),
1257 );
1258 assert_eq!(
1259 check(vec![link(&cut)]),
1260 Some("delegation_parent_mismatch".into())
1261 );
1262 for extra in [
1264 json!({ "parentGrantDigest": null }),
1265 json!({ "delegationChain": null }),
1266 json!({ "parentGrantDigest": digest, "delegationChain": [link(&g1)] }),
1267 ] {
1268 let g2 = grant("did:web:a", "did:web:c", extra.clone());
1269 assert_eq!(
1270 check(vec![link(&g1), link(&g2)]),
1271 Some("malformed_delegation".into()),
1272 "{extra}"
1273 );
1274 }
1275 assert_eq!(
1277 verify_delegation_chain_with(
1278 &cred(vec![link(&g1), link(&unbound)]),
1279 NOW,
1280 30,
1281 &opts_with(&["did:web:other".to_string()])
1282 ),
1283 Some("untrusted_principal".into())
1284 );
1285 for missing in [None, Some(json!("grant")), Some(Value::Null)] {
1288 let mut first = link(&g1);
1289 match &missing {
1290 None => {
1291 first.as_object_mut().unwrap().remove("parentCredential");
1292 }
1293 Some(v) => first["parentCredential"] = v.clone(),
1294 }
1295 assert_eq!(
1296 check(vec![first, link(&unbound)]),
1297 Some("delegation_link_unsigned".into()),
1298 "{missing:?}"
1299 );
1300 }
1301 }
1302}