vouch-core 4.0.0

Vouch Protocol canonical core: JCS canonicalization, Ed25519 + ML-DSA proofs, did:key/multikey, Data Integrity (eddsa-jcs-2022), credentials, delegation, revocation. One byte-exact implementation shared by every language SDK via WASM and UniFFI/C-FFI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
//! v1.7 capability attenuation: the non-expansion rule over the six delegation
//! dimensions, verifier cost budgets, and chain-cascade revocation
//! (Specification 9.3 to 9.6).
//!
//! Security posture: default-deny. Every check answers "is the child broader
//! than its parent on this dimension?" and any malformed input, unknown shape,
//! or ambiguous comparison rejects rather than admits. A delegation chain grants
//! authority, so a false "valid" is an authority-escalation bug; a false
//! "invalid" is only an availability issue. We bias hard toward rejection.
//!
//! The rules, in plain terms (the same in every language; the shared vectors
//! in `test-vectors/delegation-attenuation/` are the contract):
//!
//! * A dimension a link leaves out is inherited unchanged from its parent; it
//!   can never be widened by omission. A dimension a link writes down must be
//!   well formed: `null` or the wrong type is refused on every link, so nobody
//!   can erase a bound by writing `null`.
//! * A parent bound that is malformed refuses the step: the child cannot be
//!   shown to be inside it.
//! * A resource is refused when it holds a backslash, `%2F` or `%5C` (any
//!   case), an ASCII control character, or a `.` or `..` path segment (also
//!   spelled with `%2e`), because a server that normalises the URL would land
//!   outside the parent's resource.
//! * A child rate never allows a burst its parent forbids, in exact integers:
//!   `child.limit <= parent.limit` and `child.limit * ceil(parent.window /
//!   child.window) <= parent.limit` ([`rate_within`]).
//! * Every number in a budget or a rate is an integer of the right range.
//! * Times follow the one strict grammar in [`crate::time`], compared to the
//!   nanosecond.
//! * There is no fixed depth limit; a caller may set `maxDepth`. An encoded
//!   chain larger than 1 MiB is refused before anything else is checked.

use std::collections::BTreeSet;

use serde_json::{json, Map, Value};

use crate::error::{CoreError, Result};
use crate::time::{parse_protocol_time_ns, MAX_CLOCK_SKEW_SECONDS};

/// The largest integer every language represents exactly (2^53 - 1).
pub const MAX_SAFE_INTEGER: i64 = 9_007_199_254_740_991;

/// The deepest JSON nesting a delegation chain or policy may use.
pub const MAX_JSON_NESTING: usize = 128;

/// The largest encoded chain (JCS, UTF-8) a verifier will look at.
pub const MAX_CHAIN_BYTES: usize = 1024 * 1024;

const NS_PER_SECOND: i128 = 1_000_000_000;
/// The most digits one duration field may carry.
const MAX_DURATION_DIGITS: usize = 16;

/// The six capability dimensions a delegation link may carry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Dimension {
    Action,
    Target,
    Resource,
    Time,
    Rate,
    Policy,
}

impl Dimension {
    pub fn as_str(self) -> &'static str {
        match self {
            Dimension::Action => "action",
            Dimension::Target => "target",
            Dimension::Resource => "resource",
            Dimension::Time => "time",
            Dimension::Rate => "rate",
            Dimension::Policy => "policy",
        }
    }
}

/// A structured reason a delegation chain is rejected. `code()` yields the
/// on-the-wire reason string used across the SDKs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DelegationReject {
    /// A child link is broader than its parent on the named dimension.
    ScopeExceedsParent { dimension: Dimension },
    /// The verifier's local cost budget was exceeded; `limit` names which one.
    VerifierBudgetExceeded { limit: String },
    /// A link (0-indexed from the root) is revoked; the whole chain and every
    /// authority below it is rejected.
    DelegationRevoked { link_index: usize },
    /// A link's `subject` does not match the next link's `issuer`.
    SubjectIssuerMismatch { link_index: usize },
    /// The root link's issuer is not in the verifier's trusted set.
    UntrustedPrincipal,
    /// The current instant is outside the chain's effective validity window.
    OutsideValidityWindow,
    /// The chain or a link is structurally malformed.
    Malformed { detail: String },
}

impl DelegationReject {
    pub fn code(&self) -> &'static str {
        match self {
            DelegationReject::ScopeExceedsParent { .. } => "scope_exceeds_parent",
            DelegationReject::VerifierBudgetExceeded { .. } => "verifier_budget_exceeded",
            DelegationReject::DelegationRevoked { .. } => "delegation_revoked",
            DelegationReject::SubjectIssuerMismatch { .. } => "subject_issuer_mismatch",
            DelegationReject::UntrustedPrincipal => "untrusted_principal",
            DelegationReject::OutsideValidityWindow => "outside_validity_window",
            DelegationReject::Malformed { .. } => "malformed_delegation",
        }
    }
}

/// Verifier-local cost budget (Specification 9.4). `None` means unlimited.
/// These are the verifier's configurable choice, not a protocol requirement;
/// there is no default depth limit.
#[derive(Debug, Clone, Default)]
pub struct VerifierBudget {
    pub max_depth: Option<usize>,
    pub max_cumulative_ttl_seconds: Option<i64>,
}

type DResult = std::result::Result<(), DelegationReject>;

// --------------------------------------------------------------------------
// Small value checks
// --------------------------------------------------------------------------

/// The integer value of `v` when it is a JSON number with an integral value in
/// `[low, high]` (so 2 and 2.0 are both 2), else None. Booleans, strings, null
/// and fractions are refused.
pub fn as_int(v: &Value, low: i64, high: i64) -> Option<i64> {
    let Value::Number(n) = v else {
        return None;
    };
    let value: i64 = if let Some(i) = n.as_i64() {
        i
    } else if n.as_u64().is_some() {
        return None; // above i64::MAX, so above every range used here
    } else {
        let f = n.as_f64()?;
        if !f.is_finite() || f.fract() != 0.0 || f.abs() > MAX_SAFE_INTEGER as f64 {
            return None;
        }
        f as i64
    };
    (low..=high).contains(&value).then_some(value)
}

