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 match (root_keys.get(did), from_did) {
191 (Some(k), Some(d)) => (k == &d).then_some(d),
192 (Some(k), None) => Some(k.clone()),
193 (None, d) => d,
194 }
195}
196
197pub(crate) fn parent_proof_binding_value(grant: &Value) -> String {
200 match grant.get("proof") {
201 Some(Value::Array(items)) => {
202 for p in items {
203 if p.get("cryptosuite").and_then(|v| v.as_str())
204 == Some(data_integrity::CRYPTOSUITE_ID)
205 {
206 return p
207 .get("proofValue")
208 .and_then(|v| v.as_str())
209 .unwrap_or("")
210 .to_string();
211 }
212 }
213 for p in items {
214 if let Some(v) = p.get("proofValue").and_then(|v| v.as_str()) {
215 if !v.is_empty() {
216 return v.to_string();
217 }
218 }
219 }
220 String::new()
221 }
222 Some(Value::Object(p)) => p
223 .get("proofValue")
224 .and_then(|v| v.as_str())
225 .unwrap_or("")
226 .to_string(),
227 _ => String::new(),
228 }
229}
230
231fn verify_grant_proof(
243 grant: &Value,
244 issuer: &str,
245 key: &[u8],
246 mldsa_key: Option<&[u8]>,
247 require_pq: bool,
248 now: i128,
249 skew: i128,
250) -> bool {
251 let Some(proof) = grant.get("proof") else {
252 return false;
253 };
254 let members: Vec<&Value> = match proof {
255 Value::Array(items) => items.iter().collect(),
256 other => vec![other],
257 };
258 if members.is_empty()
259 || !members
260 .iter()
261 .all(|m| crate::credentials::proof_member_ok(m, issuer, now, skew))
262 {
263 return false;
264 }
265 let suite = |p: &Value| {
266 p.get("cryptosuite")
267 .and_then(|v| v.as_str())
268 .unwrap_or_default()
269 .to_string()
270 };
271 match proof {
272 Value::Object(_) => match suite(proof).as_str() {
273 data_integrity::CRYPTOSUITE_ID => {
274 !require_pq && matches!(data_integrity::verify_proof(grant, key), Ok(true))
275 }
276 hybrid::HYBRID_COMPOSITE_CRYPTOSUITE_ID => match mldsa_key {
277 Some(ml) => matches!(hybrid::verify_composite(grant, key, ml), Ok(true)),
278 None => false,
279 },
280 _ => false,
281 },
282 Value::Array(items) => {
283 let mut suites: Vec<String> = items
284 .iter()
285 .map(|p| {
286 let s = suite(p);
287 if s == hybrid::MLDSA44_LEGACY_CRYPTOSUITE_ID {
288 hybrid::MLDSA44_CRYPTOSUITE_ID.to_string()
289 } else {
290 s
291 }
292 })
293 .collect();
294 suites.sort();
295 if suites != [hybrid::EDDSA_CRYPTOSUITE_ID, hybrid::MLDSA44_CRYPTOSUITE_ID] {
296 return false;
297 }
298 match mldsa_key {
299 Some(ml) => matches!(hybrid::verify_dual(grant, key, ml), Ok(true)),
300 None if require_pq => false,
301 None => {
302 let Some(ed) = items
304 .iter()
305 .find(|p| suite(p) == data_integrity::CRYPTOSUITE_ID)
306 else {
307 return false;
308 };
309 let mut single = grant.clone();
310 single["proof"] = (*ed).clone();
311 matches!(data_integrity::verify_proof(&single, key), Ok(true))
312 }
313 }
314 }
315 _ => false,
316 }
317}
318
319fn grant_proof_well_formed(grant: &Value, issuer: &str, now: i128, skew: i128) -> bool {
324 let Some(proof) = grant.get("proof") else {
325 return false;
326 };
327 let members: Vec<&Value> = match proof {
328 Value::Array(items) => items.iter().collect(),
329 other => vec![other],
330 };
331 if members.is_empty()
332 || !members
333 .iter()
334 .all(|m| crate::credentials::proof_member_ok(m, issuer, now, skew))
335 {
336 return false;
337 }
338 let suite = |p: &Value| {
339 let s = p
340 .get("cryptosuite")
341 .and_then(|v| v.as_str())
342 .unwrap_or_default();
343 if s == hybrid::MLDSA44_LEGACY_CRYPTOSUITE_ID {
344 hybrid::MLDSA44_CRYPTOSUITE_ID.to_string()
345 } else {
346 s.to_string()
347 }
348 };
349 match proof {
350 Value::Object(_) => matches!(
351 suite(proof).as_str(),
352 data_integrity::CRYPTOSUITE_ID | hybrid::HYBRID_COMPOSITE_CRYPTOSUITE_ID
353 ),
354 Value::Array(items) => {
355 let mut suites: Vec<String> = items.iter().map(suite).collect();
356 suites.sort();
357 suites == [hybrid::EDDSA_CRYPTOSUITE_ID, hybrid::MLDSA44_CRYPTOSUITE_ID]
358 }
359 _ => false,
360 }
361}
362
363fn first_64(s: &str) -> String {
364 s.chars().take(64).collect()
365}
366
367pub const REASON_TRUSTED_ROOTS_REQUIRED: &str =
370 "the chain's starting point is not trusted: pass trusted roots";
371
372pub const REASON_BUDGET_EXCEEDED: &str = "verifier_budget_exceeded";
375
376pub const MAX_CHAIN_BYTES: usize = attenuation::MAX_CHAIN_BYTES;
381
382pub fn root_did(root: &str) -> Option<String> {
388 crate::did_web::normalize_root(root).ok()
389}
390
391pub fn root_matches(root: &str, issuer: &str) -> bool {
394 root_did(root).as_deref() == Some(issuer)
395}
396
397#[derive(Debug, Clone, Copy, Default)]
399pub struct ChainOptions<'a> {
400 pub trusted_roots: Option<&'a [String]>,
406 pub grant_keys: Option<&'a BTreeMap<String, Vec<u8>>>,
409 pub mldsa_keys: Option<&'a BTreeMap<String, Vec<u8>>>,
413 pub require_pq: bool,
416 pub max_depth: Option<usize>,
419}
420
421pub fn verify_delegation_chain(
430 credential: &Value,
431 now_iso: &str,
432 clock_skew_seconds: i64,
433 root_keys: &BTreeMap<String, Vec<u8>>,
434 root_dids: Option<&[String]>,
435) -> Option<String> {
436 let opts = ChainOptions {
437 trusted_roots: root_dids,
438 grant_keys: Some(root_keys),
439 ..Default::default()
440 };
441 verify_delegation_chain_with(credential, now_iso, clock_skew_seconds, &opts)
442}
443
444pub fn verify_delegation_chain_with(
474 credential: &Value,
475 now_iso: &str,
476 clock_skew_seconds: i64,
477 opts: &ChainOptions,
478) -> Option<String> {
479 let malformed = || Some("malformed_delegation".to_string());
480 if !credential.is_object() {
481 return malformed();
482 }
483 if let Some(reason) = grant_chain::binding_fields_problem(&credential["credentialSubject"]) {
487 return Some(reason.into());
488 }
489 let chain_value = match credential
490 .get("credentialSubject")
491 .and_then(|s| s.get("delegationChain"))
492 {
493 None => return None,
494 Some(Value::Array(a)) if a.is_empty() => return None,
495 Some(v @ Value::Array(_)) => v,
496 Some(_) => return malformed(),
498 };
499 let chain = chain_value.as_array().expect("checked above");
500 match attenuation::chain_budget_exceeded(chain_value, opts.max_depth) {
501 Ok(None) => {}
502 Ok(Some(_)) => return Some(REASON_BUDGET_EXCEEDED.into()),
503 Err(_) => return malformed(),
504 }
505 let Some(roots) = opts.trusted_roots else {
506 return Some(REASON_TRUSTED_ROOTS_REQUIRED.into());
507 };
508 let Ok(skew) = check_clock_skew(clock_skew_seconds) else {
509 return malformed();
510 };
511 let Ok(now) = parse_protocol_time_ns(now_iso) else {
512 return malformed();
513 };
514
515 for link in chain {
517 let shape_ok = link.get("issuer").is_some_and(|v| v.is_string())
518 && link.get("subject").is_some_and(|v| v.is_string());
519 if !shape_ok {
520 return malformed();
521 }
522 }
523 for i in 1..chain.len() {
524 if chain[i - 1].get("subject") != chain[i].get("issuer") {
525 return Some("delegation_subject_issuer_mismatch".into());
526 }
527 }
528 let last_subject = chain[chain.len() - 1]
529 .get("subject")
530 .and_then(|v| v.as_str());
531 if last_subject.map(String::from) != issuer_did(credential) {
532 return Some("delegation_subject_issuer_mismatch".into());
533 }
534 let root = chain[0]
535 .get("issuer")
536 .and_then(|v| v.as_str())
537 .unwrap_or("");
538 if !roots.iter().any(|d| root_matches(d, root)) {
539 return Some("untrusted_principal".into());
540 }
541 if chain
546 .iter()
547 .all(|link| matches!(link.get("parentCredential"), Some(Value::Object(_))))
548 {
549 if let Some(reason) = grant_chain::chain_binding_problem(chain) {
550 return Some(reason.into());
551 }
552 }
553
554 let empty = BTreeMap::new();
555 let grant_keys = opts.grant_keys.unwrap_or(&empty);
556
557 let mut grants: Vec<&Value> = Vec::with_capacity(chain.len());
558 for link in chain {
559 let link_issuer = link["issuer"].as_str().unwrap_or_default();
560 let link_subject = link["subject"].as_str().unwrap_or_default();
561 let Some(grant) = link.get("parentCredential").filter(|g| g.is_object()) else {
562 return Some("delegation_link_unsigned".into());
563 };
564 if !matches!(
565 grant.get("proof"),
566 Some(Value::Object(_)) | Some(Value::Array(_))
567 ) {
568 return Some("delegation_link_unsigned".into());
569 }
570 let grant_issuer = issuer_did(grant);
571 if grant_issuer.as_deref() != Some(link_issuer) {
572 return Some("delegation_link_issuer_mismatch".into());
573 }
574 if !grant_proof_well_formed(grant, link_issuer, now, skew) {
577 return Some("delegation_signature_invalid".into());
578 }
579 let Some(key) = resolve_chain_key(link_issuer, grant_keys) else {
580 return Some("delegation_issuer_key_unresolved".into());
581 };
582 let mldsa_key = opts
585 .mldsa_keys
586 .and_then(|m| m.get(link_issuer))
587 .map(|k| k.as_slice());
588 if !verify_grant_proof(
589 grant,
590 link_issuer,
591 &key,
592 mldsa_key,
593 opts.require_pq,
594 now,
595 skew,
596 ) {
597 return Some("delegation_signature_invalid".into());
598 }
599 if let Some(bound) = link.get("parentProofValue") {
600 let Some(bound) = bound.as_str() else {
602 return malformed();
603 };
604 if bound != first_64(&parent_proof_binding_value(grant)) {
605 return Some("delegation_link_tampered".into());
606 }
607 }
608 let delegatee = grant
609 .get("credentialSubject")
610 .and_then(|s| s.get("intent"))
611 .and_then(|i| i.get("delegatee"))
612 .and_then(|d| d.as_str())
613 .filter(|d| !d.is_empty());
614 let Some(delegatee) = delegatee else {
615 return Some("delegation_no_delegatee".into());
616 };
617 if delegatee != link_subject {
618 return Some("delegation_subject_mismatch".into());
619 }
620 let window = (
621 grant
622 .get("validFrom")
623 .and_then(|v| v.as_str())
624 .map(parse_protocol_time_ns),
625 grant
626 .get("validUntil")
627 .and_then(|v| v.as_str())
628 .map(parse_protocol_time_ns),
629 );
630 let (Some(Ok(from)), Some(Ok(until))) = window else {
631 return malformed();
632 };
633 match window_state_ns(now, Some(from), Some(until), skew) {
634 WindowState::Ok => {}
635 WindowState::Expired => return Some("delegation_expired".into()),
636 WindowState::NotYetValid => return Some("delegation_not_yet_valid".into()),
637 WindowState::Inverted => return malformed(),
638 }
639 grants.push(grant);
640 }
641
642 let last_subject = chain[chain.len() - 1]
643 .get("subject")
644 .and_then(|v| v.as_str());
645 if last_subject.map(String::from) != issuer_did(credential) {
646 return Some("delegation_subject_issuer_mismatch".into());
647 }
648
649 let mut views: Vec<Value> = grants.iter().map(|g| capability_view(g, true)).collect();
650 views.push(capability_view(credential, true));
651 if let Err(dim) = attenuation::first_broader_step(&views) {
652 return Some(format!("scope_exceeds_parent:{}", dim.as_str()));
653 }
654 None
655}
656
657#[cfg(test)]
658mod tests {
659 use super::*;
660
661 fn link(vf: &str, vu: &str) -> Value {
662 build_delegation_link(&DelegationLinkInput {
663 issuer: "did:web:a".into(),
664 subject: "did:web:b".into(),
665 intent: json!({"action":"read","target":"t","resource":"https://x/y"}),
666 valid_from: Some(vf.into()),
667 valid_until: Some(vu.into()),
668 parent_proof_value: None,
669 })
670 }
671
672 #[test]
673 fn nested_windows_pass() {
674 let chain = vec![
675 link("2026-04-26T09:00:00Z", "2026-04-26T12:00:00Z"),
676 link("2026-04-26T10:00:00Z", "2026-04-26T11:00:00Z"),
677 ];
678 assert!(verify_chain_time_bound(&chain, "2026-04-26T10:30:00Z", 30).unwrap());
679 }
680
681 #[test]
682 fn child_wider_than_parent_fails() {
683 let chain = vec![
684 link("2026-04-26T10:00:00Z", "2026-04-26T11:00:00Z"),
685 link("2026-04-26T09:00:00Z", "2026-04-26T12:00:00Z"), ];
687 assert!(!verify_chain_time_bound(&chain, "2026-04-26T10:30:00Z", 30).unwrap());
688 }
689
690 #[test]
691 fn now_outside_leaf_window_fails() {
692 let chain = vec![link("2026-04-26T10:00:00Z", "2026-04-26T11:00:00Z")];
693 assert!(!verify_chain_time_bound(&chain, "2026-04-26T12:00:00Z", 30).unwrap());
694 }
695
696 #[test]
697 fn a_window_less_middle_link_stays_bounded_by_the_root() {
698 let root = json!({"issuer":"did:web:root","subject":"did:web:a","intent":{},
699 "validFrom":"2026-04-26T09:00:00Z","validUntil":"2026-04-26T11:00:00Z"});
700 let mid = json!({"issuer":"did:web:a","subject":"did:web:b","intent":{}});
701 let leaf = json!({"issuer":"did:web:b","subject":"did:web:c","intent":{},
702 "validFrom":"2026-04-26T09:00:00Z","validUntil":"2099-01-01T00:00:00Z"});
703 let chain = vec![root.clone(), mid, leaf];
704 assert!(!verify_chain_time_bound(&chain, "2030-01-01T00:00:00Z", 30).unwrap());
705 assert!(!verify_chain_time_bound(&chain, "2026-04-26T10:00:00Z", 30).unwrap());
706 let bad = json!({"issuer":"did:web:a","subject":"did:web:b","intent":{},
708 "validFrom":"2026-04-26T09:00:00Z","validUntil":0});
709 assert!(verify_chain_time_bound(&[root.clone(), bad], "2026-04-26T10:00:00Z", 30).is_err());
710 let inv = link("2026-04-26T11:00:00Z", "2026-04-26T10:00:00Z");
712 assert!(!verify_chain_time_bound(&[inv], "2026-04-26T10:30:00Z", 120).unwrap());
713 assert!(verify_chain_time_bound(&[root], "2026-04-26T10:00:00Z", 121).is_err());
714 }
715
716 struct Party {
719 seed: [u8; 32],
720 did: String,
721 }
722
723 fn party(n: u8) -> Party {
724 let seed = [n; 32];
725 let did = crate::keys::Ed25519KeyPair::from_seed(&seed).did_key();
726 Party { seed, did }
727 }
728
729 fn vm(p: &Party) -> String {
730 format!("{}#{}", p.did, p.did.trim_start_matches("did:key:"))
731 }
732
733 fn grant_body(from: &Party, to: &Party) -> Value {
734 json!({
735 "@context": ["https://www.w3.org/ns/credentials/v2"],
736 "type": ["VerifiableCredential", "VouchCredential"],
737 "issuer": from.did,
738 "validFrom": "2026-04-26T09:00:00Z",
739 "validUntil": "2026-04-26T12:00:00Z",
740 "credentialSubject": {"id": from.did, "vouchVersion": "1.0", "intent": {
741 "action": "read", "target": "t", "resource": "https://x/a", "delegatee": to.did}}
742 })
743 }
744
745 fn leaf_credential(leaf: &Party, link: Value) -> Value {
746 json!({
747 "@context": ["https://www.w3.org/ns/credentials/v2"],
748 "type": ["VerifiableCredential", "VouchCredential"],
749 "issuer": leaf.did,
750 "validFrom": "2026-04-26T10:00:00Z",
751 "validUntil": "2026-04-26T10:05:00Z",
752 "credentialSubject": {"id": leaf.did, "vouchVersion": "1.0",
753 "intent": {"action": "read", "target": "t", "resource": "https://x/a/b"},
754 "delegationChain": [link]}
755 })
756 }
757
758 const NOW: &str = "2026-04-26T10:01:00Z";
759
760 fn opts_with<'a>(roots: &'a [String]) -> ChainOptions<'a> {
761 ChainOptions {
762 trusted_roots: Some(roots),
763 ..Default::default()
764 }
765 }
766
767 #[test]
768 fn signed_chain_needs_roots_and_respects_the_size_guard() {
769 let (root, leaf) = (party(1), party(2));
770 let grant = data_integrity::sign(
771 &grant_body(&root, &leaf),
772 &root.seed,
773 &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
774 )
775 .unwrap();
776 let link = json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant});
777 let cred = leaf_credential(&leaf, link.clone());
778 let roots = vec![root.did.clone()];
779 assert_eq!(
780 verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&roots)),
781 None
782 );
783 assert_eq!(
784 verify_delegation_chain_with(&cred, NOW, 30, &ChainOptions::default()),
785 Some(REASON_TRUSTED_ROOTS_REQUIRED.into())
786 );
787 assert_eq!(
789 verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&[])),
790 Some("untrusted_principal".into())
791 );
792 let bare = vec![root.did.trim_start_matches("did:key:").to_string()];
794 assert_eq!(
795 verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&bare)),
796 Some("untrusted_principal".into())
797 );
798 assert!(root_matches("yourcompany.com", "did:web:yourcompany.com"));
799 assert!(!root_matches(
800 "yourcompany.com",
801 "did:web:yourcompany.com.evil"
802 ));
803 assert!(!root_matches("yourcompany.com", "did:key:yourcompany.com"));
804 assert_eq!(
805 root_did("yourcompany.com").as_deref(),
806 Some("did:web:yourcompany.com")
807 );
808 assert_eq!(
809 root_did("yourcompany.com:8443").as_deref(),
810 Some("did:web:yourcompany.com%3A8443")
811 );
812 assert!(root_did("127.0.0.1").is_none());
813 let other = vec!["did:web:someone-else".to_string()];
814 assert_eq!(
815 verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&other)),
816 Some("untrusted_principal".into())
817 );
818 let budget = ChainOptions {
820 max_depth: Some(0),
821 ..opts_with(&roots)
822 };
823 assert_eq!(
824 verify_delegation_chain_with(&cred, NOW, 30, &budget),
825 Some(REASON_BUDGET_EXCEEDED.into())
826 );
827 let mut big = link;
829 big["note"] = json!("a".repeat(MAX_CHAIN_BYTES));
830 let cred = leaf_credential(&leaf, big);
831 assert_eq!(
832 verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&roots)),
833 Some(REASON_BUDGET_EXCEEDED.into())
834 );
835 }
836
837 #[test]
838 fn post_quantum_profile_requires_a_valid_dual_proof_on_every_grant() {
839 let (root, leaf) = (party(3), party(4));
840 let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
841 let body = grant_body(&root, &leaf);
842 let dual = hybrid::sign_dual(
843 &body,
844 &root.seed,
845 &ml,
846 &vm(&root),
847 &format!("{}#mldsa", root.did),
848 "2026-04-26T09:00:00Z",
849 )
850 .unwrap();
851 let single = data_integrity::sign(
852 &body,
853 &root.seed,
854 &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
855 )
856 .unwrap();
857 let roots = vec![root.did.clone()];
858 let mut mldsa_keys = BTreeMap::new();
859 mldsa_keys.insert(root.did.clone(), ml.public_key().to_vec());
860 let pq = ChainOptions {
861 trusted_roots: Some(&roots),
862 mldsa_keys: Some(&mldsa_keys),
863 require_pq: true,
864 ..Default::default()
865 };
866 let chain_of = |grant: &Value| {
867 leaf_credential(
868 &leaf,
869 json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
870 )
871 };
872 assert_eq!(
873 verify_delegation_chain_with(&chain_of(&dual), NOW, 30, &pq),
874 None
875 );
876 assert_eq!(
878 verify_delegation_chain_with(&chain_of(&single), NOW, 30, &pq),
879 Some("delegation_signature_invalid".into())
880 );
881 let mut broken = dual.clone();
883 broken["proof"][1]["proofValue"] = dual["proof"][0]["proofValue"].clone();
884 assert_eq!(
885 verify_delegation_chain_with(&chain_of(&broken), NOW, 30, &pq),
886 Some("delegation_signature_invalid".into())
887 );
888 let none = ChainOptions {
890 mldsa_keys: None,
891 ..pq
892 };
893 assert_eq!(
894 verify_delegation_chain_with(&chain_of(&dual), NOW, 30, &none),
895 Some("delegation_signature_invalid".into())
896 );
897 assert_eq!(
899 verify_delegation_chain_with(&chain_of(&dual), NOW, 30, &opts_with(&roots)),
900 None
901 );
902 let mut foreign = dual.clone();
904 foreign["proof"][1]["verificationMethod"] = json!("did:web:someone-else#k");
905 assert_eq!(
906 verify_delegation_chain_with(&chain_of(&foreign), NOW, 30, &opts_with(&roots)),
907 Some("delegation_signature_invalid".into())
908 );
909 }
910
911 fn chain_with_proof(root: &Party, leaf: &Party, proof: Value) -> Value {
913 let mut grant = grant_body(root, leaf);
914 grant["proof"] = proof;
915 leaf_credential(
916 leaf,
917 json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
918 )
919 }
920
921 fn eddsa_proof(root: &Party, leaf: &Party, opts: data_integrity::BuildProofOptions) -> Value {
922 data_integrity::build_proof(&grant_body(root, leaf), &root.seed, &opts).unwrap()
923 }
924
925 #[test]
926 fn grant_proofs_follow_the_top_level_rules() {
927 let (root, leaf) = (party(5), party(6));
928 let roots = vec![root.did.clone()];
929 let o = opts_with(&roots);
930 let base = || data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z");
931 let good = eddsa_proof(&root, &leaf, base());
932 let check = |proof: Value| {
933 verify_delegation_chain_with(&chain_with_proof(&root, &leaf, proof), NOW, 30, &o)
934 };
935 assert_eq!(check(good.clone()), None);
936 let invalid = Some("delegation_signature_invalid".to_string());
937 for expires in [json!("2026-04-26T09:30:00Z"), Value::Null, json!(5)] {
939 let mut p = good.clone();
940 p["expires"] = expires.clone();
941 let mut unsigned = p.clone();
942 unsigned.as_object_mut().unwrap().remove("proofValue");
943 let input =
944 data_integrity::hash_data(&grant_body(&root, &leaf), unsigned.as_object().unwrap())
945 .unwrap();
946 let sig = crate::keys::Ed25519KeyPair::from_seed(&root.seed).sign(&input);
947 p["proofValue"] = json!(format!("z{}", bs58::encode(sig).into_string()));
948 assert_eq!(check(p), invalid, "expires {expires}");
949 }
950 let mut opts = base();
952 opts.created = "yesterday".into();
953 assert_eq!(check(eddsa_proof(&root, &leaf, opts)), invalid);
954 let mut p = good.clone();
956 p["cryptosuite"] = json!("some-unregistered-suite-2030");
957 assert_eq!(check(p), invalid);
958 let mut p = good.clone();
959 p.as_object_mut().unwrap().remove("proofValue");
960 assert_eq!(check(p), invalid);
961 assert_eq!(check(json!([good.clone(), 7])), invalid);
962 assert_eq!(check(json!([good.clone()])), invalid);
964 assert_eq!(check(json!([good.clone(), good.clone()])), invalid);
965 }
966
967 #[test]
968 fn grant_issuer_is_a_did_string_or_id() {
969 let (root, leaf) = (party(7), party(8));
970 let roots = vec![root.did.clone()];
971 let mut body = grant_body(&root, &leaf);
972 body["issuer"] = json!([root.did.clone()]);
973 let grant = data_integrity::sign(
974 &body,
975 &root.seed,
976 &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
977 )
978 .unwrap();
979 let cred = leaf_credential(
980 &leaf,
981 json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
982 );
983 assert_eq!(
984 verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&roots)),
985 Some("delegation_link_issuer_mismatch".into())
986 );
987 }
988
989 #[test]
990 fn a_known_mldsa_key_checks_the_grant_member() {
991 let (root, leaf) = (party(9), party(10));
992 let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
993 let body = grant_body(&root, &leaf);
994 let dual = hybrid::sign_dual(
995 &body,
996 &root.seed,
997 &ml,
998 &vm(&root),
999 &format!("{}#mldsa", root.did),
1000 "2026-04-26T09:00:00Z",
1001 )
1002 .unwrap();
1003 let roots = vec![root.did.clone()];
1004 let mut keys = BTreeMap::new();
1005 keys.insert(root.did.clone(), ml.public_key().to_vec());
1006 let known = ChainOptions {
1007 trusted_roots: Some(&roots),
1008 mldsa_keys: Some(&keys),
1009 ..Default::default()
1010 };
1011 let link = |g: &Value| {
1012 leaf_credential(
1013 &leaf,
1014 json!({"issuer": root.did, "subject": leaf.did, "parentCredential": g}),
1015 )
1016 };
1017 assert_eq!(
1018 verify_delegation_chain_with(&link(&dual), NOW, 30, &known),
1019 None
1020 );
1021 let mut broken = dual.clone();
1023 broken["proof"][1]["proofValue"] = dual["proof"][0]["proofValue"].clone();
1024 assert_eq!(
1025 verify_delegation_chain_with(&link(&broken), NOW, 30, &known),
1026 Some("delegation_signature_invalid".into())
1027 );
1028 #[allow(deprecated)]
1030 let composite =
1031 hybrid::sign_composite(&body, &root.seed, &ml, &vm(&root), "2026-04-26T09:00:00Z")
1032 .unwrap();
1033 assert_eq!(
1034 verify_delegation_chain_with(&link(&composite), NOW, 30, &known),
1035 None
1036 );
1037 assert_eq!(
1038 verify_delegation_chain_with(&link(&composite), NOW, 30, &opts_with(&roots)),
1039 Some("delegation_signature_invalid".into())
1040 );
1041 }
1042
1043 #[test]
1044 fn a_did_key_grant_issuer_keeps_its_own_key() {
1045 let (root, leaf, other) = (party(11), party(12), party(13));
1046 let grant = data_integrity::sign(
1047 &grant_body(&root, &leaf),
1048 &root.seed,
1049 &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
1050 )
1051 .unwrap();
1052 let cred = leaf_credential(
1053 &leaf,
1054 json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
1055 );
1056 let roots = vec![root.did.clone()];
1057 let mut keys = BTreeMap::new();
1058 keys.insert(
1059 root.did.clone(),
1060 crate::keys::Ed25519KeyPair::from_seed(&other.seed)
1061 .public_key()
1062 .to_vec(),
1063 );
1064 let pinned = ChainOptions {
1065 trusted_roots: Some(&roots),
1066 grant_keys: Some(&keys),
1067 ..Default::default()
1068 };
1069 assert_eq!(
1070 verify_delegation_chain_with(&cred, NOW, 30, &pinned),
1071 Some("delegation_issuer_key_unresolved".into())
1072 );
1073 }
1074
1075 #[test]
1076 fn link_fields_are_checked_before_any_key() {
1077 let link = |iss: &str, sub: &str| {
1080 json!({"issuer": iss, "subject": sub,
1081 "parentCredential": {"issuer": iss, "proof": {"type": "DataIntegrityProof"}}})
1082 };
1083 let cred = |chain: Value| json!({"issuer": "did:web:c", "credentialSubject": {"delegationChain": chain}});
1084 let roots = vec!["did:web:root".to_string()];
1085 assert_eq!(
1086 verify_delegation_chain_with(
1087 &cred(json!([link("did:web:other", "did:web:c")])),
1088 NOW,
1089 30,
1090 &opts_with(&roots)
1091 ),
1092 Some("untrusted_principal".into())
1093 );
1094 assert_eq!(
1095 verify_delegation_chain_with(
1096 &cred(json!([
1097 link("did:web:root", "did:web:a"),
1098 link("did:web:b", "did:web:c")
1099 ])),
1100 NOW,
1101 30,
1102 &opts_with(&roots)
1103 ),
1104 Some("delegation_subject_issuer_mismatch".into())
1105 );
1106 assert_eq!(
1108 verify_delegation_chain_with(
1109 &cred(json!([link("did:web:root", "did:web:other")])),
1110 NOW,
1111 30,
1112 &opts_with(&roots)
1113 ),
1114 Some("delegation_subject_issuer_mismatch".into())
1115 );
1116 assert_eq!(
1119 verify_delegation_chain_with(
1120 &cred(json!([link("did:web:root", "did:web:c")])),
1121 NOW,
1122 30,
1123 &opts_with(&roots)
1124 ),
1125 Some("delegation_signature_invalid".into())
1126 );
1127 for chain in [Value::Null, json!({}), json!(""), json!(0), json!(false)] {
1129 assert_eq!(
1130 verify_delegation_chain_with(&cred(chain.clone()), NOW, 30, &opts_with(&roots)),
1131 Some("malformed_delegation".into()),
1132 "{chain}"
1133 );
1134 }
1135 let big =
1137 cred(json!([{"issuer": "x", "subject": "y", "pad": "a".repeat(MAX_CHAIN_BYTES)}]));
1138 assert_eq!(
1139 verify_delegation_chain_with(&big, NOW, 30, &ChainOptions::default()),
1140 Some(REASON_BUDGET_EXCEEDED.into())
1141 );
1142 }
1143
1144 #[test]
1145 fn grant_binding_is_checked_before_any_key() {
1146 let grant = |iss: &str, sub: &str, extra: Value| {
1149 let mut g = json!({"issuer": iss, "proof": {"type": "DataIntegrityProof"},
1150 "credentialSubject": {"intent": {"delegatee": sub}}});
1151 for (k, v) in extra.as_object().unwrap() {
1152 g["credentialSubject"][k] = v.clone();
1153 }
1154 g
1155 };
1156 let link = |g: &Value| {
1157 json!({"issuer": g["issuer"], "subject": g["credentialSubject"]["intent"]["delegatee"],
1158 "parentCredential": g})
1159 };
1160 let cred = |chain: Vec<Value>| json!({"issuer": "did:web:c", "credentialSubject": {"delegationChain": chain}});
1161 let roots = vec!["did:web:root".to_string()];
1162 let check = |chain: Vec<Value>| {
1163 verify_delegation_chain_with(&cred(chain), NOW, 30, &opts_with(&roots))
1164 };
1165 let g1 = grant("did:web:root", "did:web:a", json!({}));
1166 let digest = grant_chain::grant_digest(&g1).unwrap();
1167 let bound = grant(
1168 "did:web:a",
1169 "did:web:c",
1170 json!({ "parentGrantDigest": digest }),
1171 );
1172 let unbound = grant("did:web:a", "did:web:c", json!({}));
1173 assert_eq!(
1175 check(vec![link(&g1), link(&bound)]),
1176 Some("delegation_signature_invalid".into())
1177 );
1178 assert_eq!(
1179 check(vec![link(&g1), link(&unbound)]),
1180 Some("delegation_parent_mismatch".into())
1181 );
1182 let cut = grant(
1184 "did:web:root",
1185 "did:web:c",
1186 json!({ "parentGrantDigest": "uEiAAAA" }),
1187 );
1188 assert_eq!(
1189 check(vec![link(&cut)]),
1190 Some("delegation_parent_mismatch".into())
1191 );
1192 for extra in [
1194 json!({ "parentGrantDigest": null }),
1195 json!({ "delegationChain": null }),
1196 json!({ "parentGrantDigest": digest, "delegationChain": [link(&g1)] }),
1197 ] {
1198 let g2 = grant("did:web:a", "did:web:c", extra.clone());
1199 assert_eq!(
1200 check(vec![link(&g1), link(&g2)]),
1201 Some("malformed_delegation".into()),
1202 "{extra}"
1203 );
1204 }
1205 assert_eq!(
1207 verify_delegation_chain_with(
1208 &cred(vec![link(&g1), link(&unbound)]),
1209 NOW,
1210 30,
1211 &opts_with(&["did:web:other".to_string()])
1212 ),
1213 Some("untrusted_principal".into())
1214 );
1215 for missing in [None, Some(json!("grant")), Some(Value::Null)] {
1218 let mut first = link(&g1);
1219 match &missing {
1220 None => {
1221 first.as_object_mut().unwrap().remove("parentCredential");
1222 }
1223 Some(v) => first["parentCredential"] = v.clone(),
1224 }
1225 assert_eq!(
1226 check(vec![first, link(&unbound)]),
1227 Some("delegation_link_unsigned".into()),
1228 "{missing:?}"
1229 );
1230 }
1231 }
1232}