vouch-core 4.1.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
//! Fleet chains: credentials presented one by one, root first.
//!
//! A port of `vouch.fleet.verify_delegated_chain` (Python is the reference).
//! A root identity grants a device's DID a scope; the device signs its own
//! actions (or sub-grants) with its own key. A verifier is handed the chain as
//! separate credentials, `[root_grant, ...sub_grants, leaf_action]`, and checks
//! it back to a trusted root:
//!
//! 1. before any credential is verified or any key is looked up, from the
//!    credentials' fields alone: every credential is a JSON object (else
//!    `"credential {i} is not a JSON object"`), then the presented-chain
//!    binding rule ([`crate::grant_chain::presented_chain_problem`]: binding
//!    fields of the right shape, credential 0 a root grant, and every later
//!    credential that carries a digest or a non-empty `delegationChain` bound
//!    to the credential before it; else `"credential {i}: {code}"`);
//! 2. for every credential, in order: it names an issuer, the first issuer is a
//!    trusted root, it verifies (proof, window, and any embedded delegation
//!    chain, with the fleet's trusted roots as that chain's trusted starting
//!    points and their keys resolving its grants), its status when it carries
//!    one, and neither its issuer nor its id is revoked;
//! 3. for every adjacent pair: the parent names a delegatee, the delegatee is
//!    not revoked, the child is issued by it, the child is no broader than the
//!    effective capability so far (the same `capability_view` / `inherit` /
//!    `non_expansion` rules as embedded chains, time left out), and the child's
//!    window sits inside the parent's;
//! 4. the leaf's intent meets the caller's exact `require_action`,
//!    `require_target` and `require_resource`.
//!
//! Refusal texts match the reference byte for byte. Three differences follow
//! from the core being stateless and offline:
//!
//! * revocation is a list of revoked identifiers (device DIDs, credential ids),
//!   not a callback; [`revocation_candidates`] lists every identifier the check
//!   asks about, so a caller with a callback can build the list first;
//! * keys come from the trusted-roots map, then from a `did:key` issuer; there
//!   is no `did:web` resolution (put such keys in the map);
//! * a credential (or an embedded grant) that carries `credentialStatus` is
//!   checked against the status lists the caller supplies; with none supplied it
//!   is refused, as the reference refuses it offline. `check_status: false`
//!   skips the status check, as `check_status=False` does in the reference.
//!
//! The leaf is returned so the caller can mark it in its replay store; the core
//! keeps no replay state.

use std::collections::BTreeMap;

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

use crate::attenuation;
use crate::credentials;
use crate::delegation::{self, ChainOptions};
use crate::grant_chain::{self, py_repr, py_repr_str, truthy};
use crate::status_list;
use crate::time::parse_protocol_time_ns;

/// How a fleet chain is verified.
#[derive(Debug, Clone, Copy)]
pub struct FleetOptions<'a> {
    /// The accepted roots: DID to Ed25519 public key. The first credential's
    /// issuer must be here. Its DIDs are the trusted starting points of any
    /// embedded delegation chain, and its keys resolve later issuers and
    /// embedded grants before a `did:key` is decoded.
    pub trusted_roots: &'a BTreeMap<String, Vec<u8>>,
    /// Revoked identifiers: device DIDs and credential ids. A chain whose
    /// issuer, credential id or delegatee is listed is refused.
    pub revoked: &'a [String],
    /// The current instant (protocol time).
    pub now_iso: &'a str,
    /// The allowed clock drift, 0 to 120 seconds.
    pub clock_skew_seconds: i64,
    /// An exact `intent.action` the leaf must carry.
    pub require_action: Option<&'a str>,
    /// An exact `intent.target` the leaf must carry.
    pub require_target: Option<&'a str>,
    /// An exact `intent.resource` the leaf must carry.
    pub require_resource: Option<&'a str>,
    /// Check the `credentialStatus` of every credential and embedded grant
    /// that carries one (the reference's default).
    pub check_status: bool,
    /// The status lists the caller fetched, keyed by `statusListCredential`
    /// URL. `None` refuses any credential that carries a status entry while
    /// `check_status` is on.
    pub status_lists: Option<&'a Map<String, Value>>,
}

/// The outcome of verifying a fleet chain.
#[derive(Debug, Clone, PartialEq)]
pub struct FleetResult {
    /// True only when every check passes.
    pub ok: bool,
    /// The first check that failed.
    pub reason: Option<String>,
    /// The leaf credential: on success, and when only the leaf policy failed.
    pub leaf: Option<Value>,
    /// The root issuer, on success.
    pub root_did: Option<String>,
}

impl FleetResult {
    fn fail(reason: String) -> Self {
        FleetResult {
            ok: false,
            reason: Some(reason),
            leaf: None,
            root_did: None,
        }
    }

    /// The result as JSON: `{"ok", "reason", "leaf", "rootDid"}`.
    pub fn to_json(&self) -> Value {
        json!({
            "ok": self.ok,
            "reason": self.reason,
            "leaf": self.leaf,
            "rootDid": self.root_did,
        })
    }
}