/// True when `value` nests arrays or objects deeper than `limit` levels. Walks
/// with an explicit stack, so hostile input cannot exhaust the call stack. A
/// scalar has depth 0 and `[]` has depth 1.
pub fn json_nesting_exceeds(value: &Value, limit: usize) -> bool {
    let mut stack: Vec<(&Value, usize)> = vec![(value, 0)];
    while let Some((item, depth)) = stack.pop() {
        let children: Box<dyn Iterator<Item = &Value>> = match item {
            Value::Array(a) => Box::new(a.iter()),
            Value::Object(o) => Box::new(o.values()),
            _ => continue,
        };
        let depth = depth + 1;
        if depth > limit {
            return true;
        }
        for child in children {
            if child.is_array() || child.is_object() {
                stack.push((child, depth));
            }
        }
    }
    false
}

/// The UTF-8 length of `value` in its JCS (RFC 8785) form, the size every
/// language measures a chain by.
pub fn encoded_size(value: &Value) -> usize {
    crate::jcs::canonicalize(value).len()
}

/// The cost limit a chain breaks, or None: `"depth"` when the caller set
/// `max_depth` and the chain has more links, `"size"` when its JCS form is
/// larger than [`MAX_CHAIN_BYTES`]. There is no default depth limit. An `Err`
/// means the chain nests deeper than [`MAX_JSON_NESTING`] (malformed).
pub fn chain_budget_exceeded(
    chain: &Value,
    max_depth: Option<usize>,
) -> std::result::Result<Option<&'static str>, String> {
    if let (Some(max), Some(links)) = (max_depth, chain.as_array()) {
        if links.len() > max {
            return Ok(Some("depth"));
        }
    }
    if json_nesting_exceeds(chain, MAX_JSON_NESTING) {
        return Err("delegation chain nests too deeply".into());
    }
    if encoded_size(chain) > MAX_CHAIN_BYTES {
        return Ok(Some("size"));
    }
    Ok(None)
}

fn is_number(v: &Value) -> bool {
    matches!(v, Value::Number(_))
}

/// Equality in the JSON data model: numbers by value (9 == 9.0), a boolean is
/// never a number, and containers compare element by element.
pub fn json_equal(a: &Value, b: &Value) -> bool {
    match (a, b) {
        (Value::Number(x), Value::Number(y)) => {
            if let (Some(i), Some(j)) = (x.as_i64(), y.as_i64()) {
                return i == j;
            }
            if let (Some(i), Some(j)) = (x.as_u64(), y.as_u64()) {
                return i == j;
            }
            match (x.as_f64(), y.as_f64()) {
                (Some(i), Some(j)) => i == j,
                _ => false,
            }
        }
        (Value::Array(x), Value::Array(y)) => {
            x.len() == y.len() && x.iter().zip(y).all(|(i, j)| json_equal(i, j))
        }
        (Value::Object(x), Value::Object(y)) => {
            x.len() == y.len()
                && x.iter()
                    .all(|(k, v)| y.get(k).map(|w| json_equal(v, w)).unwrap_or(false))
        }
        _ => a == b,
    }
}

// --------------------------------------------------------------------------
// Dimension helpers
// --------------------------------------------------------------------------

fn intent(link: &Value) -> Option<&Map<String, Value>> {
    link.get("intent").and_then(|i| i.as_object())
}

/// An action/target field as a set of strings: a string or an array of
/// strings. Anything else (null included) is an error.
fn string_set(v: &Value) -> Result<BTreeSet<String>> {
    match v {
        Value::String(s) => Ok(BTreeSet::from([s.clone()])),
        Value::Array(arr) => {
            let mut set = BTreeSet::new();
            for item in arr {
                match item.as_str() {
                    Some(s) => {
                        set.insert(s.to_string());
                    }
                    None => {
                        return Err(CoreError::Json(
                            "action/target array must be strings".into(),
                        ))
                    }
                }
            }
            Ok(set)
        }
        _ => Err(CoreError::Json(
            "action/target must be a string or array of strings".into(),
        )),
    }
}

/// True when a resource could escape its parent once a server normalises it: a
/// backslash, `%2F` or `%5C` in any case, an ASCII control character, or a `.`
/// / `..` segment (with `%2e` read as `.`) in the part before the first `?` or
/// `#`.
pub fn resource_is_unsafe(resource: &str) -> bool {
    let lowered = resource.to_ascii_lowercase();
    if resource.contains('\\') || lowered.contains("%2f") || lowered.contains("%5c") {
        return true;
    }
    if resource.bytes().any(|c| c < 0x20 || c == 0x7f) {
        return true;
    }
    let path = lowered.split(['?', '#']).next().unwrap_or("");
    path.split('/').any(|segment| {
        let s = segment.replace("%2e", ".");
        s == "." || s == ".."
    })
}

/// True when `child` equals `parent` or extends it at a `/` boundary (trailing
/// slashes ignored), and `child` is not an unsafe resource
/// ([`resource_is_unsafe`]). "https://x/a2" is NOT under "https://x/a".
pub fn resource_within(child: &str, parent: &str) -> bool {
    if resource_is_unsafe(child) {
        return false;
    }
    let c = child.trim_end_matches('/');
    let p = parent.trim_end_matches('/');
    if c == p {
        return true;
    }
    c.len() > p.len() && c.starts_with(p) && c.as_bytes()[p.len()] == b'/'
}

