1use std::collections::BTreeSet;
17
18use serde_json::{json, Value};
19
20use crate::error::{CoreError, Result};
21use crate::time::iso_to_epoch_seconds;
22
23const RATE_EPSILON: f64 = 1e-9;
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum Dimension {
30 Action,
31 Target,
32 Resource,
33 Time,
34 Rate,
35 Policy,
36}
37
38impl Dimension {
39 pub fn as_str(self) -> &'static str {
40 match self {
41 Dimension::Action => "action",
42 Dimension::Target => "target",
43 Dimension::Resource => "resource",
44 Dimension::Time => "time",
45 Dimension::Rate => "rate",
46 Dimension::Policy => "policy",
47 }
48 }
49}
50
51#[derive(Debug, Clone, PartialEq, Eq)]
54pub enum DelegationReject {
55 ScopeExceedsParent { dimension: Dimension },
57 VerifierBudgetExceeded { limit: String },
59 DelegationRevoked { link_index: usize },
62 SubjectIssuerMismatch { link_index: usize },
64 UntrustedPrincipal,
66 OutsideValidityWindow,
68 Malformed { detail: String },
70}
71
72impl DelegationReject {
73 pub fn code(&self) -> &'static str {
74 match self {
75 DelegationReject::ScopeExceedsParent { .. } => "scope_exceeds_parent",
76 DelegationReject::VerifierBudgetExceeded { .. } => "verifier_budget_exceeded",
77 DelegationReject::DelegationRevoked { .. } => "delegation_revoked",
78 DelegationReject::SubjectIssuerMismatch { .. } => "subject_issuer_mismatch",
79 DelegationReject::UntrustedPrincipal => "untrusted_principal",
80 DelegationReject::OutsideValidityWindow => "outside_validity_window",
81 DelegationReject::Malformed { .. } => "malformed_delegation",
82 }
83 }
84}
85
86#[derive(Debug, Clone, Default)]
89pub struct VerifierBudget {
90 pub max_depth: Option<usize>,
91 pub max_cumulative_ttl_seconds: Option<i64>,
92}
93
94type DResult = std::result::Result<(), DelegationReject>;
95
96fn intent<'a>(link: &'a Value) -> Option<&'a Value> {
101 link.get("intent")
102}
103
104fn string_set(v: Option<&Value>) -> Result<Option<BTreeSet<String>>> {
109 match v {
110 None | Some(Value::Null) => Ok(None),
111 Some(Value::String(s)) => {
112 let mut set = BTreeSet::new();
113 set.insert(s.clone());
114 Ok(Some(set))
115 }
116 Some(Value::Array(arr)) => {
117 let mut set = BTreeSet::new();
118 for item in arr {
119 match item.as_str() {
120 Some(s) => {
121 set.insert(s.to_string());
122 }
123 None => {
124 return Err(CoreError::Json(
125 "action/target array must be strings".into(),
126 ))
127 }
128 }
129 }
130 Ok(Some(set))
131 }
132 Some(_) => Err(CoreError::Json(
133 "action/target must be a string or array".into(),
134 )),
135 }
136}
137
138fn is_sub_resource(child: &str, parent: &str) -> bool {
141 let c = child.trim_end_matches('/');
142 let p = parent.trim_end_matches('/');
143 if c == p {
144 return true;
145 }
146 c.len() > p.len() && c.starts_with(p) && c.as_bytes()[p.len()] == b'/'
149}
150
151fn parse_duration_seconds(s: &str) -> Result<i64> {
154 let bytes = s.as_bytes();
155 if bytes.is_empty() || bytes[0] != b'P' {
156 return Err(CoreError::Json(format!("invalid duration: {s}")));
157 }
158 let mut total: i64 = 0;
159 let mut num = String::new();
160 let mut in_time = false;
161 let mut saw_field = false;
162 for &b in &bytes[1..] {
163 match b {
164 b'T' => in_time = true,
165 b'0'..=b'9' => num.push(b as char),
166 b'D' | b'H' | b'M' | b'S' => {
167 if num.is_empty() {
168 return Err(CoreError::Json(format!("invalid duration: {s}")));
169 }
170 let n: i64 = num
171 .parse()
172 .map_err(|_| CoreError::Json(format!("invalid duration: {s}")))?;
173 let secs = match b {
174 b'D' => n * 86_400,
175 b'H' => n * 3_600,
176 b'M' if in_time => n * 60, b'M' => n * 2_592_000, b'S' => n,
179 _ => unreachable!(),
180 };
181 total += secs;
182 num.clear();
183 saw_field = true;
184 }
185 _ => return Err(CoreError::Json(format!("invalid duration: {s}"))),
186 }
187 }
188 if !saw_field || !num.is_empty() {
189 return Err(CoreError::Json(format!("invalid duration: {s}")));
190 }
191 Ok(total)
192}
193
194fn rate_events_per_sec(rate: &Value) -> Result<f64> {
196 let obj = rate
197 .as_object()
198 .ok_or_else(|| CoreError::Json("rate must be an object".into()))?;
199 let limit = obj
200 .get("limit")
201 .and_then(|v| v.as_f64())
202 .ok_or_else(|| CoreError::Json("rate.limit must be a number".into()))?;
203 if limit < 0.0 {
204 return Err(CoreError::Json("rate.limit must be non-negative".into()));
205 }
206 let window = obj
207 .get("window")
208 .and_then(|v| v.as_str())
209 .ok_or_else(|| CoreError::Json("rate.window must be an ISO-8601 duration".into()))?;
210 let secs = parse_duration_seconds(window)?;
211 if secs <= 0 {
212 return Err(CoreError::Json("rate.window must be positive".into()));
213 }
214 Ok(limit / secs as f64)
215}
216
217fn policy_not_weaker(parent: &Value, child: &Value) -> bool {
225 let (pobj, cobj) = match (parent.as_object(), child.as_object()) {
226 (Some(p), Some(c)) => (p, c),
227 _ => return false, };
229 for (k, pv) in pobj {
230 match cobj.get(k) {
231 None => return false, Some(cv) => match (pv.as_f64(), cv.as_f64()) {
233 (Some(pn), Some(cn)) => {
234 let weaker = if k.starts_with("max") {
235 cn > pn } else if k.starts_with("min") {
237 cn < pn } else {
239 cn != pn };
241 if weaker {
242 return false;
243 }
244 }
245 (Some(_), None) | (None, Some(_)) => return false, (None, None) => {
247 if pv != cv {
248 return false; }
250 }
251 },
252 }
253 }
254 true
255}
256
257fn window(link: &Value) -> Result<(Option<i64>, Option<i64>)> {
258 let vf = match link.get("validFrom").and_then(|v| v.as_str()) {
259 Some(s) => Some(iso_to_epoch_seconds(s)?),
260 None => None,
261 };
262 let vu = match link.get("validUntil").and_then(|v| v.as_str()) {
263 Some(s) => Some(iso_to_epoch_seconds(s)?),
264 None => None,
265 };
266 Ok((vf, vu))
267}
268
269pub fn non_expansion(parent: &Value, child: &Value) -> std::result::Result<(), Dimension> {
277 let p_intent = intent(parent);
278 let c_intent = intent(child);
279
280 if let Ok(Some(c_actions)) = string_set(c_intent.and_then(|v| v.get("action"))) {
282 if let Ok(Some(p_actions)) = string_set(p_intent.and_then(|v| v.get("action"))) {
283 if !c_actions.is_subset(&p_actions) {
284 return Err(Dimension::Action);
285 }
286 }
287 } else if c_intent.map(|v| v.get("action").is_some()).unwrap_or(false) {
288 return Err(Dimension::Action); }
290
291 if let Ok(Some(c_targets)) = string_set(c_intent.and_then(|v| v.get("target"))) {
293 if let Ok(Some(p_targets)) = string_set(p_intent.and_then(|v| v.get("target"))) {
294 if !c_targets.is_subset(&p_targets) {
295 return Err(Dimension::Target);
296 }
297 }
298 } else if c_intent.map(|v| v.get("target").is_some()).unwrap_or(false) {
299 return Err(Dimension::Target);
300 }
301
302 let c_res = c_intent
304 .and_then(|v| v.get("resource"))
305 .and_then(|v| v.as_str());
306 if let Some(cr) = c_res {
307 if let Some(pr) = p_intent
308 .and_then(|v| v.get("resource"))
309 .and_then(|v| v.as_str())
310 {
311 if !is_sub_resource(cr, pr) {
312 return Err(Dimension::Resource);
313 }
314 }
315 } else if c_intent
316 .and_then(|v| v.get("resource"))
317 .map(|v| !v.is_null())
318 .unwrap_or(false)
319 {
320 return Err(Dimension::Resource); }
322
323 let (cf, cu) = match window(child) {
325 Ok(w) => w,
326 Err(_) => return Err(Dimension::Time),
327 };
328 let (pf, pu) = match window(parent) {
329 Ok(w) => w,
330 Err(_) => return Err(Dimension::Time),
331 };
332 if let (Some(f), Some(pf)) = (cf, pf) {
333 if f < pf {
334 return Err(Dimension::Time);
335 }
336 }
337 if let (Some(u), Some(pu)) = (cu, pu) {
338 if u > pu {
339 return Err(Dimension::Time);
340 }
341 }
342
343 if let Some(cr) = child.get("rate") {
345 if !cr.is_null() {
346 let ce = match rate_events_per_sec(cr) {
347 Ok(e) => e,
348 Err(_) => return Err(Dimension::Rate),
349 };
350 if let Some(pr) = parent.get("rate") {
351 if !pr.is_null() {
352 let pe = match rate_events_per_sec(pr) {
353 Ok(e) => e,
354 Err(_) => return Err(Dimension::Rate),
355 };
356 if ce > pe + RATE_EPSILON {
357 return Err(Dimension::Rate);
358 }
359 }
360 }
361 }
362 }
363
364 if let Some(cp) = child.get("policy") {
366 if !cp.is_null() {
367 if let Some(pp) = parent.get("policy") {
368 if !pp.is_null() && !policy_not_weaker(pp, cp) {
369 return Err(Dimension::Policy);
370 }
371 }
372 }
373 }
374
375 if let Some(cap) = parent.get("policy").and_then(|p| p.get("maxSpend")) {
377 if let Some(amount) = c_intent.and_then(|i| i.get("amount")) {
378 match (amount.as_f64(), cap.as_f64()) {
379 (Some(a), Some(c)) if a <= c => {}
380 _ => return Err(Dimension::Policy),
381 }
382 }
383 }
384
385 Ok(())
386}
387
388pub fn inherit(parent_effective: &Value, child: &Value) -> Value {
392 let mut out = child.as_object().cloned().unwrap_or_default();
393 let mut c_intent = child
394 .get("intent")
395 .and_then(|i| i.as_object())
396 .cloned()
397 .unwrap_or_default();
398 if let Some(p_intent) = parent_effective.get("intent").and_then(|i| i.as_object()) {
399 for k in ["action", "target", "resource"] {
400 if !c_intent.contains_key(k) {
401 if let Some(v) = p_intent.get(k) {
402 c_intent.insert(k.into(), v.clone());
403 }
404 }
405 }
406 }
407 out.insert("intent".into(), Value::Object(c_intent));
408 for k in ["rate", "policy", "validFrom", "validUntil"] {
409 let absent = out.get(k).map(|v| v.is_null()).unwrap_or(true);
410 if absent {
411 if let Some(v) = parent_effective.get(k).filter(|v| !v.is_null()) {
412 out.insert(k.into(), v.clone());
413 }
414 }
415 }
416 Value::Object(out)
417}
418
419pub fn first_broader_step(views: &[Value]) -> std::result::Result<(), Dimension> {
423 let Some(first) = views.first() else {
424 return Ok(());
425 };
426 let mut effective = first.clone();
427 for child in &views[1..] {
428 non_expansion(&effective, child)?;
429 effective = inherit(&effective, child);
430 }
431 Ok(())
432}
433
434fn link_str<'a>(link: &'a Value, key: &str) -> Option<&'a str> {
439 link.get(key).and_then(|v| v.as_str())
440}
441
442pub fn validate_chain(
452 chain: &[Value],
453 trusted_roots: &[String],
454 revoked_link_indices: &[usize],
455 budget: &VerifierBudget,
456 now_iso: &str,
457 clock_skew_seconds: i64,
458) -> DResult {
459 if chain.is_empty() {
460 return Err(DelegationReject::Malformed {
461 detail: "empty delegation chain".into(),
462 });
463 }
464
465 if let Some(max) = budget.max_depth {
467 if chain.len() > max {
468 return Err(DelegationReject::VerifierBudgetExceeded {
469 limit: "depth".into(),
470 });
471 }
472 }
473
474 for (i, link) in chain.iter().enumerate() {
476 if link.as_object().is_none() {
477 return Err(DelegationReject::Malformed {
478 detail: format!("link {i} is not an object"),
479 });
480 }
481 if link_str(link, "issuer").is_none() || link_str(link, "subject").is_none() {
482 return Err(DelegationReject::Malformed {
483 detail: format!("link {i} missing issuer/subject"),
484 });
485 }
486 }
487
488 if !trusted_roots.is_empty() {
490 let root_issuer = link_str(&chain[0], "issuer").unwrap();
491 if !trusted_roots.iter().any(|r| r == root_issuer) {
492 return Err(DelegationReject::UntrustedPrincipal);
493 }
494 }
495
496 if let Some(&idx) = revoked_link_indices.iter().min() {
498 if idx < chain.len() {
499 return Err(DelegationReject::DelegationRevoked { link_index: idx });
500 }
501 }
502
503 let mut effective = chain[0].clone();
506 for i in 1..chain.len() {
507 let parent = &chain[i - 1];
508 let child = &chain[i];
509 if link_str(parent, "subject") != link_str(child, "issuer") {
510 return Err(DelegationReject::SubjectIssuerMismatch { link_index: i });
511 }
512 let checked = non_expansion(&effective, child);
513 effective = inherit(&effective, child);
514 checked.map_err(|dimension| DelegationReject::ScopeExceedsParent { dimension })?;
515 }
516
517 let mut eff_start: Option<i64> = None;
520 let mut eff_end: Option<i64> = None;
521 let mut cumulative_ttl: i64 = 0;
522 for link in chain {
523 let (vf, vu) = window(link).map_err(|e| DelegationReject::Malformed {
524 detail: e.to_string(),
525 })?;
526 if let Some(f) = vf {
527 eff_start = Some(eff_start.map_or(f, |cur| cur.max(f)));
528 }
529 if let Some(u) = vu {
530 eff_end = Some(eff_end.map_or(u, |cur| cur.min(u)));
531 }
532 if let (Some(f), Some(u)) = (vf, vu) {
533 if u >= f {
534 cumulative_ttl += u - f;
535 }
536 }
537 }
538 let now = iso_to_epoch_seconds(now_iso).map_err(|e| DelegationReject::Malformed {
539 detail: e.to_string(),
540 })?;
541 if let Some(f) = eff_start {
542 if now < f - clock_skew_seconds {
543 return Err(DelegationReject::OutsideValidityWindow);
544 }
545 }
546 if let Some(u) = eff_end {
547 if now > u + clock_skew_seconds {
548 return Err(DelegationReject::OutsideValidityWindow);
549 }
550 }
551
552 if let Some(max) = budget.max_cumulative_ttl_seconds {
554 if cumulative_ttl > max {
555 return Err(DelegationReject::VerifierBudgetExceeded {
556 limit: "cumulative_ttl".into(),
557 });
558 }
559 }
560
561 Ok(())
562}
563
564pub fn validate_chain_json(request_json: &str) -> String {
578 let req: Value = match serde_json::from_str(request_json) {
579 Ok(v) => v,
580 Err(e) => return verdict_malformed(&format!("request json: {e}")),
581 };
582 let chain: Vec<Value> = match req.get("chain").and_then(|v| v.as_array()) {
583 Some(c) => c.clone(),
584 None => return verdict_malformed("missing chain array"),
585 };
586 let trusted_roots: Vec<String> = req
587 .get("trustedRoots")
588 .and_then(|v| v.as_array())
589 .map(|a| {
590 a.iter()
591 .filter_map(|x| x.as_str().map(String::from))
592 .collect()
593 })
594 .unwrap_or_default();
595 let revoked: Vec<usize> = req
596 .get("revokedIndices")
597 .and_then(|v| v.as_array())
598 .map(|a| {
599 a.iter()
600 .filter_map(|x| x.as_u64().map(|n| n as usize))
601 .collect()
602 })
603 .unwrap_or_default();
604 let budget = VerifierBudget {
605 max_depth: req
606 .pointer("/budget/maxDepth")
607 .and_then(|v| v.as_u64())
608 .map(|n| n as usize),
609 max_cumulative_ttl_seconds: req
610 .pointer("/budget/maxCumulativeTtlSeconds")
611 .and_then(|v| v.as_i64()),
612 };
613 let now = req.get("nowIso").and_then(|v| v.as_str()).unwrap_or("");
614 let skew = req
615 .get("clockSkewSeconds")
616 .and_then(|v| v.as_i64())
617 .unwrap_or(30);
618
619 match validate_chain(&chain, &trusted_roots, &revoked, &budget, now, skew) {
620 Ok(()) => json!({ "valid": true }).to_string(),
621 Err(r) => reject_to_json(&r).to_string(),
622 }
623}
624
625fn verdict_malformed(detail: &str) -> String {
626 json!({ "valid": false, "code": "malformed_delegation", "detail": detail }).to_string()
627}
628
629fn reject_to_json(r: &DelegationReject) -> Value {
630 let mut v = json!({ "valid": false, "code": r.code() });
631 let o = v.as_object_mut().unwrap();
632 match r {
633 DelegationReject::ScopeExceedsParent { dimension } => {
634 o.insert("dimension".into(), json!(dimension.as_str()));
635 }
636 DelegationReject::VerifierBudgetExceeded { limit } => {
637 o.insert("limit".into(), json!(limit));
638 }
639 DelegationReject::DelegationRevoked { link_index }
640 | DelegationReject::SubjectIssuerMismatch { link_index } => {
641 o.insert("linkIndex".into(), json!(link_index));
642 }
643 DelegationReject::Malformed { detail } => {
644 o.insert("detail".into(), json!(detail));
645 }
646 DelegationReject::UntrustedPrincipal | DelegationReject::OutsideValidityWindow => {}
647 }
648 v
649}
650
651#[cfg(test)]
652mod tests {
653 use super::*;
654 use serde_json::json;
655
656 fn link(issuer: &str, subject: &str, intent: Value) -> Value {
657 json!({
658 "issuer": issuer,
659 "subject": subject,
660 "intent": intent,
661 "validFrom": "2026-04-26T09:00:00Z",
662 "validUntil": "2026-04-26T12:00:00Z"
663 })
664 }
665
666 fn now() -> &'static str {
667 "2026-04-26T10:00:00Z"
668 }
669
670 #[test]
671 fn restate_unchanged_is_valid() {
672 let i = json!({"action":"read","target":"t","resource":"https://x/a"});
673 let chain = vec![
674 link("did:web:root", "did:web:a", i.clone()),
675 link("did:web:a", "did:web:b", i.clone()),
676 ];
677 assert!(validate_chain(&chain, &[], &[], &VerifierBudget::default(), now(), 30).is_ok());
678 }
679
680 #[test]
681 fn resource_narrowing_is_valid() {
682 let chain = vec![
683 link(
684 "did:web:root",
685 "did:web:a",
686 json!({"resource":"https://x/a"}),
687 ),
688 link(
689 "did:web:a",
690 "did:web:b",
691 json!({"resource":"https://x/a/b"}),
692 ),
693 ];
694 assert!(validate_chain(&chain, &[], &[], &VerifierBudget::default(), now(), 30).is_ok());
695 }
696
697 #[test]
698 fn resource_widening_rejected_naming_dimension() {
699 let chain = vec![
700 link(
701 "did:web:root",
702 "did:web:a",
703 json!({"resource":"https://x/a/b"}),
704 ),
705 link("did:web:a", "did:web:b", json!({"resource":"https://x/a"})),
706 ];
707 let err =
708 validate_chain(&chain, &[], &[], &VerifierBudget::default(), now(), 30).unwrap_err();
709 assert_eq!(err.code(), "scope_exceeds_parent");
710 assert_eq!(
711 err,
712 DelegationReject::ScopeExceedsParent {
713 dimension: Dimension::Resource
714 }
715 );
716 }
717
718 #[test]
719 fn sibling_prefix_is_not_sub_resource() {
720 assert!(!is_sub_resource("https://x/a2", "https://x/a"));
721 assert!(is_sub_resource("https://x/a/b", "https://x/a"));
722 assert!(is_sub_resource("https://x/a", "https://x/a/"));
723 }
724
725 #[test]
726 fn action_superset_rejected() {
727 let chain = vec![
728 link("did:web:root", "did:web:a", json!({"action":"read"})),
729 link("did:web:a", "did:web:b", json!({"action":["read","write"]})),
730 ];
731 let err =
732 validate_chain(&chain, &[], &[], &VerifierBudget::default(), now(), 30).unwrap_err();
733 assert_eq!(
734 err,
735 DelegationReject::ScopeExceedsParent {
736 dimension: Dimension::Action
737 }
738 );
739 }
740
741 #[test]
742 fn action_subset_ok() {
743 let chain = vec![
744 link(
745 "did:web:root",
746 "did:web:a",
747 json!({"action":["read","write"]}),
748 ),
749 link("did:web:a", "did:web:b", json!({"action":"read"})),
750 ];
751 assert!(validate_chain(&chain, &[], &[], &VerifierBudget::default(), now(), 30).is_ok());
752 }
753
754 #[test]
755 fn rate_widening_rejected() {
756 let mut a = link("did:web:root", "did:web:a", json!({"action":"read"}));
757 a["rate"] = json!({"limit":100,"window":"PT1H"});
758 let mut b = link("did:web:a", "did:web:b", json!({"action":"read"}));
759 b["rate"] = json!({"limit":100,"window":"PT30M"}); let chain = vec![a, b];
761 let err =
762 validate_chain(&chain, &[], &[], &VerifierBudget::default(), now(), 30).unwrap_err();
763 assert_eq!(
764 err,
765 DelegationReject::ScopeExceedsParent {
766 dimension: Dimension::Rate
767 }
768 );
769 }
770
771 #[test]
772 fn rate_narrowing_ok() {
773 let mut a = link("did:web:root", "did:web:a", json!({"action":"read"}));
774 a["rate"] = json!({"limit":100,"window":"PT1H"});
775 let mut b = link("did:web:a", "did:web:b", json!({"action":"read"}));
776 b["rate"] = json!({"limit":50,"window":"PT1H"});
777 let chain = vec![a, b];
778 assert!(validate_chain(&chain, &[], &[], &VerifierBudget::default(), now(), 30).is_ok());
779 }
780
781 #[test]
782 fn policy_weakening_rejected() {
783 let mut a = link("did:web:root", "did:web:a", json!({"action":"read"}));
784 a["policy"] = json!({"minHeartbeatAgeSeconds":300});
785 let mut b = link("did:web:a", "did:web:b", json!({"action":"read"}));
786 b["policy"] = json!({"minHeartbeatAgeSeconds":100}); let chain = vec![a, b];
788 let err =
789 validate_chain(&chain, &[], &[], &VerifierBudget::default(), now(), 30).unwrap_err();
790 assert_eq!(
791 err,
792 DelegationReject::ScopeExceedsParent {
793 dimension: Dimension::Policy
794 }
795 );
796 }
797
798 #[test]
799 fn policy_dropping_constraint_rejected() {
800 let mut a = link("did:web:root", "did:web:a", json!({"action":"read"}));
801 a["policy"] = json!({"minHeartbeatAgeSeconds":300});
802 let mut b = link("did:web:a", "did:web:b", json!({"action":"read"}));
803 b["policy"] = json!({"unrelated":true}); let chain = vec![a, b];
805 assert!(validate_chain(&chain, &[], &[], &VerifierBudget::default(), now(), 30).is_err());
806 }
807
808 #[test]
809 fn time_widening_rejected() {
810 let chain = vec![
811 json!({"issuer":"did:web:root","subject":"did:web:a","intent":{"action":"read"},
812 "validFrom":"2026-04-26T10:00:00Z","validUntil":"2026-04-26T11:00:00Z"}),
813 json!({"issuer":"did:web:a","subject":"did:web:b","intent":{"action":"read"},
814 "validFrom":"2026-04-26T09:00:00Z","validUntil":"2026-04-26T12:00:00Z"}),
815 ];
816 let err = validate_chain(
817 &chain,
818 &[],
819 &[],
820 &VerifierBudget::default(),
821 "2026-04-26T10:30:00Z",
822 30,
823 )
824 .unwrap_err();
825 assert_eq!(
826 err,
827 DelegationReject::ScopeExceedsParent {
828 dimension: Dimension::Time
829 }
830 );
831 }
832
833 #[test]
834 fn subject_issuer_mismatch_rejected() {
835 let i = json!({"action":"read"});
836 let chain = vec![
837 link("did:web:root", "did:web:a", i.clone()),
838 link("did:web:WRONG", "did:web:b", i.clone()),
839 ];
840 let err =
841 validate_chain(&chain, &[], &[], &VerifierBudget::default(), now(), 30).unwrap_err();
842 assert_eq!(
843 err,
844 DelegationReject::SubjectIssuerMismatch { link_index: 1 }
845 );
846 }
847
848 #[test]
849 fn untrusted_root_rejected() {
850 let i = json!({"action":"read"});
851 let chain = vec![link("did:web:root", "did:web:a", i)];
852 let err = validate_chain(
853 &chain,
854 &["did:web:other".into()],
855 &[],
856 &VerifierBudget::default(),
857 now(),
858 30,
859 )
860 .unwrap_err();
861 assert_eq!(err, DelegationReject::UntrustedPrincipal);
862 }
863
864 #[test]
865 fn cascade_revocation_rejects_whole_chain() {
866 let i = json!({"action":"read"});
867 let chain = vec![
868 link("did:web:root", "did:web:a", i.clone()),
869 link("did:web:a", "did:web:b", i.clone()),
870 link("did:web:b", "did:web:c", i.clone()),
871 ];
872 let err =
874 validate_chain(&chain, &[], &[1], &VerifierBudget::default(), now(), 30).unwrap_err();
875 assert_eq!(err, DelegationReject::DelegationRevoked { link_index: 1 });
876 }
877
878 #[test]
879 fn budget_depth_exceeded() {
880 let i = json!({"action":"read"});
881 let chain = vec![
882 link("did:web:root", "did:web:a", i.clone()),
883 link("did:web:a", "did:web:b", i.clone()),
884 link("did:web:b", "did:web:c", i.clone()),
885 ];
886 let budget = VerifierBudget {
887 max_depth: Some(2),
888 max_cumulative_ttl_seconds: None,
889 };
890 let err = validate_chain(&chain, &[], &[], &budget, now(), 30).unwrap_err();
891 assert_eq!(
892 err,
893 DelegationReject::VerifierBudgetExceeded {
894 limit: "depth".into()
895 }
896 );
897 }
898
899 #[test]
900 fn deep_but_attenuating_chain_is_valid_without_depth_cap() {
901 let mut chain = Vec::new();
904 let i = json!({"action":"read","resource":"https://x/a"});
905 for n in 0..10 {
906 let issuer = if n == 0 {
907 "did:web:root".to_string()
908 } else {
909 format!("did:web:h{}", n - 1)
910 };
911 let subject = format!("did:web:h{n}");
912 chain.push(link(&issuer, &subject, i.clone()));
913 }
914 assert!(validate_chain(&chain, &[], &[], &VerifierBudget::default(), now(), 30).is_ok());
915 }
916
917 #[test]
918 fn now_outside_effective_window_rejected() {
919 let chain = vec![link("did:web:root", "did:web:a", json!({"action":"read"}))];
920 let err = validate_chain(
921 &chain,
922 &[],
923 &[],
924 &VerifierBudget::default(),
925 "2026-04-26T20:00:00Z",
926 30,
927 )
928 .unwrap_err();
929 assert_eq!(err, DelegationReject::OutsideValidityWindow);
930 }
931
932 #[test]
933 fn absent_child_dimension_inherits_and_passes() {
934 let chain = vec![
935 link(
936 "did:web:root",
937 "did:web:a",
938 json!({"action":"read","resource":"https://x/a"}),
939 ),
940 link(
941 "did:web:a",
942 "did:web:b",
943 json!({"resource":"https://x/a/b"}),
944 ), ];
946 assert!(validate_chain(&chain, &[], &[], &VerifierBudget::default(), now(), 30).is_ok());
947 }
948
949 #[test]
950 fn duration_parser() {
951 assert_eq!(parse_duration_seconds("PT1H").unwrap(), 3600);
952 assert_eq!(parse_duration_seconds("PT30M").unwrap(), 1800);
953 assert_eq!(parse_duration_seconds("PT1H30M15S").unwrap(), 5415);
954 assert_eq!(parse_duration_seconds("P1D").unwrap(), 86400);
955 assert!(parse_duration_seconds("1H").is_err());
956 assert!(parse_duration_seconds("PT").is_err());
957 }
958}