/// The issuer the reference reads (`_issuer_of`): the `issuer` string, the
/// first entry of an issuer list, or the `id` of an issuer object.
fn issuer_of(cred: &Value) -> Option<String> {
    let issuer = match cred.get("issuer") {
        Some(Value::Array(items)) => items.first(),
        Some(Value::Object(o)) => o.get("id"),
        other => other,
    };
    issuer
        .and_then(Value::as_str)
        .filter(|s| !s.is_empty())
        .map(String::from)
}

fn intent_of(cred: &Value) -> Option<&Map<String, Value>> {
    cred.get("credentialSubject")
        .and_then(|s| s.get("intent"))
        .and_then(Value::as_object)
}

/// The proof is a proof set, which needs a post-quantum key. (One proof
/// object is an eddsa-jcs-2022 proof or it is refused: the earlier composite
/// proof is no longer read.)
fn post_quantum_proof(cred: &Value) -> bool {
    matches!(cred.get("proof"), Some(Value::Array(_)))
}

/// The grants of a credential's embedded delegation chain.
fn embedded_grants(cred: &Value) -> Vec<&Value> {
    cred.get("credentialSubject")
        .and_then(|s| s.get("delegationChain"))
        .and_then(Value::as_array)
        .map(|links| {
            links
                .iter()
                .filter_map(|l| l.get("parentCredential").filter(|g| g.is_object()))
                .collect()
        })
        .unwrap_or_default()
}

/// The status of a credential and of every grant in its embedded chain, each
/// against a list signed by that credential's issuer. True when acceptable.
fn status_ok(cred: &Value, cred_key: &[u8], opts: &FleetOptions) -> bool {
    let mut checked: Vec<(&Value, Option<Vec<u8>>)> = vec![(cred, Some(cred_key.to_vec()))];
    for grant in embedded_grants(cred) {
        let key = issuer_of(grant).and_then(|i| opts.trusted_roots.get(&i).cloned());
        checked.push((grant, key));
    }
    for (c, key) in checked {
        if c.get("credentialStatus").is_none() {
            continue;
        }
        let Some(lists) = opts.status_lists else {
            // Offline means no fetch: a status that cannot be read is not a
            // good status.
            return false;
        };
        match status_list::check_credential_status(
            c,
            lists,
            key.as_deref(),
            None,
            opts.now_iso,
            opts.clock_skew_seconds,
        ) {
            Ok(r) if r.ok => {}
            _ => return false,
        }
    }
    true
}

/// True if the child's validity window sits inside the parent's.
fn window_within(child: &Value, parent: &Value) -> bool {
    let t = |c: &Value, k: &str| {
        c.get(k)
            .and_then(Value::as_str)
            .and_then(|s| parse_protocol_time_ns(s).ok())
    };
    match (
        t(child, "validFrom"),
        t(child, "validUntil"),
        t(parent, "validFrom"),
        t(parent, "validUntil"),
    ) {
        (Some(cf), Some(cu), Some(pf), Some(pu)) => cf >= pf && cu <= pu,
        _ => false,
    }
}

/// Every identifier the revocation check asks about, in the order it asks:
/// each credential's issuer and id, and each credential's delegatee. A caller
/// with a revocation callback passes the ones it reports as revoked.
pub fn revocation_candidates(credentials: &[Value]) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    let mut push = |s: Option<String>| {
        if let Some(s) = s.filter(|s| !s.is_empty()) {
            if !out.contains(&s) {
                out.push(s);
            }
        }
    };
    for cred in credentials {
        push(issuer_of(cred));
        push(cred.get("id").and_then(Value::as_str).map(String::from));
    }
    for cred in credentials {
        push(
            intent_of(cred)
                .and_then(|i| i.get("delegatee"))
                .and_then(Value::as_str)
                .map(String::from),
        );
    }
    out
}