/// Seconds in an ISO-8601 duration `P[nM][nD][T[nH][nM][nS]]`: ASCII digits
/// only, each field at most 16 digits, the total at most 2^53 - 1, and at least
/// one field. A month in the date part counts as 30 days. "P", "PT" and a
/// trailing "T" are refused.
pub fn parse_duration_seconds(s: &str) -> Result<i64> {
    let bad = || {
        CoreError::Json(format!(
            "invalid duration: {:?}",
            s.chars().take(64).collect::<String>()
        ))
    };
    let b = s.as_bytes();
    if b.first() != Some(&b'P') || s == "P" || s == "PT" || s.ends_with('T') {
        return Err(bad());
    }
    // Units allowed in order: the date part, then the time part after 'T'.
    const DATE: [(u8, i64); 2] = [(b'M', 2_592_000), (b'D', 86_400)];
    const TIME: [(u8, i64); 3] = [(b'H', 3_600), (b'M', 60), (b'S', 1)];
    let mut units: &[(u8, i64)] = &DATE;
    let mut in_time = false;
    let mut total: i64 = 0;
    let mut saw_field = false;
    let mut i = 1usize;
    while i < b.len() {
        if b[i] == b'T' {
            if in_time {
                return Err(bad());
            }
            in_time = true;
            units = &TIME;
            i += 1;
            continue;
        }
        let start = i;
        while i < b.len() && b[i].is_ascii_digit() {
            i += 1;
        }
        let digits = &s[start..i];
        if digits.is_empty() || i >= b.len() {
            return Err(bad());
        }
        if digits.len() > MAX_DURATION_DIGITS {
            return Err(CoreError::Json("duration field is too large".into()));
        }
        let unit = b[i];
        let Some(pos) = units.iter().position(|(u, _)| *u == unit) else {
            return Err(bad());
        };
        let n: i64 = digits.parse().map_err(|_| bad())?;
        total = n
            .checked_mul(units[pos].1)
            .and_then(|v| total.checked_add(v))
            .ok_or_else(|| CoreError::Json("duration is too large".into()))?;
        units = &units[pos + 1..];
        saw_field = true;
        i += 1;
    }
    if !saw_field {
        return Err(bad());
    }
    if total > MAX_SAFE_INTEGER {
        return Err(CoreError::Json("duration is too large".into()));
    }
    Ok(total)
}

/// `(limit, window_seconds)` of a rate object: an integer limit from 0 to
/// 2^53 - 1 and a positive duration window.
fn parse_rate(rate: &Value) -> Result<(i64, i64)> {
    let obj = rate
        .as_object()
        .ok_or_else(|| CoreError::Json("rate must be an object".into()))?;
    let limit = obj
        .get("limit")
        .and_then(|v| as_int(v, 0, MAX_SAFE_INTEGER))
        .ok_or_else(|| {
            CoreError::Json("rate.limit must be an integer from 0 to 2^53 - 1".into())
        })?;
    let window = obj
        .get("window")
        .and_then(|v| v.as_str())
        .ok_or_else(|| CoreError::Json("rate.window must be an ISO-8601 duration".into()))?;
    let secs = parse_duration_seconds(window)?;
    if secs <= 0 {
        return Err(CoreError::Json("rate.window must be positive".into()));
    }
    Ok((limit, secs))
}

/// True when a child rate can never allow more events than its parent.
///
/// The parent allows `parent_limit` events in any `parent_window` seconds. A
/// child window as long as the parent's (or longer) can spend its whole limit
/// in one burst, so it needs `child_limit <= parent_limit`. A shorter child
/// window repeats `ceil(parent_window / child_window)` times inside one parent
/// window, so it also needs `child_limit * ceil(...) <= parent_limit`. Under
/// 10 per hour: 240 per day is refused (240 at once), 1 per minute is refused
/// (60 in an hour), 2 per 12 minutes is allowed (10 in an hour). Exact
/// integers, no rounding, no overflow. Windows must be positive.
pub fn rate_within(
    child_limit: i64,
    child_window: i64,
    parent_limit: i64,
    parent_window: i64,
) -> bool {
    if child_window <= 0 || parent_window <= 0 {
        return false;
    }
    let (cl, cw, pl, pw) = (
        i128::from(child_limit),
        i128::from(child_window),
        i128::from(parent_limit),
        i128::from(parent_window),
    );
    let repeats = (pw + cw - 1) / cw; // ceil for positive integers
    cl <= pl && cl * repeats <= pl
}

/// Child policy must be equal to or stricter than the parent's. Numeric values
/// narrow by the key's name: a key starting with "max" is a ceiling (the child
/// may lower it, never raise it), a key starting with "min" is a floor (the
/// child may raise it, never lower it), and any other numeric key must be
/// restated unchanged. Other values must be equal in the JSON data model
/// (`true` is not `1`). A parent key the child omits means the child dropped a
/// constraint, which is broader, and is rejected.
fn policy_not_weaker(parent: &Value, child: &Value) -> bool {
    let (pobj, cobj) = match (parent.as_object(), child.as_object()) {
        (Some(p), Some(c)) => (p, c),
        _ => return false, // a policy that is not an object cannot be reasoned about
    };
    for (k, pv) in pobj {
        let Some(cv) = cobj.get(k) else {
            return false; // child dropped a parent constraint => weaker
        };
        match (is_number(pv), is_number(cv)) {
            (true, true) => {
                let (Some(pn), Some(cn)) = (pv.as_f64(), cv.as_f64()) else {
                    return false;
                };
                let weaker = if k.starts_with("max") {
                    cn > pn // a raised ceiling is broader
                } else if k.starts_with("min") {
                    cn < pn // a lowered floor is broader
                } else {
                    !json_equal(pv, cv) // unknown direction: must be restated
                };
                if weaker {
                    return false;
                }
            }
            (true, false) | (false, true) => return false, // type mismatch
            (false, false) => {
                if !json_equal(pv, cv) {
                    return false; // non-numeric must match exactly
                }
            }
        }
    }
    true
}

/// A link's window bound in nanoseconds: absent is None; present but null,
/// not a string, or not a protocol time is an error.
fn bound(link: &Value, key: &str) -> Result<Option<i128>> {
    match link.get(key) {
        None => Ok(None),
        Some(Value::String(s)) => Ok(Some(parse_protocol_time_ns(s)?)),
        Some(_) => Err(CoreError::Json(format!("{key} must be a time string"))),
    }
}

fn window(link: &Value) -> Result<(Option<i128>, Option<i128>)> {
    Ok((bound(link, "validFrom")?, bound(link, "validUntil")?))
}

