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::hybrid;
18use crate::multikey;
19use crate::time::{check_clock_skew, parse_protocol_time_ns, window_state_ns, WindowState};
20
21#[derive(Debug, Clone)]
23pub struct DelegationLinkInput {
24 pub issuer: String,
25 pub subject: String,
26 pub intent: Value,
27 pub valid_from: Option<String>,
28 pub valid_until: Option<String>,
29 pub parent_proof_value: Option<String>,
30}
31
32pub fn build_delegation_link(input: &DelegationLinkInput) -> Value {
34 let mut link = Map::new();
35 link.insert("issuer".into(), json!(input.issuer));
36 link.insert("subject".into(), json!(input.subject));
37 link.insert("intent".into(), input.intent.clone());
38 if let Some(vf) = &input.valid_from {
39 link.insert("validFrom".into(), json!(vf));
40 }
41 if let Some(vu) = &input.valid_until {
42 link.insert("validUntil".into(), json!(vu));
43 }
44 if let Some(pp) = &input.parent_proof_value {
45 link.insert("parentProofValue".into(), json!(pp));
46 }
47 Value::Object(link)
48}
49
50fn link_bound(obj: &Map<String, Value>, key: &str) -> Result<Option<i128>> {
53 match obj.get(key) {
54 None => Ok(None),
55 Some(Value::String(s)) => Ok(Some(parse_protocol_time_ns(s)?)),
56 Some(_) => Err(CoreError::Json(format!(
57 "delegation link {key} must be a time string"
58 ))),
59 }
60}
61
62fn link_window(link: &Value) -> Result<(Option<i128>, Option<i128>)> {
63 let obj = link
64 .as_object()
65 .ok_or_else(|| CoreError::Json("delegation link must be an object".into()))?;
66 Ok((
67 link_bound(obj, "validFrom")?,
68 link_bound(obj, "validUntil")?,
69 ))
70}
71
72pub fn verify_chain_time_bound(
80 chain: &[Value],
81 now_iso: &str,
82 clock_skew_seconds: i64,
83) -> Result<bool> {
84 let skew = check_clock_skew(clock_skew_seconds)?;
85 let now = parse_protocol_time_ns(now_iso)?;
86 let mut eff_from: Option<i128> = None;
87 let mut eff_until: Option<i128> = None;
88
89 for link in chain {
90 let (vf, vu) = link_window(link)?;
91 if let (Some(f), Some(u)) = (vf, vu) {
92 if f > u {
93 return Ok(false); }
95 }
96 if let (Some(f), Some(ef)) = (vf, eff_from) {
97 if f < ef {
98 return Ok(false); }
100 }
101 if let (Some(u), Some(eu)) = (vu, eff_until) {
102 if u > eu {
103 return Ok(false); }
105 }
106 if let Some(f) = vf {
107 eff_from = Some(eff_from.map_or(f, |cur| cur.max(f)));
108 }
109 if let Some(u) = vu {
110 eff_until = Some(eff_until.map_or(u, |cur| cur.min(u)));
111 }
112 }
113 Ok(window_state_ns(now, eff_from, eff_until, skew) == WindowState::Ok)
114}
115
116pub fn capability_view(credential: &Value, include_time: bool) -> Value {
129 let intent = credential
130 .get("credentialSubject")
131 .and_then(|s| s.get("intent"))
132 .and_then(|i| i.as_object())
133 .cloned()
134 .unwrap_or_default();
135 let mut view = Map::new();
136 view.insert(
137 "issuer".into(),
138 issuer_did(credential)
139 .map(Value::String)
140 .unwrap_or(Value::Null),
141 );
142 view.insert(
143 "subject".into(),
144 intent.get("delegatee").cloned().unwrap_or(Value::Null),
145 );
146 let mut dims = Map::new();
147 for k in ["action", "target", "resource", "amount"] {
148 if let Some(v) = intent.get(k) {
149 dims.insert(k.into(), v.clone());
150 }
151 }
152 view.insert("intent".into(), Value::Object(dims));
153 if include_time {
154 for k in ["validFrom", "validUntil"] {
155 if let Some(v) = credential.get(k) {
156 view.insert(k.into(), v.clone());
157 }
158 }
159 }
160 for k in ["rate", "policy"] {
161 if let Some(v) = intent.get(k) {
162 view.insert(k.into(), v.clone());
163 }
164 }
165 Value::Object(view)
166}
167
168fn issuer_did(credential: &Value) -> Option<String> {
171 crate::credentials::issuer_did(credential).map(String::from)
172}
173
174fn resolve_chain_key(did: &str, root_keys: &BTreeMap<String, Vec<u8>>) -> Option<Vec<u8>> {
179 let from_did = match did.strip_prefix("did:key:") {
180 Some(mk) => {
181 let decoded = multikey::decode(mk).ok()?;
182 if decoded.algorithm != "Ed25519" {
183 return None;
184 }
185 Some(decoded.raw_key)
186 }
187 None => None,
188 };
189 match (root_keys.get(did), from_did) {
190 (Some(k), Some(d)) => (k == &d).then_some(d),
191 (Some(k), None) => Some(k.clone()),
192 (None, d) => d,
193 }
194}
195
196fn parent_proof_binding_value(grant: &Value) -> String {
199 match grant.get("proof") {
200 Some(Value::Array(items)) => {
201 for p in items {
202 if p.get("cryptosuite").and_then(|v| v.as_str())
203 == Some(data_integrity::CRYPTOSUITE_ID)
204 {
205 return p
206 .get("proofValue")
207 .and_then(|v| v.as_str())
208 .unwrap_or("")
209 .to_string();
210 }
211 }
212 for p in items {
213 if let Some(v) = p.get("proofValue").and_then(|v| v.as_str()) {
214 if !v.is_empty() {
215 return v.to_string();
216 }
217 }
218 }
219 String::new()
220 }
221 Some(Value::Object(p)) => p
222 .get("proofValue")
223 .and_then(|v| v.as_str())
224 .unwrap_or("")
225 .to_string(),
226 _ => String::new(),
227 }
228}
229
230fn verify_grant_proof(
242 grant: &Value,
243 issuer: &str,
244 key: &[u8],
245 mldsa_key: Option<&[u8]>,
246 require_pq: bool,
247 now: i128,
248 skew: i128,
249) -> bool {
250 let Some(proof) = grant.get("proof") else {
251 return false;
252 };
253 let members: Vec<&Value> = match proof {
254 Value::Array(items) => items.iter().collect(),
255 other => vec![other],
256 };
257 if members.is_empty()
258 || !members
259 .iter()
260 .all(|m| crate::credentials::proof_member_ok(m, issuer, now, skew))
261 {
262 return false;
263 }
264 let suite = |p: &Value| {
265 p.get("cryptosuite")
266 .and_then(|v| v.as_str())
267 .unwrap_or_default()
268 .to_string()
269 };
270 match proof {
271 Value::Object(_) => match suite(proof).as_str() {
272 data_integrity::CRYPTOSUITE_ID => {
273 !require_pq && matches!(data_integrity::verify_proof(grant, key), Ok(true))
274 }
275 hybrid::HYBRID_COMPOSITE_CRYPTOSUITE_ID => match mldsa_key {
276 Some(ml) => matches!(hybrid::verify_composite(grant, key, ml), Ok(true)),
277 None => false,
278 },
279 _ => false,
280 },
281 Value::Array(items) => {
282 let mut suites: Vec<String> = items
283 .iter()
284 .map(|p| {
285 let s = suite(p);
286 if s == hybrid::MLDSA44_LEGACY_CRYPTOSUITE_ID {
287 hybrid::MLDSA44_CRYPTOSUITE_ID.to_string()
288 } else {
289 s
290 }
291 })
292 .collect();
293 suites.sort();
294 if suites != [hybrid::EDDSA_CRYPTOSUITE_ID, hybrid::MLDSA44_CRYPTOSUITE_ID] {
295 return false;
296 }
297 match mldsa_key {
298 Some(ml) => matches!(hybrid::verify_dual(grant, key, ml), Ok(true)),
299 None if require_pq => false,
300 None => {
301 let Some(ed) = items
303 .iter()
304 .find(|p| suite(p) == data_integrity::CRYPTOSUITE_ID)
305 else {
306 return false;
307 };
308 let mut single = grant.clone();
309 single["proof"] = (*ed).clone();
310 matches!(data_integrity::verify_proof(&single, key), Ok(true))
311 }
312 }
313 }
314 _ => false,
315 }
316}
317
318fn grant_proof_well_formed(grant: &Value, issuer: &str, now: i128, skew: i128) -> bool {
323 let Some(proof) = grant.get("proof") else {
324 return false;
325 };
326 let members: Vec<&Value> = match proof {
327 Value::Array(items) => items.iter().collect(),
328 other => vec![other],
329 };
330 if members.is_empty()
331 || !members
332 .iter()
333 .all(|m| crate::credentials::proof_member_ok(m, issuer, now, skew))
334 {
335 return false;
336 }
337 let suite = |p: &Value| {
338 let s = p
339 .get("cryptosuite")
340 .and_then(|v| v.as_str())
341 .unwrap_or_default();
342 if s == hybrid::MLDSA44_LEGACY_CRYPTOSUITE_ID {
343 hybrid::MLDSA44_CRYPTOSUITE_ID.to_string()
344 } else {
345 s.to_string()
346 }
347 };
348 match proof {
349 Value::Object(_) => matches!(
350 suite(proof).as_str(),
351 data_integrity::CRYPTOSUITE_ID | hybrid::HYBRID_COMPOSITE_CRYPTOSUITE_ID
352 ),
353 Value::Array(items) => {
354 let mut suites: Vec<String> = items.iter().map(suite).collect();
355 suites.sort();
356 suites == [hybrid::EDDSA_CRYPTOSUITE_ID, hybrid::MLDSA44_CRYPTOSUITE_ID]
357 }
358 _ => false,
359 }
360}
361
362fn first_64(s: &str) -> String {
363 s.chars().take(64).collect()
364}
365
366pub const REASON_TRUSTED_ROOTS_REQUIRED: &str =
369 "the chain's starting point is not trusted: pass trusted roots";
370
371pub const REASON_BUDGET_EXCEEDED: &str = "verifier_budget_exceeded";
374
375pub const MAX_CHAIN_BYTES: usize = attenuation::MAX_CHAIN_BYTES;
380
381pub fn root_did(root: &str) -> Option<String> {
387 crate::did_web::normalize_root(root).ok()
388}
389
390pub fn root_matches(root: &str, issuer: &str) -> bool {
393 root_did(root).as_deref() == Some(issuer)
394}
395
396#[derive(Debug, Clone, Copy, Default)]
398pub struct ChainOptions<'a> {
399 pub trusted_roots: Option<&'a [String]>,
405 pub grant_keys: Option<&'a BTreeMap<String, Vec<u8>>>,
408 pub mldsa_keys: Option<&'a BTreeMap<String, Vec<u8>>>,
412 pub require_pq: bool,
415 pub max_depth: Option<usize>,
418}
419
420pub fn verify_delegation_chain(
429 credential: &Value,
430 now_iso: &str,
431 clock_skew_seconds: i64,
432 root_keys: &BTreeMap<String, Vec<u8>>,
433 root_dids: Option<&[String]>,
434) -> Option<String> {
435 let opts = ChainOptions {
436 trusted_roots: root_dids,
437 grant_keys: Some(root_keys),
438 ..Default::default()
439 };
440 verify_delegation_chain_with(credential, now_iso, clock_skew_seconds, &opts)
441}
442
443pub fn verify_delegation_chain_with(
458 credential: &Value,
459 now_iso: &str,
460 clock_skew_seconds: i64,
461 opts: &ChainOptions,
462) -> Option<String> {
463 let malformed = || Some("malformed_delegation".to_string());
464 if !credential.is_object() {
465 return malformed();
466 }
467 let chain_value = match credential
468 .get("credentialSubject")
469 .and_then(|s| s.get("delegationChain"))
470 {
471 None => return None,
472 Some(Value::Array(a)) if a.is_empty() => return None,
473 Some(v @ Value::Array(_)) => v,
474 Some(_) => return malformed(),
476 };
477 let chain = chain_value.as_array().expect("checked above");
478 match attenuation::chain_budget_exceeded(chain_value, opts.max_depth) {
479 Ok(None) => {}
480 Ok(Some(_)) => return Some(REASON_BUDGET_EXCEEDED.into()),
481 Err(_) => return malformed(),
482 }
483 let Some(roots) = opts.trusted_roots else {
484 return Some(REASON_TRUSTED_ROOTS_REQUIRED.into());
485 };
486 let Ok(skew) = check_clock_skew(clock_skew_seconds) else {
487 return malformed();
488 };
489 let Ok(now) = parse_protocol_time_ns(now_iso) else {
490 return malformed();
491 };
492
493 for link in chain {
495 let shape_ok = link.get("issuer").is_some_and(|v| v.is_string())
496 && link.get("subject").is_some_and(|v| v.is_string());
497 if !shape_ok {
498 return malformed();
499 }
500 }
501 for i in 1..chain.len() {
502 if chain[i - 1].get("subject") != chain[i].get("issuer") {
503 return Some("delegation_subject_issuer_mismatch".into());
504 }
505 }
506 let last_subject = chain[chain.len() - 1]
507 .get("subject")
508 .and_then(|v| v.as_str());
509 if last_subject.map(String::from) != issuer_did(credential) {
510 return Some("delegation_subject_issuer_mismatch".into());
511 }
512 let root = chain[0]
513 .get("issuer")
514 .and_then(|v| v.as_str())
515 .unwrap_or("");
516 if !roots.iter().any(|d| root_matches(d, root)) {
517 return Some("untrusted_principal".into());
518 }
519
520 let empty = BTreeMap::new();
521 let grant_keys = opts.grant_keys.unwrap_or(&empty);
522
523 let mut grants: Vec<&Value> = Vec::with_capacity(chain.len());
524 for link in chain {
525 let link_issuer = link["issuer"].as_str().unwrap_or_default();
526 let link_subject = link["subject"].as_str().unwrap_or_default();
527 let Some(grant) = link.get("parentCredential").filter(|g| g.is_object()) else {
528 return Some("delegation_link_unsigned".into());
529 };
530 if !matches!(
531 grant.get("proof"),
532 Some(Value::Object(_)) | Some(Value::Array(_))
533 ) {
534 return Some("delegation_link_unsigned".into());
535 }
536 let grant_issuer = issuer_did(grant);
537 if grant_issuer.as_deref() != Some(link_issuer) {
538 return Some("delegation_link_issuer_mismatch".into());
539 }
540 if !grant_proof_well_formed(grant, link_issuer, now, skew) {
543 return Some("delegation_signature_invalid".into());
544 }
545 let Some(key) = resolve_chain_key(link_issuer, grant_keys) else {
546 return Some("delegation_issuer_key_unresolved".into());
547 };
548 let mldsa_key = opts
551 .mldsa_keys
552 .and_then(|m| m.get(link_issuer))
553 .map(|k| k.as_slice());
554 if !verify_grant_proof(
555 grant,
556 link_issuer,
557 &key,
558 mldsa_key,
559 opts.require_pq,
560 now,
561 skew,
562 ) {
563 return Some("delegation_signature_invalid".into());
564 }
565 if let Some(bound) = link.get("parentProofValue") {
566 let Some(bound) = bound.as_str() else {
568 return malformed();
569 };
570 if bound != first_64(&parent_proof_binding_value(grant)) {
571 return Some("delegation_link_tampered".into());
572 }
573 }
574 let delegatee = grant
575 .get("credentialSubject")
576 .and_then(|s| s.get("intent"))
577 .and_then(|i| i.get("delegatee"))
578 .and_then(|d| d.as_str())
579 .filter(|d| !d.is_empty());
580 let Some(delegatee) = delegatee else {
581 return Some("delegation_no_delegatee".into());
582 };
583 if delegatee != link_subject {
584 return Some("delegation_subject_mismatch".into());
585 }
586 let window = (
587 grant
588 .get("validFrom")
589 .and_then(|v| v.as_str())
590 .map(parse_protocol_time_ns),
591 grant
592 .get("validUntil")
593 .and_then(|v| v.as_str())
594 .map(parse_protocol_time_ns),
595 );
596 let (Some(Ok(from)), Some(Ok(until))) = window else {
597 return malformed();
598 };
599 match window_state_ns(now, Some(from), Some(until), skew) {
600 WindowState::Ok => {}
601 WindowState::Expired => return Some("delegation_expired".into()),
602 WindowState::NotYetValid => return Some("delegation_not_yet_valid".into()),
603 WindowState::Inverted => return malformed(),
604 }
605 grants.push(grant);
606 }
607
608 let last_subject = chain[chain.len() - 1]
609 .get("subject")
610 .and_then(|v| v.as_str());
611 if last_subject.map(String::from) != issuer_did(credential) {
612 return Some("delegation_subject_issuer_mismatch".into());
613 }
614
615 let mut views: Vec<Value> = grants.iter().map(|g| capability_view(g, true)).collect();
616 views.push(capability_view(credential, true));
617 if let Err(dim) = attenuation::first_broader_step(&views) {
618 return Some(format!("scope_exceeds_parent:{}", dim.as_str()));
619 }
620 None
621}
622
623#[cfg(test)]
624mod tests {
625 use super::*;
626
627 fn link(vf: &str, vu: &str) -> Value {
628 build_delegation_link(&DelegationLinkInput {
629 issuer: "did:web:a".into(),
630 subject: "did:web:b".into(),
631 intent: json!({"action":"read","target":"t","resource":"https://x/y"}),
632 valid_from: Some(vf.into()),
633 valid_until: Some(vu.into()),
634 parent_proof_value: None,
635 })
636 }
637
638 #[test]
639 fn nested_windows_pass() {
640 let chain = vec![
641 link("2026-04-26T09:00:00Z", "2026-04-26T12:00:00Z"),
642 link("2026-04-26T10:00:00Z", "2026-04-26T11:00:00Z"),
643 ];
644 assert!(verify_chain_time_bound(&chain, "2026-04-26T10:30:00Z", 30).unwrap());
645 }
646
647 #[test]
648 fn child_wider_than_parent_fails() {
649 let chain = vec![
650 link("2026-04-26T10:00:00Z", "2026-04-26T11:00:00Z"),
651 link("2026-04-26T09:00:00Z", "2026-04-26T12:00:00Z"), ];
653 assert!(!verify_chain_time_bound(&chain, "2026-04-26T10:30:00Z", 30).unwrap());
654 }
655
656 #[test]
657 fn now_outside_leaf_window_fails() {
658 let chain = vec![link("2026-04-26T10:00:00Z", "2026-04-26T11:00:00Z")];
659 assert!(!verify_chain_time_bound(&chain, "2026-04-26T12:00:00Z", 30).unwrap());
660 }
661
662 #[test]
663 fn a_window_less_middle_link_stays_bounded_by_the_root() {
664 let root = json!({"issuer":"did:web:root","subject":"did:web:a","intent":{},
665 "validFrom":"2026-04-26T09:00:00Z","validUntil":"2026-04-26T11:00:00Z"});
666 let mid = json!({"issuer":"did:web:a","subject":"did:web:b","intent":{}});
667 let leaf = json!({"issuer":"did:web:b","subject":"did:web:c","intent":{},
668 "validFrom":"2026-04-26T09:00:00Z","validUntil":"2099-01-01T00:00:00Z"});
669 let chain = vec![root.clone(), mid, leaf];
670 assert!(!verify_chain_time_bound(&chain, "2030-01-01T00:00:00Z", 30).unwrap());
671 assert!(!verify_chain_time_bound(&chain, "2026-04-26T10:00:00Z", 30).unwrap());
672 let bad = json!({"issuer":"did:web:a","subject":"did:web:b","intent":{},
674 "validFrom":"2026-04-26T09:00:00Z","validUntil":0});
675 assert!(verify_chain_time_bound(&[root.clone(), bad], "2026-04-26T10:00:00Z", 30).is_err());
676 let inv = link("2026-04-26T11:00:00Z", "2026-04-26T10:00:00Z");
678 assert!(!verify_chain_time_bound(&[inv], "2026-04-26T10:30:00Z", 120).unwrap());
679 assert!(verify_chain_time_bound(&[root], "2026-04-26T10:00:00Z", 121).is_err());
680 }
681
682 struct Party {
685 seed: [u8; 32],
686 did: String,
687 }
688
689 fn party(n: u8) -> Party {
690 let seed = [n; 32];
691 let did = crate::keys::Ed25519KeyPair::from_seed(&seed).did_key();
692 Party { seed, did }
693 }
694
695 fn vm(p: &Party) -> String {
696 format!("{}#{}", p.did, p.did.trim_start_matches("did:key:"))
697 }
698
699 fn grant_body(from: &Party, to: &Party) -> Value {
700 json!({
701 "@context": ["https://www.w3.org/ns/credentials/v2"],
702 "type": ["VerifiableCredential", "VouchCredential"],
703 "issuer": from.did,
704 "validFrom": "2026-04-26T09:00:00Z",
705 "validUntil": "2026-04-26T12:00:00Z",
706 "credentialSubject": {"id": from.did, "vouchVersion": "1.0", "intent": {
707 "action": "read", "target": "t", "resource": "https://x/a", "delegatee": to.did}}
708 })
709 }
710
711 fn leaf_credential(leaf: &Party, link: Value) -> Value {
712 json!({
713 "@context": ["https://www.w3.org/ns/credentials/v2"],
714 "type": ["VerifiableCredential", "VouchCredential"],
715 "issuer": leaf.did,
716 "validFrom": "2026-04-26T10:00:00Z",
717 "validUntil": "2026-04-26T10:05:00Z",
718 "credentialSubject": {"id": leaf.did, "vouchVersion": "1.0",
719 "intent": {"action": "read", "target": "t", "resource": "https://x/a/b"},
720 "delegationChain": [link]}
721 })
722 }
723
724 const NOW: &str = "2026-04-26T10:01:00Z";
725
726 fn opts_with<'a>(roots: &'a [String]) -> ChainOptions<'a> {
727 ChainOptions {
728 trusted_roots: Some(roots),
729 ..Default::default()
730 }
731 }
732
733 #[test]
734 fn signed_chain_needs_roots_and_respects_the_size_guard() {
735 let (root, leaf) = (party(1), party(2));
736 let grant = data_integrity::sign(
737 &grant_body(&root, &leaf),
738 &root.seed,
739 &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
740 )
741 .unwrap();
742 let link = json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant});
743 let cred = leaf_credential(&leaf, link.clone());
744 let roots = vec![root.did.clone()];
745 assert_eq!(
746 verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&roots)),
747 None
748 );
749 assert_eq!(
750 verify_delegation_chain_with(&cred, NOW, 30, &ChainOptions::default()),
751 Some(REASON_TRUSTED_ROOTS_REQUIRED.into())
752 );
753 assert_eq!(
755 verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&[])),
756 Some("untrusted_principal".into())
757 );
758 let bare = vec![root.did.trim_start_matches("did:key:").to_string()];
760 assert_eq!(
761 verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&bare)),
762 Some("untrusted_principal".into())
763 );
764 assert!(root_matches("yourcompany.com", "did:web:yourcompany.com"));
765 assert!(!root_matches(
766 "yourcompany.com",
767 "did:web:yourcompany.com.evil"
768 ));
769 assert!(!root_matches("yourcompany.com", "did:key:yourcompany.com"));
770 assert_eq!(
771 root_did("yourcompany.com").as_deref(),
772 Some("did:web:yourcompany.com")
773 );
774 assert_eq!(
775 root_did("yourcompany.com:8443").as_deref(),
776 Some("did:web:yourcompany.com%3A8443")
777 );
778 assert!(root_did("127.0.0.1").is_none());
779 let other = vec!["did:web:someone-else".to_string()];
780 assert_eq!(
781 verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&other)),
782 Some("untrusted_principal".into())
783 );
784 let budget = ChainOptions {
786 max_depth: Some(0),
787 ..opts_with(&roots)
788 };
789 assert_eq!(
790 verify_delegation_chain_with(&cred, NOW, 30, &budget),
791 Some(REASON_BUDGET_EXCEEDED.into())
792 );
793 let mut big = link;
795 big["note"] = json!("a".repeat(MAX_CHAIN_BYTES));
796 let cred = leaf_credential(&leaf, big);
797 assert_eq!(
798 verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&roots)),
799 Some(REASON_BUDGET_EXCEEDED.into())
800 );
801 }
802
803 #[test]
804 fn post_quantum_profile_requires_a_valid_dual_proof_on_every_grant() {
805 let (root, leaf) = (party(3), party(4));
806 let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
807 let body = grant_body(&root, &leaf);
808 let dual = hybrid::sign_dual(
809 &body,
810 &root.seed,
811 &ml,
812 &vm(&root),
813 &format!("{}#mldsa", root.did),
814 "2026-04-26T09:00:00Z",
815 )
816 .unwrap();
817 let single = data_integrity::sign(
818 &body,
819 &root.seed,
820 &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
821 )
822 .unwrap();
823 let roots = vec![root.did.clone()];
824 let mut mldsa_keys = BTreeMap::new();
825 mldsa_keys.insert(root.did.clone(), ml.public_key().to_vec());
826 let pq = ChainOptions {
827 trusted_roots: Some(&roots),
828 mldsa_keys: Some(&mldsa_keys),
829 require_pq: true,
830 ..Default::default()
831 };
832 let chain_of = |grant: &Value| {
833 leaf_credential(
834 &leaf,
835 json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
836 )
837 };
838 assert_eq!(
839 verify_delegation_chain_with(&chain_of(&dual), NOW, 30, &pq),
840 None
841 );
842 assert_eq!(
844 verify_delegation_chain_with(&chain_of(&single), NOW, 30, &pq),
845 Some("delegation_signature_invalid".into())
846 );
847 let mut broken = dual.clone();
849 broken["proof"][1]["proofValue"] = dual["proof"][0]["proofValue"].clone();
850 assert_eq!(
851 verify_delegation_chain_with(&chain_of(&broken), NOW, 30, &pq),
852 Some("delegation_signature_invalid".into())
853 );
854 let none = ChainOptions {
856 mldsa_keys: None,
857 ..pq
858 };
859 assert_eq!(
860 verify_delegation_chain_with(&chain_of(&dual), NOW, 30, &none),
861 Some("delegation_signature_invalid".into())
862 );
863 assert_eq!(
865 verify_delegation_chain_with(&chain_of(&dual), NOW, 30, &opts_with(&roots)),
866 None
867 );
868 let mut foreign = dual.clone();
870 foreign["proof"][1]["verificationMethod"] = json!("did:web:someone-else#k");
871 assert_eq!(
872 verify_delegation_chain_with(&chain_of(&foreign), NOW, 30, &opts_with(&roots)),
873 Some("delegation_signature_invalid".into())
874 );
875 }
876
877 fn chain_with_proof(root: &Party, leaf: &Party, proof: Value) -> Value {
879 let mut grant = grant_body(root, leaf);
880 grant["proof"] = proof;
881 leaf_credential(
882 leaf,
883 json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
884 )
885 }
886
887 fn eddsa_proof(root: &Party, leaf: &Party, opts: data_integrity::BuildProofOptions) -> Value {
888 data_integrity::build_proof(&grant_body(root, leaf), &root.seed, &opts).unwrap()
889 }
890
891 #[test]
892 fn grant_proofs_follow_the_top_level_rules() {
893 let (root, leaf) = (party(5), party(6));
894 let roots = vec![root.did.clone()];
895 let o = opts_with(&roots);
896 let base = || data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z");
897 let good = eddsa_proof(&root, &leaf, base());
898 let check = |proof: Value| {
899 verify_delegation_chain_with(&chain_with_proof(&root, &leaf, proof), NOW, 30, &o)
900 };
901 assert_eq!(check(good.clone()), None);
902 let invalid = Some("delegation_signature_invalid".to_string());
903 for expires in [json!("2026-04-26T09:30:00Z"), Value::Null, json!(5)] {
905 let mut p = good.clone();
906 p["expires"] = expires.clone();
907 let mut unsigned = p.clone();
908 unsigned.as_object_mut().unwrap().remove("proofValue");
909 let input =
910 data_integrity::hash_data(&grant_body(&root, &leaf), unsigned.as_object().unwrap())
911 .unwrap();
912 let sig = crate::keys::Ed25519KeyPair::from_seed(&root.seed).sign(&input);
913 p["proofValue"] = json!(format!("z{}", bs58::encode(sig).into_string()));
914 assert_eq!(check(p), invalid, "expires {expires}");
915 }
916 let mut opts = base();
918 opts.created = "yesterday".into();
919 assert_eq!(check(eddsa_proof(&root, &leaf, opts)), invalid);
920 let mut p = good.clone();
922 p["cryptosuite"] = json!("some-unregistered-suite-2030");
923 assert_eq!(check(p), invalid);
924 let mut p = good.clone();
925 p.as_object_mut().unwrap().remove("proofValue");
926 assert_eq!(check(p), invalid);
927 assert_eq!(check(json!([good.clone(), 7])), invalid);
928 assert_eq!(check(json!([good.clone()])), invalid);
930 assert_eq!(check(json!([good.clone(), good.clone()])), invalid);
931 }
932
933 #[test]
934 fn grant_issuer_is_a_did_string_or_id() {
935 let (root, leaf) = (party(7), party(8));
936 let roots = vec![root.did.clone()];
937 let mut body = grant_body(&root, &leaf);
938 body["issuer"] = json!([root.did.clone()]);
939 let grant = data_integrity::sign(
940 &body,
941 &root.seed,
942 &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
943 )
944 .unwrap();
945 let cred = leaf_credential(
946 &leaf,
947 json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
948 );
949 assert_eq!(
950 verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&roots)),
951 Some("delegation_link_issuer_mismatch".into())
952 );
953 }
954
955 #[test]
956 fn a_known_mldsa_key_checks_the_grant_member() {
957 let (root, leaf) = (party(9), party(10));
958 let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
959 let body = grant_body(&root, &leaf);
960 let dual = hybrid::sign_dual(
961 &body,
962 &root.seed,
963 &ml,
964 &vm(&root),
965 &format!("{}#mldsa", root.did),
966 "2026-04-26T09:00:00Z",
967 )
968 .unwrap();
969 let roots = vec![root.did.clone()];
970 let mut keys = BTreeMap::new();
971 keys.insert(root.did.clone(), ml.public_key().to_vec());
972 let known = ChainOptions {
973 trusted_roots: Some(&roots),
974 mldsa_keys: Some(&keys),
975 ..Default::default()
976 };
977 let link = |g: &Value| {
978 leaf_credential(
979 &leaf,
980 json!({"issuer": root.did, "subject": leaf.did, "parentCredential": g}),
981 )
982 };
983 assert_eq!(
984 verify_delegation_chain_with(&link(&dual), NOW, 30, &known),
985 None
986 );
987 let mut broken = dual.clone();
989 broken["proof"][1]["proofValue"] = dual["proof"][0]["proofValue"].clone();
990 assert_eq!(
991 verify_delegation_chain_with(&link(&broken), NOW, 30, &known),
992 Some("delegation_signature_invalid".into())
993 );
994 #[allow(deprecated)]
996 let composite =
997 hybrid::sign_composite(&body, &root.seed, &ml, &vm(&root), "2026-04-26T09:00:00Z")
998 .unwrap();
999 assert_eq!(
1000 verify_delegation_chain_with(&link(&composite), NOW, 30, &known),
1001 None
1002 );
1003 assert_eq!(
1004 verify_delegation_chain_with(&link(&composite), NOW, 30, &opts_with(&roots)),
1005 Some("delegation_signature_invalid".into())
1006 );
1007 }
1008
1009 #[test]
1010 fn a_did_key_grant_issuer_keeps_its_own_key() {
1011 let (root, leaf, other) = (party(11), party(12), party(13));
1012 let grant = data_integrity::sign(
1013 &grant_body(&root, &leaf),
1014 &root.seed,
1015 &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
1016 )
1017 .unwrap();
1018 let cred = leaf_credential(
1019 &leaf,
1020 json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
1021 );
1022 let roots = vec![root.did.clone()];
1023 let mut keys = BTreeMap::new();
1024 keys.insert(
1025 root.did.clone(),
1026 crate::keys::Ed25519KeyPair::from_seed(&other.seed)
1027 .public_key()
1028 .to_vec(),
1029 );
1030 let pinned = ChainOptions {
1031 trusted_roots: Some(&roots),
1032 grant_keys: Some(&keys),
1033 ..Default::default()
1034 };
1035 assert_eq!(
1036 verify_delegation_chain_with(&cred, NOW, 30, &pinned),
1037 Some("delegation_issuer_key_unresolved".into())
1038 );
1039 }
1040
1041 #[test]
1042 fn link_fields_are_checked_before_any_key() {
1043 let link = |iss: &str, sub: &str| {
1046 json!({"issuer": iss, "subject": sub,
1047 "parentCredential": {"issuer": iss, "proof": {"type": "DataIntegrityProof"}}})
1048 };
1049 let cred = |chain: Value| json!({"issuer": "did:web:c", "credentialSubject": {"delegationChain": chain}});
1050 let roots = vec!["did:web:root".to_string()];
1051 assert_eq!(
1052 verify_delegation_chain_with(
1053 &cred(json!([link("did:web:other", "did:web:c")])),
1054 NOW,
1055 30,
1056 &opts_with(&roots)
1057 ),
1058 Some("untrusted_principal".into())
1059 );
1060 assert_eq!(
1061 verify_delegation_chain_with(
1062 &cred(json!([
1063 link("did:web:root", "did:web:a"),
1064 link("did:web:b", "did:web:c")
1065 ])),
1066 NOW,
1067 30,
1068 &opts_with(&roots)
1069 ),
1070 Some("delegation_subject_issuer_mismatch".into())
1071 );
1072 assert_eq!(
1074 verify_delegation_chain_with(
1075 &cred(json!([link("did:web:root", "did:web:other")])),
1076 NOW,
1077 30,
1078 &opts_with(&roots)
1079 ),
1080 Some("delegation_subject_issuer_mismatch".into())
1081 );
1082 assert_eq!(
1085 verify_delegation_chain_with(
1086 &cred(json!([link("did:web:root", "did:web:c")])),
1087 NOW,
1088 30,
1089 &opts_with(&roots)
1090 ),
1091 Some("delegation_signature_invalid".into())
1092 );
1093 for chain in [Value::Null, json!({}), json!(""), json!(0), json!(false)] {
1095 assert_eq!(
1096 verify_delegation_chain_with(&cred(chain.clone()), NOW, 30, &opts_with(&roots)),
1097 Some("malformed_delegation".into()),
1098 "{chain}"
1099 );
1100 }
1101 let big =
1103 cred(json!([{"issuer": "x", "subject": "y", "pad": "a".repeat(MAX_CHAIN_BYTES)}]));
1104 assert_eq!(
1105 verify_delegation_chain_with(&big, NOW, 30, &ChainOptions::default()),
1106 Some(REASON_BUDGET_EXCEEDED.into())
1107 );
1108 }
1109}