/// Verify a fleet chain: credentials presented one by one, root grant first,
/// leaf action last. See the module documentation for every check, in order.
pub fn verify_delegated_chain(credentials: &[Value], opts: &FleetOptions) -> FleetResult {
    if credentials.is_empty() {
        return FleetResult::fail("empty chain".into());
    }
    for (index, cred) in credentials.iter().enumerate() {
        if !cred.is_object() {
            return FleetResult::fail(format!("credential {index} is not a JSON object"));
        }
    }
    // Every credential is bound to the one above it: checked from the
    // credentials alone, before any key is looked up.
    if let Some((index, code)) = grant_chain::presented_chain_problem(credentials) {
        return FleetResult::fail(format!("credential {index}: {code}"));
    }
    let is_revoked = |id: &str| opts.revoked.iter().any(|r| r == id);
    let root_dids: Vec<String> = opts.trusted_roots.keys().cloned().collect();
    // The embedded delegation chain starts at the fleet's root, so the fleet's
    // trusted roots are the chain's trusted starting points.
    let chain_opts = ChainOptions {
        trusted_roots: Some(&root_dids),
        grant_keys: Some(opts.trusted_roots),
        ..Default::default()
    };

    let mut issuers: Vec<String> = Vec::with_capacity(credentials.len());
    for (index, cred) in credentials.iter().enumerate() {
        let Some(issuer) = issuer_of(cred) else {
            return FleetResult::fail(format!("credential {index} has no issuer"));
        };
        // The root anchor must be explicitly trusted. Later links resolve
        // their key from the trusted roots if present, otherwise by DID.
        let given = opts.trusted_roots.get(&issuer);
        if index == 0 && given.is_none() {
            return FleetResult::fail(format!(
                "root issuer {} is not in trusted_roots",
                py_repr_str(&issuer)
            ));
        }
        let key = match given {
            Some(k) => Some(k.clone()),
            None => crate::keys::did_key_to_ed25519(&issuer).ok(),
        };
        let failed = || FleetResult::fail(format!("credential {index} failed verification"));
        let Some(key) = key else {
            return failed();
        };
        let verdict = credentials::verify_with_keys(
            cred,
            &key,
            None,
            opts.now_iso,
            opts.clock_skew_seconds,
            &chain_opts,
        );
        match verdict {
            Ok((r, _)) if r.is_valid() => {}
            Ok((r, _)) => {
                // A post-quantum proof with only an Ed25519 key given for its
                // issuer: the reference raises MissingMLDSA44KeyError, once
                // the key is a usable Ed25519 key (an unusable one fails first).
                if given.is_some()
                    && crate::keys::strict_verifying_key(&key).is_ok()
                    && r.time_valid
                    && !r.proof_valid
                    && post_quantum_proof(cred)
                {
                    return FleetResult::fail(format!("credential {index} needs an ML-DSA-44 key"));
                }
                return failed();
            }
            Err(_) => return failed(),
        }
        if opts.check_status && !status_ok(cred, &key, opts) {
            return failed();
        }

        // Revocation: a revoked issuer (device or root) or a revoked specific
        // credential breaks the chain.
        if is_revoked(&issuer) {
            return FleetResult::fail(format!(
                "credential {index} issuer {} is revoked",
                py_repr_str(&issuer)
            ));
        }
        if let Some(id) = cred.get("id").filter(|v| truthy(Some(v))) {
            if id.as_str().is_some_and(is_revoked) {
                let shown = id
                    .as_str()
                    .map(String::from)
                    .unwrap_or_else(|| id.to_string());
                return FleetResult::fail(format!("credential {index} ({shown}) is revoked"));
            }
        }
        issuers.push(issuer);
    }

    // Walk parent -> child links, comparing each child against its parent's
    // effective capability (dimensions a grant omits are inherited).
    let mut effective = delegation::capability_view(&credentials[0], false);
    for i in 0..credentials.len() - 1 {
        let (parent, child) = (&credentials[i], &credentials[i + 1]);
        let parent_intent = intent_of(parent);
        let delegatee = parent_intent.and_then(|it| it.get("delegatee"));
        if !truthy(delegatee) {
            return FleetResult::fail(format!(
                "link {i} (grant by {}) names no delegatee",
                py_repr_str(&issuers[i])
            ));
        }
        if delegatee.and_then(Value::as_str).is_some_and(is_revoked) {
            return FleetResult::fail(format!(
                "link {i}: delegatee {} is revoked",
                py_repr(delegatee)
            ));
        }
        if delegatee.and_then(Value::as_str) != Some(issuers[i + 1].as_str()) {
            return FleetResult::fail(format!(
                "link {i}: child issuer {} is not the delegatee {} the parent authorized",
                py_repr_str(&issuers[i + 1]),
                py_repr(delegatee)
            ));
        }

        let child_view = delegation::capability_view(child, false);
        let dimension = attenuation::non_expansion(&effective, &child_view);
        effective = attenuation::inherit(&effective, &child_view);
        if let Err(dim) = dimension {
            let name = dim.as_str();
            let granted = parent_intent.and_then(|it| it.get(name));
            let asked = intent_of(child).and_then(|it| it.get(name));
            return FleetResult::fail(format!(
                "link {i}: {name} {} is not within the granted {}",
                py_repr(asked),
                py_repr(granted)
            ));
        }

        if !window_within(child, parent) {
            return FleetResult::fail(format!(
                "link {i}: child validity is outside the grant window"
            ));
        }
    }

    let leaf = &credentials[credentials.len() - 1];
    let leaf_intent = intent_of(leaf);
    for (field, expected) in [
        ("action", opts.require_action),
        ("target", opts.require_target),
        ("resource", opts.require_resource),
    ] {
        let Some(expected) = expected else { continue };
        if leaf_intent
            .and_then(|it| it.get(field))
            .and_then(Value::as_str)
            != Some(expected)
        {
            return FleetResult {
                ok: false,
                reason: Some(format!("leaf intent.{field} != {}", py_repr_str(expected))),
                leaf: Some(leaf.clone()),
                root_did: None,
            };
        }
    }

    FleetResult {
        ok: true,
        reason: None,
        leaf: Some(leaf.clone()),
        root_did: Some(issuers[0].clone()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::credentials::{sign_sub_grant, sign_vouch_credential, BuildCredentialOptions};
    use crate::data_integrity::BuildProofOptions;
    use crate::hybrid;
    use crate::keys::Ed25519KeyPair;

    const NOW: &str = "2026-11-10T12:00:00Z";
    const FROM: &str = "2026-11-10T00:00:00Z";
    const UNTIL: &str = "2026-11-11T00:00:00Z";

    struct Who {
        seed: [u8; 32],
        did: String,
    }

    fn key_party(n: u8) -> Who {
        let seed = [n; 32];
        Who {
            seed,
            did: Ed25519KeyPair::from_seed(&seed).did_key(),
        }
    }

    fn web_party(n: u8, host: &str) -> Who {
        Who {
            seed: [n; 32],
            did: format!("did:web:{host}"),
        }
    }

    fn public(w: &Who) -> Vec<u8> {
        Ed25519KeyPair::from_seed(&w.seed).public_key().to_vec()
    }

    fn intent(action: &str, target: &str, resource: &str, extra: Value) -> Value {
        let mut i = json!({"action": action, "target": target, "resource": resource});
        for (k, v) in extra.as_object().unwrap() {
            i[k] = v.clone();
        }
        i
    }

    fn opts(
        who: &Who,
        intent: Value,
        id: &str,
        window: (&str, &str),
        chain: Option<Vec<Value>>,
    ) -> BuildCredentialOptions {
        BuildCredentialOptions {
            issuer_did: who.did.clone(),
            credential_id: id.into(),
            intent,
            valid_from: window.0.into(),
            valid_until: window.1.into(),
            reputation_score: None,
            delegation_chain: chain.map(Value::Array),
            credential_status: None,
        }
    }

    fn proof(who: &Who) -> BuildProofOptions {
        BuildProofOptions::new(format!("{}#key-1", who.did), FROM)
    }

    fn sign(who: &Who, intent: Value, id: &str) -> Value {
        sign_vouch_credential(
            &opts(who, intent, id, (FROM, UNTIL), None),
            &who.seed,
            &proof(who),
        )
        .unwrap()
    }

    fn sign_window(who: &Who, intent: Value, id: &str, window: (&str, &str)) -> Value {
        sign_vouch_credential(&opts(who, intent, id, window, None), &who.seed, &proof(who)).unwrap()
    }

    fn roots(ws: &[&Who]) -> BTreeMap<String, Vec<u8>> {
        ws.iter().map(|w| (w.did.clone(), public(w))).collect()
    }

    fn check(
        creds: &[Value],
        roots: &BTreeMap<String, Vec<u8>>,
        revoked: &[String],
    ) -> FleetResult {
        verify_delegated_chain(
            creds,
            &FleetOptions {
                trusted_roots: roots,
                revoked,
                now_iso: NOW,
                clock_skew_seconds: 30,
                require_action: None,
                require_target: None,
                require_resource: None,
                check_status: true,
                status_lists: None,
            },
        )
    }

    fn reason(r: FleetResult) -> String {
        assert!(!r.ok);
        r.reason.unwrap()
    }

    /// root (did:web, key in the map) grants read on calendar/team to device.
    struct Fleet {
        root: Who,
        device: Who,
        impostor: Who,
        grant: Value,
    }

    fn fleet() -> Fleet {
        let (root, device, impostor) =
            (web_party(31, "root.example"), key_party(32), key_party(33));
        let grant = sign(
            &root,
            intent(
                "read",
                "calendar",
                "https://cal.example/team",
                json!({"delegatee": device.did, "rate": {"limit": 10, "window": "PT1H"}}),
            ),
            "urn:uuid:00000000-0000-4000-8000-000000000001",
        );
        Fleet {
            root,
            device,
            impostor,
            grant,
        }
    }

    fn leaf_by(
        f: &Fleet,
        who: &Who,
        action: &str,
        target: &str,
        resource: &str,
        extra: Value,
    ) -> Value {
        let _ = f;
        sign(
            who,
            intent(action, target, resource, extra),
            "urn:uuid:00000000-0000-4000-8000-000000000002",
        )
    }

    #[test]
    fn a_narrowing_chain_verifies_and_returns_the_leaf() {
        let f = fleet();
        let leaf = leaf_by(
            &f,
            &f.device,
            "read",
            "calendar",
            "https://cal.example/team/1",
            json!({}),
        );
        let r = check(&[f.grant.clone(), leaf.clone()], &roots(&[&f.root]), &[]);
        assert!(r.ok, "{:?}", r.reason);
        assert_eq!(r.root_did.as_deref(), Some("did:web:root.example"));
        assert_eq!(r.leaf, Some(leaf));
        assert_eq!(r.reason, None);
        assert_eq!(r.to_json()["ok"], json!(true));
    }

    #[test]
    fn widening_steps_are_refused_with_the_reference_text() {
        let f = fleet();
        let roots = roots(&[&f.root]);
        let cases = [
            (
                leaf_by(&f, &f.device, "write", "calendar", "https://cal.example/team", json!({})),
                "link 0: action 'write' is not within the granted 'read'",
            ),
            (
                leaf_by(&f, &f.device, "read", "mail", "https://cal.example/team", json!({})),
                "link 0: target 'mail' is not within the granted 'calendar'",
            ),
            (
                leaf_by(&f, &f.device, "read", "calendar", "https://cal.example/other", json!({})),
                "link 0: resource 'https://cal.example/other' is not within the granted 'https://cal.example/team'",
            ),
            (
                leaf_by(
                    &f,
                    &f.device,
                    "read",
                    "calendar",
                    "https://cal.example/team",
                    json!({"rate": {"limit": 100, "window": "PT1H"}}),
                ),
                "link 0: rate {'limit': 100, 'window': 'PT1H'} is not within the granted {'limit': 10, 'window': 'PT1H'}",
            ),
            (
                // A float is quoted the way Python's repr writes it.
                leaf_by(
                    &f,
                    &f.device,
                    "read",
                    "calendar",
                    "https://cal.example/team",
                    json!({"rate": {"limit": 2.5e-05, "window": "PT1H"}}),
                ),
                "link 0: rate {'limit': 2.5e-05, 'window': 'PT1H'} is not within the granted {'limit': 10, 'window': 'PT1H'}",
            ),
            (
                leaf_by(&f, &f.device, "read", "calendar", "https://cal.example/team", json!({"rate": null})),
                "link 0: rate None is not within the granted {'limit': 10, 'window': 'PT1H'}",
            ),
            (
                leaf_by(&f, &f.device, "read", "calendar", "https://cal.example/../x", json!({})),
                "link 0: resource 'https://cal.example/../x' is not within the granted 'https://cal.example/team'",
            ),
        ];
        for (leaf, want) in cases {
            assert_eq!(reason(check(&[f.grant.clone(), leaf], &roots, &[])), want);
        }
        // A list of actions is a set: one outside the grant is refused.
        let mut body = crate::credentials::build_vouch_credential(&opts(
            &f.device,
            intent("read", "calendar", "https://cal.example/team", json!({})),
            "urn:uuid:00000000-0000-4000-8000-000000000003",
            (FROM, UNTIL),
            None,
        ))
        .unwrap();
        body["credentialSubject"]["intent"]["action"] = json!(["read", "delete"]);
        let both_actions =
            crate::data_integrity::sign(&body, &f.device.seed, &proof(&f.device)).unwrap();
        assert_eq!(
            reason(check(&[f.grant.clone(), both_actions], &roots, &[])),
            "link 0: action ['read', 'delete'] is not within the granted 'read'"
        );
    }

    #[test]
    fn the_issuer_is_a_string_the_first_of_a_list_or_an_object_id() {
        // The reference's _issuer_of, shape by shape.
        for (issuer, expected) in [
            (json!("did:web:a"), Some("did:web:a")),
            (json!(["did:web:a", "did:web:b"]), Some("did:web:a")),
            (json!({"id": "did:web:a", "name": "x"}), Some("did:web:a")),
            (json!([]), None),
            (json!([{"id": "did:web:a"}]), None),
            (json!([""]), None),
            (json!([["did:web:a"]]), None),
            (json!([5]), None),
            (json!({"id": 5}), None),
            (json!({"id": ""}), None),
            (json!({"id": ["did:web:a"]}), None),
            (json!({}), None),
            (json!(""), None),
            (json!(5), None),
            (json!(true), None),
            (Value::Null, None),
        ] {
            let cred = json!({ "issuer": issuer });
            assert_eq!(issuer_of(&cred).as_deref(), expected, "{issuer}");
        }
        assert_eq!(issuer_of(&json!({})), None);
        // Anything that is no issuer is refused by name, wherever it sits.
        let f = fleet();
        let roots = roots(&[&f.root]);
        let good = leaf_by(
            &f,
            &f.device,
            "read",
            "calendar",
            "https://cal.example/team",
            json!({}),
        );
        for issuer in [json!(5), json!({"id": 5}), json!([]), json!({}), json!("")] {
            let mut grant = f.grant.clone();
            grant["issuer"] = issuer.clone();
            assert_eq!(
                reason(check(&[grant, good.clone()], &roots, &[])),
                "credential 0 has no issuer",
                "{issuer}"
            );
            let mut leaf = good.clone();
            leaf["issuer"] = issuer.clone();
            assert_eq!(
                reason(check(&[f.grant.clone(), leaf], &roots, &[])),
                "credential 1 has no issuer",
                "{issuer}"
            );
        }
    }

    #[test]
    fn omitted_dimensions_are_inherited_down_the_chain() {
        // The device passes a sub-grant on without a rate; the helper's action
        // asks for more than the root's rate.
        let f = fleet();
        let helper = key_party(34);
        let sub_intent = intent(
            "read",
            "calendar",
            "https://cal.example/team",
            json!({"delegatee": helper.did}),
        );
        let sub = sign_sub_grant(
            &opts(
                &f.device,
                sub_intent,
                "urn:uuid:00000000-0000-4000-8000-000000000004",
                (FROM, UNTIL),
                None,
            ),
            &grant_chain::grant_digest(&f.grant).unwrap(),
            &f.device.seed,
            &proof(&f.device),
        )
        .unwrap();
        let ok_leaf = sign(
            &helper,
            intent("read", "calendar", "https://cal.example/team", json!({})),
            "urn:uuid:00000000-0000-4000-8000-000000000005",
        );
        let roots = roots(&[&f.root]);
        let r = check(&[f.grant.clone(), sub.clone(), ok_leaf], &roots, &[]);
        assert!(r.ok, "{:?}", r.reason);
        let greedy = sign(
            &helper,
            intent(
                "read",
                "calendar",
                "https://cal.example/team",
                json!({"rate": {"limit": 11, "window": "PT1H"}}),
            ),
            "urn:uuid:00000000-0000-4000-8000-000000000006",
        );
        assert_eq!(
            reason(check(&[f.grant.clone(), sub.clone(), greedy], &roots, &[])),
            "link 1: rate {'limit': 11, 'window': 'PT1H'} is not within the granted None"
        );
        // A sub-grant presented under the wrong grant fails the binding rule first.
        let other = sign(
            &f.root,
            intent(
                "read",
                "calendar",
                "https://cal.example/team",
                json!({"delegatee": f.device.did}),
            ),
            "urn:uuid:00000000-0000-4000-8000-000000000007",
        );
        let leaf = sign(
            &helper,
            intent("read", "calendar", "https://cal.example/team", json!({})),
            "urn:uuid:00000000-0000-4000-8000-000000000008",
        );
        assert_eq!(
            reason(check(&[other, sub, leaf], &roots, &[])),
            "credential 1: delegation_parent_mismatch"
        );
    }

    #[test]
    fn the_walk_checks_delegatees_revocation_and_windows() {
        let f = fleet();
        let roots = roots(&[&f.root]);
        let good = leaf_by(
            &f,
            &f.device,
            "read",
            "calendar",
            "https://cal.example/team",
            json!({}),
        );
        let by_impostor = leaf_by(
            &f,
            &f.impostor,
            "read",
            "calendar",
            "https://cal.example/team",
            json!({}),
        );
        assert_eq!(
            reason(check(&[f.grant.clone(), by_impostor.clone()], &roots, &[])),
            format!(
                "link 0: child issuer '{}' is not the delegatee '{}' the parent authorized",
                f.impostor.did, f.device.did
            )
        );
        // A revoked device, a revoked credential, a revoked delegatee, a revoked root.
        assert_eq!(
            reason(check(
                &[f.grant.clone(), good.clone()],
                &roots,
                std::slice::from_ref(&f.device.did)
            )),
            format!("credential 1 issuer '{}' is revoked", f.device.did)
        );
        let leaf_id = good["id"].as_str().unwrap().to_string();
        assert_eq!(
            reason(check(
                &[f.grant.clone(), good.clone()],
                &roots,
                std::slice::from_ref(&leaf_id)
            )),
            format!("credential 1 ({leaf_id}) is revoked")
        );
        assert_eq!(
            reason(check(
                &[f.grant.clone(), by_impostor],
                &roots,
                std::slice::from_ref(&f.device.did)
            )),
            format!("link 0: delegatee '{}' is revoked", f.device.did)
        );
        assert_eq!(
            reason(check(
                &[f.grant.clone(), good.clone()],
                &roots,
                std::slice::from_ref(&f.root.did)
            )),
            "credential 0 issuer 'did:web:root.example' is revoked"
        );
        // A leaf that outlives its grant, or starts before it.
        let late = sign_window(
            &f.device,
            intent("read", "calendar", "https://cal.example/team", json!({})),
            "urn:uuid:00000000-0000-4000-8000-000000000009",
            (FROM, "2026-11-12T00:00:00Z"),
        );
        let early = sign_window(
            &f.device,
            intent("read", "calendar", "https://cal.example/team", json!({})),
            "urn:uuid:00000000-0000-4000-8000-000000000010",
            ("2026-11-09T00:00:00Z", UNTIL),
        );
        for leaf in [late, early] {
            assert_eq!(
                reason(check(&[f.grant.clone(), leaf], &roots, &[])),
                "link 0: child validity is outside the grant window"
            );
        }
        // A grant that names no delegatee.
        let no_delegatee = sign(
            &f.root,
            intent("read", "calendar", "https://cal.example/team", json!({})),
            "urn:uuid:00000000-0000-4000-8000-000000000011",
        );
        assert_eq!(
            reason(check(&[no_delegatee, good], &roots, &[])),
            "link 0 (grant by 'did:web:root.example') names no delegatee"
        );
    }

    #[test]
    fn trust_identity_and_proofs_come_first() {
        let f = fleet();
        let roots = roots(&[&f.root]);
        let good = leaf_by(
            &f,
            &f.device,
            "read",
            "calendar",
            "https://cal.example/team",
            json!({}),
        );
        assert_eq!(reason(check(&[], &roots, &[])), "empty chain");
        assert_eq!(
            reason(check(
                &[f.grant.clone(), good.clone()],
                &BTreeMap::new(),
                &[]
            )),
            "root issuer 'did:web:root.example' is not in trusted_roots"
        );
        // The root's key is the map's: a wrong one fails verification.
        let mut wrong = BTreeMap::new();
        wrong.insert(f.root.did.clone(), vec![7u8; 32]);
        assert_eq!(
            reason(check(&[f.grant.clone(), good.clone()], &wrong, &[])),
            "credential 0 failed verification"
        );
        let mut no_issuer = good.clone();
        no_issuer.as_object_mut().unwrap().remove("issuer");
        assert_eq!(
            reason(check(&[f.grant.clone(), no_issuer], &roots, &[])),
            "credential 1 has no issuer"
        );
        let mut tampered = good.clone();
        tampered["credentialSubject"]["intent"]["resource"] = json!("https://cal.example/team/2");
        assert_eq!(
            reason(check(&[f.grant.clone(), tampered], &roots, &[])),
            "credential 1 failed verification"
        );
        // A did:web device that is not in the map cannot be resolved offline.
        let web_device = web_party(35, "device.example");
        let web_grant = sign(
            &f.root,
            intent(
                "read",
                "calendar",
                "https://cal.example/team",
                json!({"delegatee": web_device.did}),
            ),
            "urn:uuid:00000000-0000-4000-8000-000000000012",
        );
        let web_leaf = leaf_by(
            &f,
            &web_device,
            "read",
            "calendar",
            "https://cal.example/team",
            json!({}),
        );
        assert_eq!(
            reason(check(&[web_grant.clone(), web_leaf.clone()], &roots, &[])),
            "credential 1 failed verification"
        );
        let both = super::tests::roots(&[&f.root, &web_device]);
        assert!(check(&[web_grant, web_leaf], &both, &[]).ok);
        // The binding rule runs before the trust check.
        let sub = sign_sub_grant(
            &opts(
                &f.device,
                intent(
                    "read",
                    "calendar",
                    "https://cal.example/team",
                    json!({"delegatee": f.impostor.did}),
                ),
                "urn:uuid:00000000-0000-4000-8000-000000000013",
                (FROM, UNTIL),
                None,
            ),
            &grant_chain::grant_digest(&f.grant).unwrap(),
            &f.device.seed,
            &proof(&f.device),
        )
        .unwrap();
        assert_eq!(
            reason(check(&[sub], &BTreeMap::new(), &[])),
            "credential 0: delegation_parent_mismatch"
        );
    }

    #[test]
    fn shape_and_binding_come_before_any_key() {
        let f = fleet();
        let roots = roots(&[&f.root]);
        let none = BTreeMap::new();
        let good = leaf_by(
            &f,
            &f.device,
            "read",
            "calendar",
            "https://cal.example/team",
            json!({}),
        );
        // A credential that is not a JSON object, wherever it sits, and before
        // the trust check.
        for (position, value) in [
            (0, json!(f.grant.to_string())),
            (1, Value::Null),
            (1, json!(["x"])),
            (2, json!(7)),
        ] {
            let mut creds = vec![f.grant.clone(), good.clone(), good.clone()];
            creds[position] = value;
            for r in [&roots, &none] {
                assert_eq!(
                    reason(check(&creds, r, &[])),
                    format!("credential {position} is not a JSON object")
                );
            }
        }
        // That check runs over every credential before the binding rule.
        let named = json!({"issuer": f.device.did,
                           "credentialSubject": {"parentGrantDigest": "uEiA"}});
        assert_eq!(
            reason(check(&[named, json!("x")], &roots, &[])),
            "credential 1 is not a JSON object"
        );
        // An older nested sub-grant made under another root's grant: refused
        // from its fields, with no key looked up (the roots are empty).
        let other = sign(
            &f.impostor,
            intent(
                "read",
                "calendar",
                "https://cal.example/team",
                json!({"delegatee": f.device.did}),
            ),
            "urn:uuid:00000000-0000-4000-8000-000000000020",
        );
        let link = |grant: &Value| {
            json!({"issuer": grant["issuer"], "subject": f.device.did,
                   "parentCredential": grant})
        };
        let nested = json!({"issuer": f.device.did, "credentialSubject": {
            "intent": {"action": "read", "delegatee": f.impostor.did},
            "delegationChain": [link(&other)]}});
        assert_eq!(
            reason(check(
                &[f.grant.clone(), nested.clone(), good.clone()],
                &none,
                &[]
            )),
            "credential 1: delegation_parent_mismatch"
        );
        // An action that embeds a chain ending somewhere else.
        let elsewhere = json!({"issuer": f.device.did, "credentialSubject": {
            "intent": {"action": "read"}, "delegationChain": [link(&other)]}});
        assert_eq!(
            reason(check(&[f.grant.clone(), elsewhere], &none, &[])),
            "credential 1: delegation_parent_mismatch"
        );
        // Binding fields of the wrong shape.
        for subject in [
            json!({"delegationChain": null}),
            json!({"delegationChain": {}}),
            json!({"parentGrantDigest": null}),
            json!({"parentGrantDigest": grant_chain::grant_digest(&f.grant).unwrap(),
                   "delegationChain": [link(&f.grant)]}),
        ] {
            let sub = json!({"issuer": f.device.did, "credentialSubject": subject});
            assert_eq!(
                reason(check(&[f.grant.clone(), sub, good.clone()], &none, &[])),
                "credential 1: malformed_delegation"
            );
        }
    }

    #[test]
    fn a_post_quantum_root_grant_needs_its_mldsa_key() {
        let f = fleet();
        let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
        let body = crate::credentials::build_vouch_credential(&opts(
            &f.root,
            intent(
                "read",
                "calendar",
                "https://cal.example/team",
                json!({"delegatee": f.device.did}),
            ),
            "urn:uuid:00000000-0000-4000-8000-000000000014",
            (FROM, UNTIL),
            None,
        ))
        .unwrap();
        let dual = hybrid::sign_dual(
            &body,
            &f.root.seed,
            &ml,
            &format!("{}#key-1", f.root.did),
            &format!("{}#mldsa", f.root.did),
            FROM,
        )
        .unwrap();
        let good = leaf_by(
            &f,
            &f.device,
            "read",
            "calendar",
            "https://cal.example/team",
            json!({}),
        );
        assert_eq!(
            reason(check(
                &[dual.clone(), good.clone()],
                &roots(&[&f.root]),
                &[]
            )),
            "credential 0 needs an ML-DSA-44 key"
        );
        // A trusted key that is not a usable Ed25519 key fails first, as in
        // the reference.
        let mut short = roots(&[&f.root]);
        for key in short.values_mut() {
            key.truncate(31);
        }
        assert_eq!(
            reason(check(&[dual, good], &short, &[])),
            "credential 0 failed verification"
        );
    }

    #[test]
    fn leaf_policy_and_status() {
        let f = fleet();
        let roots = roots(&[&f.root]);
        let good = leaf_by(
            &f,
            &f.device,
            "read",
            "calendar",
            "https://cal.example/team/1",
            json!({}),
        );
        let creds = [f.grant.clone(), good.clone()];
        let with = |action: Option<&str>, target: Option<&str>, resource: Option<&str>| {
            verify_delegated_chain(
                &creds,
                &FleetOptions {
                    trusted_roots: &roots,
                    revoked: &[],
                    now_iso: NOW,
                    clock_skew_seconds: 30,
                    require_action: action,
                    require_target: target,
                    require_resource: resource,
                    check_status: true,
                    status_lists: None,
                },
            )
        };
        assert!(
            with(
                Some("read"),
                Some("calendar"),
                Some("https://cal.example/team/1")
            )
            .ok
        );
        for (r, want) in [
            (
                with(Some("write"), None, None),
                "leaf intent.action != 'write'",
            ),
            (
                with(None, Some("mail"), None),
                "leaf intent.target != 'mail'",
            ),
            (
                with(None, None, Some("https://cal.example/team")),
                "leaf intent.resource != 'https://cal.example/team'",
            ),
        ] {
            assert!(!r.ok);
            assert_eq!(r.leaf.as_ref(), Some(&good));
            assert_eq!(r.root_did, None);
            assert_eq!(r.reason.as_deref(), Some(want));
        }
        // A grant that carries a status entry: refused with no status lists
        // (offline), accepted when the status check is turned off.
        let status = json!({"id": "https://status.example/1#5", "type": "BitstringStatusListEntry",
            "statusPurpose": "revocation", "statusListIndex": "5",
            "statusListCredential": "https://status.example/1"});
        let mut o = opts(
            &f.root,
            intent(
                "read",
                "calendar",
                "https://cal.example/team",
                json!({"delegatee": f.device.did}),
            ),
            "urn:uuid:00000000-0000-4000-8000-000000000015",
            (FROM, UNTIL),
            None,
        );
        o.credential_status = Some(status);
        let with_status = sign_vouch_credential(&o, &f.root.seed, &proof(&f.root)).unwrap();
        let creds = [with_status, good];
        let base = FleetOptions {
            trusted_roots: &roots,
            revoked: &[],
            now_iso: NOW,
            clock_skew_seconds: 30,
            require_action: None,
            require_target: None,
            require_resource: None,
            check_status: true,
            status_lists: None,
        };
        assert_eq!(
            verify_delegated_chain(&creds, &base).reason.as_deref(),
            Some("credential 0 failed verification")
        );
        let empty = Map::new();
        let listed = FleetOptions {
            status_lists: Some(&empty),
            ..base
        };
        assert_eq!(
            verify_delegated_chain(&creds, &listed).reason.as_deref(),
            Some("credential 0 failed verification")
        );
        let unchecked = FleetOptions {
            check_status: false,
            ..base
        };
        assert!(verify_delegated_chain(&creds, &unchecked).ok);
    }

    #[test]
    fn embedded_chains_start_at_the_fleet_roots() {
        // A leaf that carries the chain above it (signed under the grant)
        // verifies with the fleet's root as its trusted start and the map's
        // key for the did:web root grant.
        let f = fleet();
        let leaf_intent = intent("read", "calendar", "https://cal.example/team", json!({}));
        let links =
            grant_chain::check_grant_chain(std::slice::from_ref(&f.grant), &leaf_intent).unwrap();
        let leaf = sign_vouch_credential(
            &opts(
                &f.device,
                leaf_intent,
                "urn:uuid:00000000-0000-4000-8000-000000000016",
                (FROM, UNTIL),
                Some(links),
            ),
            &f.device.seed,
            &proof(&f.device),
        )
        .unwrap();
        assert!(check(&[f.grant.clone(), leaf.clone()], &roots(&[&f.root]), &[]).ok);
        // A different fleet root is not this chain's start.
        let other = web_party(36, "other.example");
        let mut two = roots(&[&f.root]);
        two.insert(other.did.clone(), public(&other));
        assert!(check(&[f.grant.clone(), leaf.clone()], &two, &[]).ok);
        let mut wrong_key = roots(&[&f.root]);
        wrong_key.insert(f.root.did.clone(), public(&other));
        assert_eq!(
            reason(check(&[f.grant.clone(), leaf], &wrong_key, &[])),
            "credential 0 failed verification"
        );
    }

    #[test]
    fn revocation_candidates_cover_every_identifier_asked_about() {
        let f = fleet();
        let good = leaf_by(
            &f,
            &f.device,
            "read",
            "calendar",
            "https://cal.example/team",
            json!({}),
        );
        assert_eq!(
            revocation_candidates(&[f.grant.clone(), good]),
            vec![
                "did:web:root.example".to_string(),
                "urn:uuid:00000000-0000-4000-8000-000000000001".to_string(),
                f.device.did.clone(),
                "urn:uuid:00000000-0000-4000-8000-000000000002".to_string(),
            ]
        );
        assert!(
            revocation_candidates(&[json!("x"), json!({"issuer": ["did:web:a"]})])
                .contains(&"did:web:a".to_string())
        );
    }
}