/// The first dimension a link writes down in a form that cannot be compared,
/// or None. A present dimension must be well formed: action and target a
/// string or an array of strings; resource a string that is not unsafe;
/// validFrom / validUntil protocol times; rate an object with an integer limit
/// and a positive duration window; policy an object nested no deeper than 128
/// levels. `null` is malformed everywhere.
pub fn malformed_dimension(link: &Value) -> Option<Dimension> {
    let Some(obj) = link.as_object() else {
        return Some(Dimension::Action);
    };
    let intent = match obj.get("intent") {
        None => None,
        Some(Value::Object(i)) => Some(i),
        Some(_) => return Some(Dimension::Action),
    };
    if let Some(i) = intent {
        for (key, dim) in [("action", Dimension::Action), ("target", Dimension::Target)] {
            if let Some(v) = i.get(key) {
                if string_set(v).is_err() {
                    return Some(dim);
                }
            }
        }
        if let Some(res) = i.get("resource") {
            match res.as_str() {
                Some(r) if !resource_is_unsafe(r) => {}
                _ => return Some(Dimension::Resource),
            }
        }
    }
    if window(link).is_err() {
        return Some(Dimension::Time);
    }
    if let Some(rate) = obj.get("rate") {
        if parse_rate(rate).is_err() {
            return Some(Dimension::Rate);
        }
    }
    if let Some(policy) = obj.get("policy") {
        if !policy.is_object() || json_nesting_exceeds(policy, MAX_JSON_NESTING) {
            return Some(Dimension::Policy);
        }
    }
    None
}

// --------------------------------------------------------------------------
// Non-expansion between an adjacent (parent, child) pair
// --------------------------------------------------------------------------

/// Verify that `child` does not broaden `parent` on any dimension. Returns the
/// offending [`Dimension`] on failure. A malformed dimension on either side
/// ([`malformed_dimension`]) is reported as that dimension: a child cannot
/// erase a bound with `null`, and nothing can be shown to sit inside a
/// malformed parent bound.
pub fn non_expansion(parent: &Value, child: &Value) -> std::result::Result<(), Dimension> {
    if let Some(dim) = malformed_dimension(child) {
        return Err(dim);
    }
    if let Some(dim) = malformed_dimension(parent) {
        return Err(dim);
    }
    let empty = Map::new();
    let p_intent = intent(parent).unwrap_or(&empty);
    let c_intent = intent(child).unwrap_or(&empty);

    // action / target: the child's set must be a subset of the parent's.
    for (key, dim) in [("action", Dimension::Action), ("target", Dimension::Target)] {
        if let (Some(c), Some(p)) = (c_intent.get(key), p_intent.get(key)) {
            match (string_set(c), string_set(p)) {
                (Ok(cs), Ok(ps)) if cs.is_subset(&ps) => {}
                _ => return Err(dim),
            }
        }
    }

    // resource: the child's resource must be within the parent's.
    if let (Some(c), Some(p)) = (c_intent.get("resource"), p_intent.get("resource")) {
        match (c.as_str(), p.as_str()) {
            (Some(cr), Some(pr)) if resource_within(cr, pr) => {}
            _ => return Err(Dimension::Resource),
        }
    }

    // time: the child's window must be within the parent's (to the nanosecond).
    let (Ok((cf, cu)), Ok((pf, pu))) = (window(child), window(parent)) else {
        return Err(Dimension::Time);
    };
    if let (Some(f), Some(pf)) = (cf, pf) {
        if f < pf {
            return Err(Dimension::Time);
        }
    }
    if let (Some(u), Some(pu)) = (cu, pu) {
        if u > pu {
            return Err(Dimension::Time);
        }
    }

    // rate: never a burst the parent forbids, in exact integers.
    if let (Some(cr), Some(pr)) = (child.get("rate"), parent.get("rate")) {
        let (Ok((c_limit, c_secs)), Ok((p_limit, p_secs))) = (parse_rate(cr), parse_rate(pr))
        else {
            return Err(Dimension::Rate);
        };
        if !rate_within(c_limit, c_secs, p_limit, p_secs) {
            return Err(Dimension::Rate);
        }
    }

    // policy: the child's policy must be equal to or stricter than the parent's.
    let p_pol = parent.get("policy").filter(|p| !p.is_null());
    if let (Some(cp), Some(pp)) = (child.get("policy"), p_pol) {
        if !policy_not_weaker(pp, cp) {
            return Err(Dimension::Policy);
        }
    }

    // spend: an action's intent.amount stays within the parent's maxSpend.
    if let Some(cap) = p_pol
        .and_then(|p| p.as_object())
        .and_then(|p| p.get("maxSpend"))
    {
        if let Some(amount) = c_intent.get("amount") {
            match (amount.as_f64(), cap.as_f64()) {
                (Some(a), Some(c)) if a <= c => {}
                _ => return Err(Dimension::Policy),
            }
        }
    }

    Ok(())
}

/// The child's effective capability: any dimension it omits is inherited
/// unchanged from its parent's effective capability (Specification 9.2).
/// `amount` is per action and is never inherited.
pub fn inherit(parent_effective: &Value, child: &Value) -> Value {
    let mut out = child.as_object().cloned().unwrap_or_default();
    let mut c_intent = child
        .get("intent")
        .and_then(|i| i.as_object())
        .cloned()
        .unwrap_or_default();
    if let Some(p_intent) = parent_effective.get("intent").and_then(|i| i.as_object()) {
        for k in ["action", "target", "resource"] {
            if !c_intent.contains_key(k) {
                if let Some(v) = p_intent.get(k) {
                    c_intent.insert(k.into(), v.clone());
                }
            }
        }
    }
    out.insert("intent".into(), Value::Object(c_intent));
    for k in ["rate", "policy", "validFrom", "validUntil"] {
        let absent = out.get(k).map(|v| v.is_null()).unwrap_or(true);
        if absent {
            if let Some(v) = parent_effective.get(k).filter(|v| !v.is_null()) {
                out.insert(k.into(), v.clone());
            }
        }
    }
    Value::Object(out)
}

/// Walk root to leaf comparing each step against its parent's EFFECTIVE
/// capability (inherited dimensions included). Returns the first offending
/// dimension; a malformed dimension on the root is reported too.
pub fn first_broader_step(views: &[Value]) -> std::result::Result<(), Dimension> {
    let Some(first) = views.first() else {
        return Ok(());
    };
    if let Some(dim) = malformed_dimension(first) {
        return Err(dim);
    }
    let mut effective = first.clone();
    for child in &views[1..] {
        non_expansion(&effective, child)?;
        effective = inherit(&effective, child);
    }
    Ok(())
}

// --------------------------------------------------------------------------
// Full chain validation
// --------------------------------------------------------------------------

fn link_str<'a>(link: &'a Value, key: &str) -> Option<&'a str> {
    link.get(key).and_then(|v| v.as_str())
}

fn malformed(detail: impl Into<String>) -> DelegationReject {
    DelegationReject::Malformed {
        detail: detail.into(),
    }
}

/// Validate a delegation chain ordered root -> leaf under the v1.7 rules.
///
/// * `trusted_roots`: `None` skips the root-trust check (the caller anchors
///   trust elsewhere); a list names the trusted roots (a bare domain stands
///   for its did:web), and an empty list trusts nobody.
/// * `revoked_link_indices` are links the caller has resolved as revoked
///   (credential- or DID-level); any hit rejects the whole chain (cascade).
/// * `budget` caps the verifier's work; `None` fields are unlimited. There is
///   no default depth limit; an encoded chain over 1 MiB is always refused.
/// * `clock_skew_seconds` must be 0 to 120.
///
/// Returns `Ok(())` when the chain is valid, or the first [`DelegationReject`].
pub fn validate_chain(
    chain: &[Value],
    trusted_roots: Option<&[String]>,
    revoked_link_indices: &[usize],
    budget: &VerifierBudget,
    now_iso: &str,
    clock_skew_seconds: i64,
) -> DResult {
    if !(0..=MAX_CLOCK_SKEW_SECONDS).contains(&clock_skew_seconds) {
        return Err(malformed(format!(
            "clockSkewSeconds must be an integer from 0 to {MAX_CLOCK_SKEW_SECONDS}"
        )));
    }
    let skew = i128::from(clock_skew_seconds) * NS_PER_SECOND;
    let now = parse_protocol_time_ns(now_iso).map_err(|e| malformed(format!("nowIso: {e}")))?;
    if chain.is_empty() {
        return Err(malformed("empty delegation chain"));
    }

    // Verifier budget, before anything else is looked at.
    let chain_value = Value::Array(chain.to_vec());
    match chain_budget_exceeded(&chain_value, budget.max_depth) {
        Ok(None) => {}
        Ok(Some(limit)) => {
            return Err(DelegationReject::VerifierBudgetExceeded {
                limit: limit.into(),
            })
        }
        Err(detail) => return Err(malformed(detail)),
    }

    // Every link must be an object with issuer and subject strings, and an
    // intent object when it has one.
    for (i, link) in chain.iter().enumerate() {
        let shape_ok = link.is_object()
            && link_str(link, "issuer").is_some()
            && link_str(link, "subject").is_some()
            && link.get("intent").map(|v| v.is_object()).unwrap_or(true);
        if !shape_ok {
            return Err(malformed(format!("link {i} malformed")));
        }
    }

    // Root trust.
    if let Some(roots) = trusted_roots {
        let root_issuer = link_str(&chain[0], "issuer").unwrap_or("");
        if !roots
            .iter()
            .any(|r| crate::delegation::root_matches(r, root_issuer))
        {
            return Err(DelegationReject::UntrustedPrincipal);
        }
    }

    // Cascade revocation: a revoked link invalidates the whole chain.
    if let Some(&idx) = revoked_link_indices.iter().min() {
        if idx < chain.len() {
            return Err(DelegationReject::DelegationRevoked { link_index: idx });
        }
    }

    // Linkage and non-expansion for each step against its parent's effective
    // capability (dimensions a link omits are inherited).
    if let Some(dimension) = malformed_dimension(&chain[0]) {
        return Err(DelegationReject::ScopeExceedsParent { dimension });
    }
    let mut effective = chain[0].clone();
    let mut windows = vec![window(&chain[0]).map_err(|e| malformed(e.to_string()))?];
    for i in 1..chain.len() {
        let parent = &chain[i - 1];
        let child = &chain[i];
        if link_str(parent, "subject") != link_str(child, "issuer") {
            return Err(DelegationReject::SubjectIssuerMismatch { link_index: i });
        }
        non_expansion(&effective, child)
            .map_err(|dimension| DelegationReject::ScopeExceedsParent { dimension })?;
        effective = inherit(&effective, child);
        windows.push(window(&effective).map_err(|e| malformed(e.to_string()))?);
    }

    // Effective validity window: the latest start and the earliest end.
    let eff_start = windows.iter().filter_map(|w| w.0).max();
    let eff_end = windows.iter().filter_map(|w| w.1).min();
    if let (Some(f), Some(u)) = (eff_start, eff_end) {
        if f > u {
            return Err(DelegationReject::OutsideValidityWindow);
        }
    }
    if let Some(f) = eff_start {
        if now < f - skew {
            return Err(DelegationReject::OutsideValidityWindow);
        }
    }
    if let Some(u) = eff_end {
        if now > u + skew {
            return Err(DelegationReject::OutsideValidityWindow);
        }
    }

    // Cumulative TTL over each link's effective (inherited) window. A link with
    // an open end has no finite TTL, so a TTL budget refuses it.
    if let Some(max) = budget.max_cumulative_ttl_seconds {
        let exceeded = || DelegationReject::VerifierBudgetExceeded {
            limit: "cumulative_ttl".into(),
        };
        let mut total: i128 = 0;
        for (vf, vu) in &windows {
            let (Some(f), Some(u)) = (vf, vu) else {
                return Err(exceeded());
            };
            total += (u - f).max(0);
        }
        if total > i128::from(max) * NS_PER_SECOND {
            return Err(exceeded());
        }
    }

    Ok(())
}

// --------------------------------------------------------------------------
// JSON boundary for the SDK bindings (uniffi / wasm)
// --------------------------------------------------------------------------

/// Validate a delegation chain from a single JSON request, returning a JSON
/// verdict. Infallible: malformed input yields a `malformed_delegation` verdict
/// rather than an error, so every caller gets a uniform verdict shape.
///
/// Request:  `{ "chain": [..links..], "trustedRoots"?: [str], "revokedIndices"?:
/// [int], "budget"?: {"maxDepth"?: int, "maxCumulativeTtlSeconds"?: int},
/// "nowIso": "..", "clockSkewSeconds"?: int (0..120, default 30) }`. An option
/// that is present must be well formed (`null` included): integers are whole
/// numbers (2 and 2.0 are both 2) in range, `trustedRoots` is a list of
/// strings. There is no default depth limit.
///
/// Response: `{"valid": true}` or `{"valid": false, "code": "..", ..detail..}`.
pub fn validate_chain_json(request_json: &str) -> String {
    let req: Value = match serde_json::from_str(request_json) {
        Ok(v) => v,
        Err(e) => return verdict_malformed(&format!("request json: {e}")),
    };
    let Some(req) = req.as_object() else {
        return verdict_malformed("request must be a JSON object");
    };
    let chain: Vec<Value> = match req.get("chain").and_then(|v| v.as_array()) {
        Some(c) => c.clone(),
        None => return verdict_malformed("missing chain array"),
    };
    for key in [
        "trustedRoots",
        "revokedIndices",
        "budget",
        "nowIso",
        "clockSkewSeconds",
    ] {
        if matches!(req.get(key), Some(Value::Null)) {
            return verdict_malformed(&format!("{key} must not be null"));
        }
    }
    let trusted_roots: Option<Vec<String>> = match req.get("trustedRoots") {
        None => None,
        Some(Value::Array(a)) => {
            let mut roots = Vec::with_capacity(a.len());
            for r in a {
                match r.as_str() {
                    Some(s) => roots.push(s.to_string()),
                    None => return verdict_malformed("trustedRoots must be a list of strings"),
                }
            }
            Some(roots)
        }
        Some(_) => return verdict_malformed("trustedRoots must be a list of strings"),
    };
    let revoked: Vec<usize> = match req.get("revokedIndices") {
        None => Vec::new(),
        Some(Value::Array(a)) => {
            let mut out = Vec::with_capacity(a.len());
            for v in a {
                match as_int(v, 0, MAX_SAFE_INTEGER) {
                    Some(n) => out.push(n as usize),
                    None => {
                        return verdict_malformed(
                            "revokedIndices must be integers from 0 to 2^53 - 1",
                        )
                    }
                }
            }
            out
        }
        Some(_) => return verdict_malformed("revokedIndices must be a list of integers"),
    };
    let mut budget = VerifierBudget::default();
    match req.get("budget") {
        None => {}
        Some(Value::Object(b)) => {
            for key in ["maxDepth", "maxCumulativeTtlSeconds"] {
                if let Some(v) = b.get(key) {
                    let Some(n) = as_int(v, 0, MAX_SAFE_INTEGER) else {
                        return verdict_malformed(&format!(
                            "budget.{key} must be an integer from 0 to 2^53 - 1"
                        ));
                    };
                    if key == "maxDepth" {
                        budget.max_depth = Some(n as usize);
                    } else {
                        budget.max_cumulative_ttl_seconds = Some(n);
                    }
                }
            }
        }
        Some(_) => return verdict_malformed("budget must be an object"),
    }
    let skew = match req.get("clockSkewSeconds") {
        None => 30,
        Some(v) => match as_int(v, 0, MAX_CLOCK_SKEW_SECONDS) {
            Some(n) => n,
            None => {
                return verdict_malformed(&format!(
                    "clockSkewSeconds must be an integer from 0 to {MAX_CLOCK_SKEW_SECONDS}"
                ))
            }
        },
    };
    let now = match req.get("nowIso") {
        None => "",
        Some(Value::String(s)) => s.as_str(),
        Some(_) => return verdict_malformed("nowIso must be a time string"),
    };

    match validate_chain(
        &chain,
        trusted_roots.as_deref(),
        &revoked,
        &budget,
        now,
        skew,
    ) {
        Ok(()) => json!({ "valid": true }).to_string(),
        Err(r) => reject_to_json(&r).to_string(),
    }
}

fn verdict_malformed(detail: &str) -> String {
    json!({ "valid": false, "code": "malformed_delegation", "detail": detail }).to_string()
}

fn reject_to_json(r: &DelegationReject) -> Value {
    let mut v = json!({ "valid": false, "code": r.code() });
    let o = v.as_object_mut().unwrap();
    match r {
        DelegationReject::ScopeExceedsParent { dimension } => {
            o.insert("dimension".into(), json!(dimension.as_str()));
        }
        DelegationReject::VerifierBudgetExceeded { limit } => {
            o.insert("limit".into(), json!(limit));
        }
        DelegationReject::DelegationRevoked { link_index }
        | DelegationReject::SubjectIssuerMismatch { link_index } => {
            o.insert("linkIndex".into(), json!(link_index));
        }
        DelegationReject::Malformed { detail } => {
            o.insert("detail".into(), json!(detail));
        }
        DelegationReject::UntrustedPrincipal | DelegationReject::OutsideValidityWindow => {}
    }
    v
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn link(issuer: &str, subject: &str, intent: Value) -> Value {
        json!({
            "issuer": issuer,
            "subject": subject,
            "intent": intent,
            "validFrom": "2026-04-26T09:00:00Z",
            "validUntil": "2026-04-26T12:00:00Z"
        })
    }

    fn now() -> &'static str {
        "2026-04-26T10:00:00Z"
    }

    #[test]
    fn restate_unchanged_is_valid() {
        let i = json!({"action":"read","target":"t","resource":"https://x/a"});
        let chain = vec![
            link("did:web:root", "did:web:a", i.clone()),
            link("did:web:a", "did:web:b", i.clone()),
        ];
        assert!(validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).is_ok());
    }

    #[test]
    fn resource_narrowing_is_valid() {
        let chain = vec![
            link(
                "did:web:root",
                "did:web:a",
                json!({"resource":"https://x/a"}),
            ),
            link(
                "did:web:a",
                "did:web:b",
                json!({"resource":"https://x/a/b"}),
            ),
        ];
        assert!(validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).is_ok());
    }

    #[test]
    fn resource_widening_rejected_naming_dimension() {
        let chain = vec![
            link(
                "did:web:root",
                "did:web:a",
                json!({"resource":"https://x/a/b"}),
            ),
            link("did:web:a", "did:web:b", json!({"resource":"https://x/a"})),
        ];
        let err =
            validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).unwrap_err();
        assert_eq!(err.code(), "scope_exceeds_parent");
        assert_eq!(
            err,
            DelegationReject::ScopeExceedsParent {
                dimension: Dimension::Resource
            }
        );
    }

    #[test]
    fn sibling_prefix_is_not_sub_resource() {
        assert!(!resource_within("https://x/a2", "https://x/a"));
        assert!(resource_within("https://x/a/b", "https://x/a"));
        assert!(resource_within("https://x/a", "https://x/a/"));
    }

    #[test]
    fn action_superset_rejected() {
        let chain = vec![
            link("did:web:root", "did:web:a", json!({"action":"read"})),
            link("did:web:a", "did:web:b", json!({"action":["read","write"]})),
        ];
        let err =
            validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).unwrap_err();
        assert_eq!(
            err,
            DelegationReject::ScopeExceedsParent {
                dimension: Dimension::Action
            }
        );
    }

    #[test]
    fn action_subset_ok() {
        let chain = vec![
            link(
                "did:web:root",
                "did:web:a",
                json!({"action":["read","write"]}),
            ),
            link("did:web:a", "did:web:b", json!({"action":"read"})),
        ];
        assert!(validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).is_ok());
    }

    #[test]
    fn rate_widening_rejected() {
        let mut a = link("did:web:root", "did:web:a", json!({"action":"read"}));
        a["rate"] = json!({"limit":100,"window":"PT1H"});
        let mut b = link("did:web:a", "did:web:b", json!({"action":"read"}));
        b["rate"] = json!({"limit":100,"window":"PT30M"}); // twice the events/sec
        let chain = vec![a, b];
        let err =
            validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).unwrap_err();
        assert_eq!(
            err,
            DelegationReject::ScopeExceedsParent {
                dimension: Dimension::Rate
            }
        );
    }

    #[test]
    fn rate_narrowing_ok() {
        let mut a = link("did:web:root", "did:web:a", json!({"action":"read"}));
        a["rate"] = json!({"limit":100,"window":"PT1H"});
        let mut b = link("did:web:a", "did:web:b", json!({"action":"read"}));
        b["rate"] = json!({"limit":50,"window":"PT1H"});
        let chain = vec![a, b];
        assert!(validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).is_ok());
    }

    #[test]
    fn policy_weakening_rejected() {
        let mut a = link("did:web:root", "did:web:a", json!({"action":"read"}));
        a["policy"] = json!({"minHeartbeatAgeSeconds":300});
        let mut b = link("did:web:a", "did:web:b", json!({"action":"read"}));
        b["policy"] = json!({"minHeartbeatAgeSeconds":100}); // weaker
        let chain = vec![a, b];
        let err =
            validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).unwrap_err();
        assert_eq!(
            err,
            DelegationReject::ScopeExceedsParent {
                dimension: Dimension::Policy
            }
        );
    }

    #[test]
    fn policy_dropping_constraint_rejected() {
        let mut a = link("did:web:root", "did:web:a", json!({"action":"read"}));
        a["policy"] = json!({"minHeartbeatAgeSeconds":300});
        let mut b = link("did:web:a", "did:web:b", json!({"action":"read"}));
        b["policy"] = json!({"unrelated":true}); // dropped the parent's constraint
        let chain = vec![a, b];
        assert!(validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).is_err());
    }

    #[test]
    fn time_widening_rejected() {
        let chain = vec![
            json!({"issuer":"did:web:root","subject":"did:web:a","intent":{"action":"read"},
                   "validFrom":"2026-04-26T10:00:00Z","validUntil":"2026-04-26T11:00:00Z"}),
            json!({"issuer":"did:web:a","subject":"did:web:b","intent":{"action":"read"},
                   "validFrom":"2026-04-26T09:00:00Z","validUntil":"2026-04-26T12:00:00Z"}),
        ];
        let err = validate_chain(
            &chain,
            None,
            &[],
            &VerifierBudget::default(),
            "2026-04-26T10:30:00Z",
            30,
        )
        .unwrap_err();
        assert_eq!(
            err,
            DelegationReject::ScopeExceedsParent {
                dimension: Dimension::Time
            }
        );
    }

    #[test]
    fn subject_issuer_mismatch_rejected() {
        let i = json!({"action":"read"});
        let chain = vec![
            link("did:web:root", "did:web:a", i.clone()),
            link("did:web:WRONG", "did:web:b", i.clone()),
        ];
        let err =
            validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).unwrap_err();
        assert_eq!(
            err,
            DelegationReject::SubjectIssuerMismatch { link_index: 1 }
        );
    }

    #[test]
    fn untrusted_root_rejected() {
        let i = json!({"action":"read"});
        let chain = vec![link("did:web:root", "did:web:a", i)];
        let err = validate_chain(
            &chain,
            Some(&["did:web:other".to_string()]),
            &[],
            &VerifierBudget::default(),
            now(),
            30,
        )
        .unwrap_err();
        assert_eq!(err, DelegationReject::UntrustedPrincipal);
    }

    #[test]
    fn cascade_revocation_rejects_whole_chain() {
        let i = json!({"action":"read"});
        let chain = vec![
            link("did:web:root", "did:web:a", i.clone()),
            link("did:web:a", "did:web:b", i.clone()),
            link("did:web:b", "did:web:c", i.clone()),
        ];
        // middle link revoked
        let err =
            validate_chain(&chain, None, &[1], &VerifierBudget::default(), now(), 30).unwrap_err();
        assert_eq!(err, DelegationReject::DelegationRevoked { link_index: 1 });
    }

    #[test]
    fn budget_depth_exceeded() {
        let i = json!({"action":"read"});
        let chain = vec![
            link("did:web:root", "did:web:a", i.clone()),
            link("did:web:a", "did:web:b", i.clone()),
            link("did:web:b", "did:web:c", i.clone()),
        ];
        let budget = VerifierBudget {
            max_depth: Some(2),
            max_cumulative_ttl_seconds: None,
        };
        let err = validate_chain(&chain, None, &[], &budget, now(), 30).unwrap_err();
        assert_eq!(
            err,
            DelegationReject::VerifierBudgetExceeded {
                limit: "depth".into()
            }
        );
    }

    #[test]
    fn deep_but_attenuating_chain_is_valid_without_depth_cap() {
        // Ten hops, each restating the same authority: valid now that the fixed
        // depth limit is gone (this is the whole point of v1.7).
        let mut chain = Vec::new();
        let i = json!({"action":"read","resource":"https://x/a"});
        for n in 0..10 {
            let issuer = if n == 0 {
                "did:web:root".to_string()
            } else {
                format!("did:web:h{}", n - 1)
            };
            let subject = format!("did:web:h{n}");
            chain.push(link(&issuer, &subject, i.clone()));
        }
        assert!(validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).is_ok());
    }

    #[test]
    fn now_outside_effective_window_rejected() {
        let chain = vec![link("did:web:root", "did:web:a", json!({"action":"read"}))];
        let err = validate_chain(
            &chain,
            None,
            &[],
            &VerifierBudget::default(),
            "2026-04-26T20:00:00Z",
            30,
        )
        .unwrap_err();
        assert_eq!(err, DelegationReject::OutsideValidityWindow);
    }

    #[test]
    fn absent_child_dimension_inherits_and_passes() {
        let chain = vec![
            link(
                "did:web:root",
                "did:web:a",
                json!({"action":"read","resource":"https://x/a"}),
            ),
            link(
                "did:web:a",
                "did:web:b",
                json!({"resource":"https://x/a/b"}),
            ), // action omitted => inherit
        ];
        assert!(validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).is_ok());
    }

    #[test]
    fn duration_parser() {
        assert_eq!(parse_duration_seconds("PT1H").unwrap(), 3600);
        assert_eq!(parse_duration_seconds("PT30M").unwrap(), 1800);
        assert_eq!(parse_duration_seconds("PT1H30M15S").unwrap(), 5415);
        assert_eq!(parse_duration_seconds("P1D").unwrap(), 86400);
        assert!(parse_duration_seconds("1H").is_err());
        assert!(parse_duration_seconds("PT").is_err());
    }

    #[test]
    fn duration_parser_is_strict_and_never_overflows() {
        assert_eq!(parse_duration_seconds("P1M").unwrap(), 2_592_000);
        assert_eq!(parse_duration_seconds("P1DT1S").unwrap(), 86_401);
        for bad in [
            "P",
            "PT",
            "P1DT",
            "P1H",
            "PT1D",
            "P1D1M",
            "PT1S1M",
            "P\u{0661}D",
            "PT-1S",
            "PT1.5S",
            "p1D",
            "P1DTT1S",
        ] {
            assert!(parse_duration_seconds(bad).is_err(), "{bad}");
        }
        // Huge fields refuse cleanly (no panic, no wrap).
        assert!(parse_duration_seconds("P9999999999999999D").is_err());
        assert!(parse_duration_seconds("P99999999999999999D").is_err());
        assert!(parse_duration_seconds(&format!("PT{}S", "9".repeat(40))).is_err());
    }

    #[test]
    fn unsafe_resources_never_sit_inside_a_parent() {
        for r in [
            "https://x/a/../b",
            "https://x/a/./b",
            "https://x/a/%2e%2E/b",
            "https://x/a/.%2e",
            "https://x/a\\..\\b",
            "https://x/a/..%2Fb",
            "https://x/a/%5c",
            "https://x/a/\u{0007}",
        ] {
            assert!(resource_is_unsafe(r), "{r}");
            assert!(!resource_within(r, "https://x/a"), "{r}");
        }
        // Dots after '?' or '#' are data, not path segments.
        assert!(resource_within("https://x/a/b?next=../c", "https://x/a"));
    }

    #[test]
    fn integers_are_whole_numbers_in_range() {
        assert_eq!(as_int(&json!(2), 0, 10), Some(2));
        assert_eq!(as_int(&json!(2.0), 0, 10), Some(2));
        for v in [
            json!(2.5),
            json!(-1),
            json!(11),
            json!(true),
            json!("2"),
            Value::Null,
        ] {
            assert_eq!(as_int(&v, 0, 10), None, "{v}");
        }
        assert_eq!(as_int(&json!(u64::MAX), 0, MAX_SAFE_INTEGER), None);
        // A revoked index written as 1.0 still revokes link 1.
        let verdict: Value = serde_json::from_str(&validate_chain_json(
            &json!({"chain": [
                {"issuer":"did:web:r","subject":"did:web:a","intent":{"action":"read"}},
                {"issuer":"did:web:a","subject":"did:web:b","intent":{"action":"read"}}],
                "revokedIndices": [1.0], "nowIso": "2026-04-26T10:00:00Z"})
            .to_string(),
        ))
        .unwrap();
        assert_eq!(verdict["code"], json!("delegation_revoked"));
        let verdict: Value = serde_json::from_str(&validate_chain_json(
            &json!({"chain": [{"issuer":"did:web:r","subject":"did:web:a"}],
                    "budget": {"maxDepth": -1}, "nowIso": "2026-04-26T10:00:00Z"})
            .to_string(),
        ))
        .unwrap();
        assert_eq!(verdict["code"], json!("malformed_delegation"));
    }
}