vouch-core 4.2.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
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
//! Delegation links and time-bound chain validation.
//!
//! A delegation link carries an issuer, subject, intent, and an optional
//! validity window (Specification 9.2). Time-bound validation enforces that each
//! link's window is within its parent's (time attenuation, 9.3 step 6) and that
//! the current instant is within the narrowest link's window. The full v1.7
//! capability-attenuation rule across the other dimensions lives with the SDKs;
//! this core provides the link structure plus the deterministic temporal checks.

#[allow(unused_imports)]
use crate::prelude::*;

use alloc::collections::BTreeMap;

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

use crate::attenuation;
use crate::data_integrity;
use crate::error::{CoreError, Result};
use crate::grant_chain;
use crate::hybrid;
use crate::multikey;
use crate::time::{check_clock_skew, parse_protocol_time_ns, window_state_ns, WindowState};

/// Inputs for one delegation link.
#[derive(Debug, Clone)]
pub struct DelegationLinkInput {
    pub issuer: String,
    pub subject: String,
    pub intent: Value,
    pub valid_from: Option<String>,
    pub valid_until: Option<String>,
    pub parent_proof_value: Option<String>,
}

/// Build a delegation link object (field order matches the SDK).
pub fn build_delegation_link(input: &DelegationLinkInput) -> Value {
    crate::nesting::deep_guard!(Value::Null; input);
    let mut link = Map::new();
    link.insert("issuer".into(), json!(input.issuer));
    link.insert("subject".into(), json!(input.subject));
    link.insert("intent".into(), input.intent.clone());
    if let Some(vf) = &input.valid_from {
        link.insert("validFrom".into(), json!(vf));
    }
    if let Some(vu) = &input.valid_until {
        link.insert("validUntil".into(), json!(vu));
    }
    if let Some(pp) = &input.parent_proof_value {
        link.insert("parentProofValue".into(), json!(pp));
    }
    Value::Object(link)
}

/// A link's window bound: absent is open, a protocol-time string is parsed,
/// and anything else (null, a number, an object) is an error.
fn link_bound(obj: &Map<String, Value>, key: &str) -> Result<Option<i128>> {
    match obj.get(key) {
        None => Ok(None),
        Some(Value::String(s)) => Ok(Some(parse_protocol_time_ns(s)?)),
        Some(_) => Err(CoreError::Json(format!(
            "delegation link {key} must be a time string"
        ))),
    }
}

fn link_window(link: &Value) -> Result<(Option<i128>, Option<i128>)> {
    let obj = link
        .as_object()
        .ok_or_else(|| CoreError::Json("delegation link must be an object".into()))?;
    Ok((
        link_bound(obj, "validFrom")?,
        link_bound(obj, "validUntil")?,
    ))
}

/// Validate the time-bound rule over a chain ordered root -> leaf. Every
/// link's window must sit inside the window of EVERY link above it (the
/// running intersection, so a middle link with no window does not detach the
/// leaf from the root's window), no window may be inverted, and `now_iso` must
/// fall inside the intersection of all the windows (allowing the skew).
/// Returns Ok(true) if the chain is time-valid. Errors on a bound that is not a
/// time string, a malformed time, or a skew outside 0..120 seconds.
pub fn verify_chain_time_bound(
    chain: &[Value],
    now_iso: &str,
    clock_skew_seconds: i64,
) -> Result<bool> {
    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); chain);
    let skew = check_clock_skew(clock_skew_seconds)?;
    let now = parse_protocol_time_ns(now_iso)?;
    let mut eff_from: Option<i128> = None;
    let mut eff_until: Option<i128> = None;

    for link in chain {
        let (vf, vu) = link_window(link)?;
        if let (Some(f), Some(u)) = (vf, vu) {
            if f > u {
                return Ok(false); // inverted window
            }
        }
        if let (Some(f), Some(ef)) = (vf, eff_from) {
            if f < ef {
                return Ok(false); // starts before an ancestor
            }
        }
        if let (Some(u), Some(eu)) = (vu, eff_until) {
            if u > eu {
                return Ok(false); // ends after an ancestor
            }
        }
        if let Some(f) = vf {
            eff_from = Some(eff_from.map_or(f, |cur| cur.max(f)));
        }
        if let Some(u) = vu {
            eff_until = Some(eff_until.map_or(u, |cur| cur.min(u)));
        }
    }
    Ok(window_state_ns(now, eff_from, eff_until, skew) == WindowState::Ok)
}

// ---------------------------------------------------------------------------
// Delegation chain verification (Specification 9.3)
// ---------------------------------------------------------------------------
//
// A faithful port of `vouch.verifier.verify_delegation_chain` (Python is the
// reference). Every step and reason code matches it exactly; the shared vectors
// in `test-vectors/delegation-chain/vector.json` are the contract.

/// Map a signed Vouch credential onto the six-dimension link shape that
/// `attenuation::non_expansion` compares: action / target / resource from
/// `credentialSubject.intent`, time from `validFrom` / `validUntil`, rate and
/// policy from `intent.rate` / `intent.policy`, subject from `intent.delegatee`.
pub fn capability_view(credential: &Value, include_time: bool) -> Value {
    crate::nesting::deep_guard!(Value::Null; credential);
    let intent = credential
        .get("credentialSubject")
        .and_then(|s| s.get("intent"))
        .and_then(|i| i.as_object())
        .cloned()
        .unwrap_or_default();
    let mut view = Map::new();
    view.insert(
        "issuer".into(),
        issuer_did(credential)
            .map(Value::String)
            .unwrap_or(Value::Null),
    );
    view.insert(
        "subject".into(),
        intent.get("delegatee").cloned().unwrap_or(Value::Null),
    );
    let mut dims = Map::new();
    for k in ["action", "target", "resource", "amount"] {
        if let Some(v) = intent.get(k) {
            dims.insert(k.into(), v.clone());
        }
    }
    view.insert("intent".into(), Value::Object(dims));
    if include_time {
        for k in ["validFrom", "validUntil"] {
            if let Some(v) = credential.get(k) {
                view.insert(k.into(), v.clone());
            }
        }
    }
    for k in ["rate", "policy"] {
        if let Some(v) = intent.get(k) {
            view.insert(k.into(), v.clone());
        }
    }
    Value::Object(view)
}

/// The issuer DID of a grant or credential: the `issuer` string, or the `id` of
/// an issuer object. An array or any other shape has no issuer.
fn issuer_did(credential: &Value) -> Option<String> {
    crate::credentials::issuer_did(credential).map(String::from)
}

/// The Ed25519 key of a grant issuer: from the caller's map, else (for a
/// `did:key`) the key the DID encodes. For a `did:key` issuer a key in the
/// caller's map must equal the DID's own key, and a `did:key` that does not
/// decode resolves to nothing.
fn resolve_chain_key(did: &str, root_keys: &BTreeMap<String, Vec<u8>>) -> Option<Vec<u8>> {
    let from_did = match did.strip_prefix("did:key:") {
        Some(mk) => {
            let decoded = multikey::decode(mk).ok()?;
            if decoded.algorithm != "Ed25519" {
                return None;
            }
            Some(decoded.raw_key)
        }
        None => None,
    };
    // A key the caller named that the strict Ed25519 rules refuse is no key
    // (it stays the only key named for that DID).
    let given = root_keys.get(did);
    if given.is_some_and(|k| crate::keys::strict_verifying_key(k).is_err()) {
        return None;
    }
    match (given, from_did) {
        (Some(k), Some(d)) => (k == &d).then_some(d),
        (Some(k), None) => Some(k.clone()),
        (None, d) => d,
    }
}

/// The keys a grant's signature is checked with.
struct GrantIssuerKeys {
    ed25519: Vec<u8>,
    mldsa44: Option<Vec<u8>>,
    slhdsa128: Option<Vec<u8>>,
    /// The proofs the issuer's document requires on its grant: one for each
    /// post-quantum assertion key it publishes.
    requires: hybrid::Required,
}

/// A grant issuer's keys, in the reference's order: the caller's key for the
/// DID (`grant_keys`) or its did:key first; else, for a did:webvh issuer
/// whose log the caller gave (`opts.grant_logs`), the keys the latest
/// verified state lists for the verificationMethods the grant's proof names.
/// A post-quantum key the caller gave (`opts.mldsa_keys`,
/// `opts.slhdsa_keys`, a pinned key or a key resolver's answer) comes before
/// the state's, and makes that suite's proof required on the grant, exactly
/// as a key the issuer's document publishes does. None when no Ed25519 key
/// is found.
fn grant_issuer_keys(
    issuer: &str,
    grant: &Value,
    grant_keys: &BTreeMap<String, Vec<u8>>,
    opts: &ChainOptions,
) -> Option<GrantIssuerKeys> {
    // A post-quantum key known for the grant issuer is a key whose proof the
    // grant must carry: otherwise it could be stripped, and the grant would
    // stand on its Ed25519 proof alone. An unusable answer (an empty key)
    // keeps the requirement and checks nothing, so the grant is refused.
    let given_requires = hybrid::Required {
        post_quantum: false,
        mldsa44: opts.mldsa_keys.is_some_and(|m| m.contains_key(issuer)),
        slhdsa128: opts.slhdsa_keys.is_some_and(|m| m.contains_key(issuer)),
    };
    let given_mldsa = opts
        .mldsa_keys
        .and_then(|m| m.get(issuer))
        .filter(|k| !k.is_empty())
        .cloned();
    let given_slhdsa = opts
        .slhdsa_keys
        .and_then(|m| m.get(issuer))
        .filter(|k| !k.is_empty())
        .cloned();
    if let Some(ed25519) = resolve_chain_key(issuer, grant_keys) {
        return Some(GrantIssuerKeys {
            ed25519,
            mldsa44: given_mldsa,
            slhdsa128: given_slhdsa,
            requires: given_requires,
        });
    }
    if grant_keys.contains_key(issuer) {
        return None;
    }
    let fetched = opts
        .grant_documents
        .filter(|_| issuer.starts_with("did:web:") || crate::did_webvh::is_did_webvh(issuer))
        .and_then(|docs| docs.get(issuer));
    let state = match fetched {
        Some(document) => document.clone(),
        None if crate::did_webvh::is_did_webvh(issuer) => {
            opts.grant_logs?.resolve(issuer)?.ok()?.document
        }
        None => return None,
    };
    let methods = crate::credentials::proof_methods(grant);
    let keys = crate::did_document::proof_keys_for(
        &state,
        issuer,
        crate::did_document::ProofMethodRefs {
            ed25519: methods.ed25519.as_deref(),
            mldsa44: methods.mldsa44.as_deref(),
            slhdsa128: methods.slhdsa128.as_deref(),
        },
    );
    let published = keys.required();
    let requires = hybrid::Required {
        post_quantum: published.post_quantum,
        mldsa44: published.mldsa44 || given_requires.mldsa44,
        slhdsa128: published.slhdsa128 || given_requires.slhdsa128,
    };
    Some(GrantIssuerKeys {
        ed25519: keys.ed25519?,
        mldsa44: given_mldsa.or(keys.mldsa44),
        slhdsa128: given_slhdsa.or(keys.slhdsa128),
        requires,
    })
}

/// The proof value a link binds to its parent: the eddsa-jcs-2022 member of a
/// proof set, else the first proof value, else a single proof's value.
pub(crate) fn parent_proof_binding_value(grant: &Value) -> String {
    match grant.get("proof") {
        Some(Value::Array(items)) => {
            for p in items {
                if p.get("cryptosuite").and_then(|v| v.as_str())
                    == Some(data_integrity::CRYPTOSUITE_ID)
                {
                    return p
                        .get("proofValue")
                        .and_then(|v| v.as_str())
                        .unwrap_or("")
                        .to_string();
                }
            }
            for p in items {
                if let Some(v) = p.get("proofValue").and_then(|v| v.as_str()) {
                    if !v.is_empty() {
                        return v.to_string();
                    }
                }
            }
            String::new()
        }
        Some(Value::Object(p)) => p
            .get("proofValue")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string(),
        _ => String::new(),
    }
}

/// Check a grant's proof with the top-level proof rules.
///
/// Every member is an object with type "DataIntegrityProof", a known
/// cryptosuite, proofPurpose "assertionMethod", a verificationMethod of the
/// grant issuer's DID, a proofValue, a valid `created` and an `expires` (when
/// present) that has not passed. The shape is one `eddsa-jcs-2022` proof, or
/// a set of exactly one `eddsa-jcs-2022` member and one member of each
/// post-quantum suite it carries ([`hybrid::set_members`]). The earlier
/// composite proof is refused. The Ed25519 proof always verifies with `key`;
/// a post-quantum member is checked whenever its key is known, and when
/// `required` asks for anything post-quantum a single classical proof fails,
/// every suite it names must be in the set, and every post-quantum member
/// needs its key.
#[allow(clippy::too_many_arguments)]
fn verify_grant_proof(
    grant: &Value,
    issuer: &str,
    key: &[u8],
    mldsa_key: Option<&[u8]>,
    slhdsa_key: Option<&[u8]>,
    required: hybrid::Required,
    now: i128,
    skew: i128,
) -> bool {
    if !grant_proof_well_formed(grant, issuer, now, skew) {
        return false;
    }
    match grant.get("proof") {
        Some(Value::Object(_)) => {
            !required.any() && matches!(data_integrity::verify_proof(grant, key), Ok(true))
        }
        Some(Value::Array(items)) => {
            let Some(members) = hybrid::set_members(items) else {
                return false;
            };
            if !required.met_by(&members.suites()) {
                return false;
            }
            let verdict = if required.any() {
                hybrid::verify_set(grant, key, mldsa_key, slhdsa_key)
            } else {
                // Only the members whose key is known can be checked: they
                // must verify, the Ed25519 one always.
                hybrid::verify_set_known_keys(grant, key, mldsa_key, slhdsa_key)
            };
            matches!(verdict, Ok(true))
        }
        _ => false,
    }
}

/// The checks of [`verify_grant_proof`] that need no key: every member passes
/// the top-level proof rules, and the shape is one `eddsa-jcs-2022` proof or
/// a proof set ([`hybrid::set_members`]). The earlier composite proof, like
/// every other single proof object, is refused.
fn grant_proof_well_formed(grant: &Value, issuer: &str, now: i128, skew: i128) -> bool {
    let Some(proof) = grant.get("proof") else {
        return false;
    };
    let members: Vec<&Value> = match proof {
        Value::Array(items) => items.iter().collect(),
        other => vec![other],
    };
    if members.is_empty()
        || !members
            .iter()
            .all(|m| crate::credentials::proof_member_ok(m, issuer, now, skew))
    {
        return false;
    }
    match proof {
        Value::Object(_) => hybrid::Suite::of_proof(proof) == Some(hybrid::Suite::Eddsa),
        Value::Array(items) => hybrid::set_members(items).is_some(),
        _ => false,
    }
}

fn first_64(s: &str) -> String {
    s.chars().take(64).collect()
}

/// The reason a chain is refused when the caller named no trusted starting
/// point (trusted roots) for it.
pub const REASON_TRUSTED_ROOTS_REQUIRED: &str =
    "the chain's starting point is not trusted: pass trusted roots";

/// The reason a chain is refused by the verifier's resource guard or an
/// explicit budget the caller set.
pub const REASON_BUDGET_EXCEEDED: &str = "verifier_budget_exceeded";

/// An encoded delegation chain (its JCS form) larger than this is refused
/// before any signature is checked. This is a resource guard only: there is no
/// fixed depth limit, since a chain is limited by narrowing scope, never by its
/// number of links.
pub const MAX_CHAIN_BYTES: usize = attenuation::MAX_CHAIN_BYTES;

/// A trusted root as the caller wrote it, as a DID, read exactly as the Python
/// reference reads it ([`crate::did_web::normalize_root`]): a bare domain such
/// as "yourcompany.com" means "did:web:yourcompany.com" ("host:8443" means
/// "did:web:host%3A8443"); a full DID is used as it is. None when the root is
/// neither (an IP literal, a URL, a trailing dot, a bad port, ...).
pub fn root_did(root: &str) -> Option<String> {
    crate::did_web::normalize_root(root).ok()
}

/// True when the caller's trusted root names `issuer` exactly (see
/// [`root_did`]); a root that does not parse names nobody.
pub fn root_matches(root: &str, issuer: &str) -> bool {
    root_did(root).as_deref() == Some(issuer)
}

/// How a verifier checks an embedded delegation chain.
#[derive(Debug, Clone, Copy, Default)]
pub struct ChainOptions<'a> {
    /// The trusted starting points: the chain's first grant must be issued by
    /// one of them. A chain is refused when this is `None`
    /// ([`REASON_TRUSTED_ROOTS_REQUIRED`]); an empty list trusts nobody
    /// ("untrusted_principal"). A bare domain stands for its did:web
    /// ([`root_did`]).
    pub trusted_roots: Option<&'a [String]>,
    /// Ed25519 keys for grant issuers that are not `did:key` (a `did:key`
    /// issuer always resolves offline from the DID itself). A key here only
    /// resolves a grant's signature: it never makes its DID a trusted root.
    pub grant_keys: Option<&'a BTreeMap<String, Vec<u8>>>,
    /// ML-DSA-44 public keys by grant issuer DID. A grant whose issuer has a
    /// key here has its ML-DSA-44 member checked.
    pub mldsa_keys: Option<&'a BTreeMap<String, Vec<u8>>>,
    /// SLH-DSA-SHA2-128s public keys by grant issuer DID. A grant whose
    /// issuer has a key here has its SLH-DSA member checked.
    pub slhdsa_keys: Option<&'a BTreeMap<String, Vec<u8>>>,
    /// The SLH-DSA-SHA2-128s public key of the credential's own issuer (not
    /// of a grant issuer), for [`crate::credentials::verify_with_keys`]:
    /// giving it requires the SLH-DSA proof on that credential. The chain
    /// check does not read it.
    pub slhdsa128_key: Option<&'a [u8]>,
    /// did:webvh logs of grant issuers, fetched by the caller. A did:webvh
    /// grant issuer with no key in `grant_keys` takes its keys from the
    /// latest verified state of its log here, with the rules of
    /// [`crate::did_document::assertion_key`] for the verificationMethods the
    /// grant's proof names; a state that publishes a post-quantum assertion
    /// key requires that suite's proof on that grant. A log that is missing,
    /// refused or deactivated gives no key ("delegation_issuer_key_unresolved").
    /// The log is verified only when the chain check reaches a grant it signs.
    pub grant_logs: Option<&'a crate::did_webvh::LogSet>,
    /// DID documents of did:web and did:webvh grant issuers, fetched by the
    /// caller (for did:webvh, the latest verified state of its log). A grant
    /// issuer with no key in `grant_keys` takes its keys from its document
    /// here, before `grant_logs`, with the same rules.
    pub grant_documents: Option<&'a BTreeMap<String, Value>>,
    /// Require the post-quantum profile on every grant: each must carry a
    /// valid proof set (Ed25519 and at least one post-quantum proof), with
    /// the key of every post-quantum member known.
    pub require_pq: bool,
    /// The cryptosuites every grant's proofs must include (the verifier's
    /// `requireSuites` setting, which covers the credential and every grant
    /// above it). A grant without one of them is refused before any key is
    /// looked up, and a post-quantum suite named here needs its key, as
    /// `require_pq` does.
    pub require_suites: &'a [hybrid::Suite],
    /// An explicit depth budget chosen by the caller. `None` means no depth
    /// limit (there is no default one).
    pub max_depth: Option<usize>,
    /// Check only the links before this index (their grants, keys,
    /// signatures, bindings and windows) and answer None when they pass. A
    /// host that looks keys up one grant at a time asks this before it
    /// looks up the next grant issuer's key, so a DID that no verified
    /// grant named is never looked up.
    pub through_link: Option<usize>,
}

/// Verify a credential's embedded `delegationChain`. Returns `None` when the
/// chain is valid (or absent), otherwise the reason code.
///
/// `root_keys` supplies Ed25519 keys for non-`did:key` grant issuers (for a
/// `did:key` issuer it must equal the DID's own key); `root_dids` is the set of
/// trusted root DIDs the chain must start from. A credential that carries a
/// chain is refused when `root_dids` is `None`, and an empty list trusts
/// nobody. See [`verify_delegation_chain_with`] for every option.
pub fn verify_delegation_chain(
    credential: &Value,
    now_iso: &str,
    clock_skew_seconds: i64,
    root_keys: &BTreeMap<String, Vec<u8>>,
    root_dids: Option<&[String]>,
) -> Option<String> {
    crate::nesting::deep_guard!(Some(crate::nesting::TOO_DEEP.into()); credential);
    let opts = ChainOptions {
        trusted_roots: root_dids,
        grant_keys: Some(root_keys),
        ..Default::default()
    };
    verify_delegation_chain_with(credential, now_iso, clock_skew_seconds, &opts)
}

/// The chain checks that need no key, in the reference's order: the
/// credential's own binding fields, the size guard and any depth budget, the
/// trusted roots, and the link fields alone (each link continues the one
/// before it, the last names the credential's issuer, the chain starts at a
/// trusted root, and every grant is bound to the grant before it). The
/// reason to refuse, or None (also for a credential with no chain). A host
/// runs this before it asks for any key or fetches any document.
pub fn chain_links_problem(
    credential: &Value,
    now_iso: &str,
    clock_skew_seconds: i64,
    opts: &ChainOptions,
) -> Option<String> {
    crate::nesting::deep_guard!(Some(crate::nesting::TOO_DEEP.into()); credential, opts);
    let malformed = || Some("malformed_delegation".to_string());
    if !credential.is_object() {
        return malformed();
    }
    // The credential's own binding fields: a present delegationChain must be
    // a list and a present parentGrantDigest a string (null, {}, "", 0 or
    // false is malformed, never absent, D29), never both a digest and a chain.
    if let Some(reason) = grant_chain::binding_fields_problem(&credential["credentialSubject"]) {
        return Some(reason.into());
    }
    let chain_value = match credential
        .get("credentialSubject")
        .and_then(|s| s.get("delegationChain"))
    {
        None => return None,
        Some(Value::Array(a)) if a.is_empty() => return None,
        Some(v @ Value::Array(_)) => v,
        // Refused above: a delegationChain that is not a list.
        Some(_) => return malformed(),
    };
    let chain = chain_value.as_array().expect("checked above");
    match attenuation::chain_budget_exceeded(chain_value, opts.max_depth) {
        Ok(None) => {}
        Ok(Some(_)) => return Some(REASON_BUDGET_EXCEEDED.into()),
        Err(_) => return malformed(),
    }
    let Some(roots) = opts.trusted_roots else {
        return Some(REASON_TRUSTED_ROOTS_REQUIRED.into());
    };
    if check_clock_skew(clock_skew_seconds).is_err() || parse_protocol_time_ns(now_iso).is_err() {
        return malformed();
    }

    // Pre-filter from the link fields alone, before any key is resolved.
    for link in chain {
        let shape_ok = link.get("issuer").is_some_and(|v| v.is_string())
            && link.get("subject").is_some_and(|v| v.is_string());
        if !shape_ok {
            return malformed();
        }
    }
    for i in 1..chain.len() {
        if chain[i - 1].get("subject") != chain[i].get("issuer") {
            return Some("delegation_subject_issuer_mismatch".into());
        }
    }
    let last_subject = chain[chain.len() - 1]
        .get("subject")
        .and_then(|v| v.as_str());
    if last_subject.map(String::from) != issuer_did(credential) {
        return Some("delegation_subject_issuer_mismatch".into());
    }
    let root = chain[0]
        .get("issuer")
        .and_then(|v| v.as_str())
        .unwrap_or("");
    if !roots.iter().any(|d| root_matches(d, root)) {
        return Some("untrusted_principal".into());
    }
    // Every grant is bound to the grant before it (flat chains name it by
    // digest, older nested ones embed the links above them). A link without
    // its grant is left to the per-link checks, which report it as
    // delegation_link_unsigned.
    if chain
        .iter()
        .all(|link| matches!(link.get("parentCredential"), Some(Value::Object(_))))
    {
        if let Some(reason) = grant_chain::chain_binding_problem(chain) {
            return Some(reason.into());
        }
    }

    None
}

/// Verify a credential's embedded `delegationChain` under `opts`. Returns
/// `None` when the chain is valid (or absent), otherwise the reason code.
///
/// Order: first the credential's own binding fields
/// ([`grant_chain::binding_fields_problem`]: a present `delegationChain` is a
/// list, so null, `{}`, `""`, 0 or false is malformed; a present
/// `parentGrantDigest` is a string; and the credential does not carry a digest
/// together with a non-empty `delegationChain`; else "malformed_delegation").
/// Every verify path ([`crate::credentials::verify_with_keys`] and the entry
/// points over it) runs this, so it is the credential shape check for those
/// fields everywhere. A sub-grant with a string digest and no chain passes
/// here; its grant chain is checked apart. Then the size guard (1 MiB of JCS)
/// and any explicit depth
/// budget, the trusted roots, then a pre-filter from the link fields alone
/// (each link's issuer is the previous link's subject, and the first issuer
/// is a trusted root), all before any key is resolved or signature checked.
/// The pre-filter also checks that the last link's subject is the credential's
/// issuer and, when every link carries its grant as an object, that every
/// grant is bound to the grant before it
/// ([`grant_chain::chain_binding_problem`]: the first grant is a root grant,
/// and every later grant carries the digest of the grant before it in
/// `parentGrantDigest`, or embeds a chain equal to the links before it;
/// otherwise "delegation_parent_mismatch", or "malformed_delegation" for a
/// binding field of the wrong type or both bindings on one grant). Then each
/// link's signed grant: issuer, the proof's own fields and
/// shape (before any key is looked up), the key, the signatures (post-quantum
/// required with no ML-DSA-44 key known is "delegation_signature_invalid"),
/// parent binding, delegatee and window; and non-expansion across every
/// dimension.
pub fn verify_delegation_chain_with(
    credential: &Value,
    now_iso: &str,
    clock_skew_seconds: i64,
    opts: &ChainOptions,
) -> Option<String> {
    crate::nesting::deep_guard!(Some(crate::nesting::TOO_DEEP.into()); credential, opts);
    let malformed = || Some("malformed_delegation".to_string());
    if let Some(reason) = chain_links_problem(credential, now_iso, clock_skew_seconds, opts) {
        return Some(reason);
    }
    let chain = credential
        .get("credentialSubject")
        .and_then(|s| s.get("delegationChain"))
        .and_then(Value::as_array)
        .filter(|c| !c.is_empty())?;
    let (Ok(skew), Ok(now)) = (
        check_clock_skew(clock_skew_seconds),
        parse_protocol_time_ns(now_iso),
    ) else {
        return malformed();
    };

    let empty = BTreeMap::new();
    let grant_keys = opts.grant_keys.unwrap_or(&empty);

    let mut grants: Vec<&Value> = Vec::with_capacity(chain.len());
    for (index, link) in chain.iter().enumerate() {
        if opts.through_link == Some(index) {
            return None;
        }
        let link_issuer = link["issuer"].as_str().unwrap_or_default();
        let link_subject = link["subject"].as_str().unwrap_or_default();
        let Some(grant) = link.get("parentCredential").filter(|g| g.is_object()) else {
            return Some("delegation_link_unsigned".into());
        };
        if !matches!(
            grant.get("proof"),
            Some(Value::Object(_)) | Some(Value::Array(_))
        ) {
            return Some("delegation_link_unsigned".into());
        }
        let grant_issuer = issuer_did(grant);
        if grant_issuer.as_deref() != Some(link_issuer) {
            return Some("delegation_link_issuer_mismatch".into());
        }
        // The proof's own fields and shape are checked before any key is
        // looked up, so a malformed proof reads the same in every language.
        if !grant_proof_well_formed(grant, link_issuer, now, skew) {
            return Some("delegation_signature_invalid".into());
        }
        // The verifier's requireSuites setting holds for every grant too:
        // the grants are where the authority comes from.
        if !opts.require_suites.is_empty() {
            let carried = hybrid::proof_suites(grant);
            if opts.require_suites.iter().any(|s| !carried.contains(s)) {
                return Some("delegation_signature_invalid".into());
            }
        }
        let Some(keys) = grant_issuer_keys(link_issuer, grant, grant_keys, opts) else {
            return Some("delegation_issuer_key_unresolved".into());
        };
        // With post-quantum required and a post-quantum member's key not
        // known, the grant's proof cannot meet it: verify_grant_proof refuses
        // it.
        if !verify_grant_proof(
            grant,
            link_issuer,
            &keys.ed25519,
            keys.mldsa44.as_deref(),
            keys.slhdsa128.as_deref(),
            hybrid::Required {
                post_quantum: opts.require_pq
                    || keys.requires.post_quantum
                    || opts
                        .require_suites
                        .iter()
                        .any(|s| *s != hybrid::Suite::Eddsa),
                mldsa44: keys.requires.mldsa44
                    || opts.require_suites.contains(&hybrid::Suite::Mldsa44),
                slhdsa128: keys.requires.slhdsa128
                    || opts.require_suites.contains(&hybrid::Suite::Slhdsa128),
            },
            now,
            skew,
        ) {
            return Some("delegation_signature_invalid".into());
        }
        if let Some(bound) = link.get("parentProofValue") {
            // Present but null or not text is malformed, never "absent" (D29).
            let Some(bound) = bound.as_str() else {
                return malformed();
            };
            if bound != first_64(&parent_proof_binding_value(grant)) {
                return Some("delegation_link_tampered".into());
            }
        }
        let delegatee = grant
            .get("credentialSubject")
            .and_then(|s| s.get("intent"))
            .and_then(|i| i.get("delegatee"))
            .and_then(|d| d.as_str())
            .filter(|d| !d.is_empty());
        let Some(delegatee) = delegatee else {
            return Some("delegation_no_delegatee".into());
        };
        if delegatee != link_subject {
            return Some("delegation_subject_mismatch".into());
        }
        let window = (
            grant
                .get("validFrom")
                .and_then(|v| v.as_str())
                .map(parse_protocol_time_ns),
            grant
                .get("validUntil")
                .and_then(|v| v.as_str())
                .map(parse_protocol_time_ns),
        );
        let (Some(Ok(from)), Some(Ok(until))) = window else {
            return malformed();
        };
        match window_state_ns(now, Some(from), Some(until), skew) {
            WindowState::Ok => {}
            WindowState::Expired => return Some("delegation_expired".into()),
            WindowState::NotYetValid => return Some("delegation_not_yet_valid".into()),
            WindowState::Inverted => return malformed(),
        }
        grants.push(grant);
    }

    let last_subject = chain[chain.len() - 1]
        .get("subject")
        .and_then(|v| v.as_str());
    if last_subject.map(String::from) != issuer_did(credential) {
        return Some("delegation_subject_issuer_mismatch".into());
    }

    let mut views: Vec<Value> = grants.iter().map(|g| capability_view(g, true)).collect();
    views.push(capability_view(credential, true));
    if let Err(dim) = attenuation::first_broader_step(&views) {
        return Some(format!("scope_exceeds_parent:{}", dim.as_str()));
    }
    None
}

// What the no_std depth guard checks in the JSON these types carry.
crate::nesting::nested_fields!(DelegationLinkInput; intent);
crate::nesting::nested_fields!(ChainOptions<'_>; grant_documents);

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

    fn link(vf: &str, vu: &str) -> Value {
        build_delegation_link(&DelegationLinkInput {
            issuer: "did:web:a".into(),
            subject: "did:web:b".into(),
            intent: json!({"action":"read","target":"t","resource":"https://x/y"}),
            valid_from: Some(vf.into()),
            valid_until: Some(vu.into()),
            parent_proof_value: None,
        })
    }

    #[test]
    fn nested_windows_pass() {
        let chain = vec![
            link("2026-04-26T09:00:00Z", "2026-04-26T12:00:00Z"),
            link("2026-04-26T10:00:00Z", "2026-04-26T11:00:00Z"),
        ];
        assert!(verify_chain_time_bound(&chain, "2026-04-26T10:30:00Z", 30).unwrap());
    }

    #[test]
    fn child_wider_than_parent_fails() {
        let chain = vec![
            link("2026-04-26T10:00:00Z", "2026-04-26T11:00:00Z"),
            link("2026-04-26T09:00:00Z", "2026-04-26T12:00:00Z"), // wider
        ];
        assert!(!verify_chain_time_bound(&chain, "2026-04-26T10:30:00Z", 30).unwrap());
    }

    #[test]
    fn now_outside_leaf_window_fails() {
        let chain = vec![link("2026-04-26T10:00:00Z", "2026-04-26T11:00:00Z")];
        assert!(!verify_chain_time_bound(&chain, "2026-04-26T12:00:00Z", 30).unwrap());
    }

    #[test]
    fn a_window_less_middle_link_stays_bounded_by_the_root() {
        let root = json!({"issuer":"did:web:root","subject":"did:web:a","intent":{},
                          "validFrom":"2026-04-26T09:00:00Z","validUntil":"2026-04-26T11:00:00Z"});
        let mid = json!({"issuer":"did:web:a","subject":"did:web:b","intent":{}});
        let leaf = json!({"issuer":"did:web:b","subject":"did:web:c","intent":{},
                          "validFrom":"2026-04-26T09:00:00Z","validUntil":"2099-01-01T00:00:00Z"});
        let chain = vec![root.clone(), mid, leaf];
        assert!(!verify_chain_time_bound(&chain, "2030-01-01T00:00:00Z", 30).unwrap());
        assert!(!verify_chain_time_bound(&chain, "2026-04-26T10:00:00Z", 30).unwrap());
        // A bound that is not a time string is an error, not "no bound".
        let bad = json!({"issuer":"did:web:a","subject":"did:web:b","intent":{},
                         "validFrom":"2026-04-26T09:00:00Z","validUntil":0});
        assert!(verify_chain_time_bound(&[root.clone(), bad], "2026-04-26T10:00:00Z", 30).is_err());
        // Inverted, and skew out of range.
        let inv = link("2026-04-26T11:00:00Z", "2026-04-26T10:00:00Z");
        assert!(!verify_chain_time_bound(&[inv], "2026-04-26T10:30:00Z", 120).unwrap());
        assert!(verify_chain_time_bound(&[root], "2026-04-26T10:00:00Z", 121).is_err());
    }

    // --- Signed chains: roots, size guard, and the post-quantum profile ---

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

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

    fn vm(p: &Party) -> String {
        format!("{}#{}", p.did, p.did.trim_start_matches("did:key:"))
    }

    fn grant_body(from: &Party, to: &Party) -> Value {
        json!({
            "@context": ["https://www.w3.org/ns/credentials/v2"],
            "type": ["VerifiableCredential", "VouchCredential"],
            "issuer": from.did,
            "validFrom": "2026-04-26T09:00:00Z",
            "validUntil": "2026-04-26T12:00:00Z",
            "credentialSubject": {"id": from.did, "vouchVersion": "1.0", "intent": {
                "action": "read", "target": "t", "resource": "https://x/a", "delegatee": to.did}}
        })
    }

    fn leaf_credential(leaf: &Party, link: Value) -> Value {
        json!({
            "@context": ["https://www.w3.org/ns/credentials/v2"],
            "type": ["VerifiableCredential", "VouchCredential"],
            "issuer": leaf.did,
            "validFrom": "2026-04-26T10:00:00Z",
            "validUntil": "2026-04-26T10:05:00Z",
            "credentialSubject": {"id": leaf.did, "vouchVersion": "1.0",
                "intent": {"action": "read", "target": "t", "resource": "https://x/a/b"},
                "delegationChain": [link]}
        })
    }

    const NOW: &str = "2026-04-26T10:01:00Z";

    fn opts_with<'a>(roots: &'a [String]) -> ChainOptions<'a> {
        ChainOptions {
            trusted_roots: Some(roots),
            ..Default::default()
        }
    }

    #[test]
    fn signed_chain_needs_roots_and_respects_the_size_guard() {
        let (root, leaf) = (party(1), party(2));
        let grant = data_integrity::sign(
            &grant_body(&root, &leaf),
            &root.seed,
            &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
        )
        .unwrap();
        let link = json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant});
        let cred = leaf_credential(&leaf, link.clone());
        let roots = vec![root.did.clone()];
        assert_eq!(
            verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&roots)),
            None
        );
        assert_eq!(
            verify_delegation_chain_with(&cred, NOW, 30, &ChainOptions::default()),
            Some(REASON_TRUSTED_ROOTS_REQUIRED.into())
        );
        // An empty list trusts nobody.
        assert_eq!(
            verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&[])),
            Some("untrusted_principal".into())
        );
        // A bare domain means its did:web; it never matches a did:key root.
        let bare = vec![root.did.trim_start_matches("did:key:").to_string()];
        assert_eq!(
            verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&bare)),
            Some("untrusted_principal".into())
        );
        assert!(root_matches("yourcompany.com", "did:web:yourcompany.com"));
        assert!(!root_matches(
            "yourcompany.com",
            "did:web:yourcompany.com.evil"
        ));
        assert!(!root_matches("yourcompany.com", "did:key:yourcompany.com"));
        assert_eq!(
            root_did("yourcompany.com").as_deref(),
            Some("did:web:yourcompany.com")
        );
        assert_eq!(
            root_did("yourcompany.com:8443").as_deref(),
            Some("did:web:yourcompany.com%3A8443")
        );
        assert!(root_did("127.0.0.1").is_none());
        let other = vec!["did:web:someone-else".to_string()];
        assert_eq!(
            verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&other)),
            Some("untrusted_principal".into())
        );
        // No fixed depth limit, but an explicit budget still applies.
        let budget = ChainOptions {
            max_depth: Some(0),
            ..opts_with(&roots)
        };
        assert_eq!(
            verify_delegation_chain_with(&cred, NOW, 30, &budget),
            Some(REASON_BUDGET_EXCEEDED.into())
        );
        // More than 1 MiB encoded is refused before any signature is checked.
        let mut big = link;
        big["note"] = json!("a".repeat(MAX_CHAIN_BYTES));
        let cred = leaf_credential(&leaf, big);
        assert_eq!(
            verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&roots)),
            Some(REASON_BUDGET_EXCEEDED.into())
        );
    }

    #[test]
    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
    fn post_quantum_profile_requires_a_valid_dual_proof_on_every_grant() {
        let (root, leaf) = (party(3), party(4));
        let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
        let body = grant_body(&root, &leaf);
        let dual = hybrid::sign_dual(
            &body,
            &root.seed,
            &ml,
            &vm(&root),
            &format!("{}#mldsa", root.did),
            "2026-04-26T09:00:00Z",
        )
        .unwrap();
        let single = data_integrity::sign(
            &body,
            &root.seed,
            &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
        )
        .unwrap();
        let roots = vec![root.did.clone()];
        let mut mldsa_keys = BTreeMap::new();
        mldsa_keys.insert(root.did.clone(), ml.public_key().to_vec());
        let pq = ChainOptions {
            trusted_roots: Some(&roots),
            mldsa_keys: Some(&mldsa_keys),
            require_pq: true,
            ..Default::default()
        };
        let chain_of = |grant: &Value| {
            leaf_credential(
                &leaf,
                json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
            )
        };
        assert_eq!(
            verify_delegation_chain_with(&chain_of(&dual), NOW, 30, &pq),
            None
        );
        // A classical-only grant does not meet the post-quantum profile.
        assert_eq!(
            verify_delegation_chain_with(&chain_of(&single), NOW, 30, &pq),
            Some("delegation_signature_invalid".into())
        );
        // A broken ML-DSA member fails it too.
        let mut broken = dual.clone();
        broken["proof"][1]["proofValue"] = dual["proof"][0]["proofValue"].clone();
        assert_eq!(
            verify_delegation_chain_with(&chain_of(&broken), NOW, 30, &pq),
            Some("delegation_signature_invalid".into())
        );
        // Post-quantum required and no ML-DSA key known: the proof cannot meet it.
        let none = ChainOptions {
            mldsa_keys: None,
            ..pq
        };
        assert_eq!(
            verify_delegation_chain_with(&chain_of(&dual), NOW, 30, &none),
            Some("delegation_signature_invalid".into())
        );
        // Without the requirement the classical member is what is checked.
        assert_eq!(
            verify_delegation_chain_with(&chain_of(&dual), NOW, 30, &opts_with(&roots)),
            None
        );
        // Every member must be the issuer's own: a member naming another DID fails.
        let mut foreign = dual.clone();
        foreign["proof"][1]["verificationMethod"] = json!("did:web:someone-else#k");
        assert_eq!(
            verify_delegation_chain_with(&chain_of(&foreign), NOW, 30, &opts_with(&roots)),
            Some("delegation_signature_invalid".into())
        );
    }

    /// A one-link chain whose grant carries `proof`, signed over the grant body.
    fn chain_with_proof(root: &Party, leaf: &Party, proof: Value) -> Value {
        let mut grant = grant_body(root, leaf);
        grant["proof"] = proof;
        leaf_credential(
            leaf,
            json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
        )
    }

    fn eddsa_proof(root: &Party, leaf: &Party, opts: data_integrity::BuildProofOptions) -> Value {
        data_integrity::build_proof(&grant_body(root, leaf), &root.seed, &opts).unwrap()
    }

    #[test]
    fn grant_proofs_follow_the_top_level_rules() {
        let (root, leaf) = (party(5), party(6));
        let roots = vec![root.did.clone()];
        let o = opts_with(&roots);
        let base = || data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z");
        let good = eddsa_proof(&root, &leaf, base());
        let check = |proof: Value| {
            verify_delegation_chain_with(&chain_with_proof(&root, &leaf, proof), NOW, 30, &o)
        };
        assert_eq!(check(good.clone()), None);
        let invalid = Some("delegation_signature_invalid".to_string());
        // An expires that has passed, or is null (both inside the signed proof).
        for expires in [json!("2026-04-26T09:30:00Z"), Value::Null, json!(5)] {
            let mut p = good.clone();
            p["expires"] = expires.clone();
            let mut unsigned = p.clone();
            unsigned.as_object_mut().unwrap().remove("proofValue");
            let input =
                data_integrity::hash_data(&grant_body(&root, &leaf), unsigned.as_object().unwrap())
                    .unwrap();
            let sig = crate::keys::Ed25519KeyPair::from_seed(&root.seed).sign(&input);
            p["proofValue"] = json!(format!("z{}", bs58::encode(sig).into_string()));
            assert_eq!(check(p), invalid, "expires {expires}");
        }
        // A created that is not a time.
        let mut opts = base();
        opts.created = "yesterday".into();
        assert_eq!(check(eddsa_proof(&root, &leaf, opts)), invalid);
        // An unknown cryptosuite, a missing proofValue, a member that is not an object.
        let mut p = good.clone();
        p["cryptosuite"] = json!("some-unregistered-suite-2030");
        assert_eq!(check(p), invalid);
        let mut p = good.clone();
        p.as_object_mut().unwrap().remove("proofValue");
        assert_eq!(check(p), invalid);
        assert_eq!(check(json!([good.clone(), 7])), invalid);
        // A set is exactly one eddsa-jcs-2022 and one ML-DSA-44 member.
        assert_eq!(check(json!([good.clone()])), invalid);
        assert_eq!(check(json!([good.clone(), good.clone()])), invalid);
    }

    #[test]
    fn grant_issuer_is_a_did_string_or_id() {
        let (root, leaf) = (party(7), party(8));
        let roots = vec![root.did.clone()];
        let mut body = grant_body(&root, &leaf);
        body["issuer"] = json!([root.did.clone()]);
        let grant = data_integrity::sign(
            &body,
            &root.seed,
            &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
        )
        .unwrap();
        let cred = leaf_credential(
            &leaf,
            json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
        );
        assert_eq!(
            verify_delegation_chain_with(&cred, NOW, 30, &opts_with(&roots)),
            Some("delegation_link_issuer_mismatch".into())
        );
    }

    #[test]
    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
    fn a_known_mldsa_key_checks_the_grant_member() {
        let (root, leaf) = (party(9), party(10));
        let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
        let body = grant_body(&root, &leaf);
        let dual = hybrid::sign_dual(
            &body,
            &root.seed,
            &ml,
            &vm(&root),
            &format!("{}#mldsa", root.did),
            "2026-04-26T09:00:00Z",
        )
        .unwrap();
        let roots = vec![root.did.clone()];
        let mut keys = BTreeMap::new();
        keys.insert(root.did.clone(), ml.public_key().to_vec());
        let known = ChainOptions {
            trusted_roots: Some(&roots),
            mldsa_keys: Some(&keys),
            ..Default::default()
        };
        let link = |g: &Value| {
            leaf_credential(
                &leaf,
                json!({"issuer": root.did, "subject": leaf.did, "parentCredential": g}),
            )
        };
        assert_eq!(
            verify_delegation_chain_with(&link(&dual), NOW, 30, &known),
            None
        );
        // A broken ML-DSA-44 member fails once its key is known, PQ required or not.
        let mut broken = dual.clone();
        broken["proof"][1]["proofValue"] = dual["proof"][0]["proofValue"].clone();
        assert_eq!(
            verify_delegation_chain_with(&link(&broken), NOW, 30, &known),
            Some("delegation_signature_invalid".into())
        );
        // The earlier composite proof on a grant is refused, even with the
        // ML-DSA-44 key known: the post-quantum profile is the proof set only.
        let composite =
            hybrid::composite_for_tests(&body, &root.seed, &ml, &vm(&root), "2026-04-26T09:00:00Z");
        assert_eq!(
            verify_delegation_chain_with(&link(&composite), NOW, 30, &known),
            Some("delegation_signature_invalid".into())
        );
        assert_eq!(
            verify_delegation_chain_with(&link(&composite), NOW, 30, &opts_with(&roots)),
            Some("delegation_signature_invalid".into())
        );
    }

    #[test]
    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
    fn a_grant_may_carry_an_slhdsa_proof() {
        let (root, leaf) = (party(21), party(22));
        let ml = crate::pq::MlDsa44KeyPair::generate().unwrap();
        let slh = crate::slh::SlhDsa128KeyPair::generate().unwrap();
        let body = grant_body(&root, &leaf);
        let ed_vm = vm(&root);
        let sign = |with_ml: bool| {
            hybrid::sign_set(
                &body,
                &root.seed,
                &ed_vm,
                with_ml.then_some(hybrid::PqSigner {
                    key: &ml,
                    verification_method: &crate::issuance::mldsa44_verification_method(&ed_vm),
                }),
                Some(hybrid::PqSigner {
                    key: &slh,
                    verification_method: &crate::issuance::slhdsa128_verification_method(&ed_vm),
                }),
                "2026-04-26T09:00:00Z",
            )
            .unwrap()
        };
        let roots = vec![root.did.clone()];
        let ml_keys = BTreeMap::from([(root.did.clone(), ml.public_key().to_vec())]);
        let slh_keys = BTreeMap::from([(root.did.clone(), slh.public_key().to_vec())]);
        let link = |g: &Value| {
            leaf_credential(
                &leaf,
                json!({"issuer": root.did, "subject": leaf.did, "parentCredential": g}),
            )
        };
        let all = ChainOptions {
            trusted_roots: Some(&roots),
            mldsa_keys: Some(&ml_keys),
            slhdsa_keys: Some(&slh_keys),
            ..Default::default()
        };
        let slh_only = ChainOptions {
            mldsa_keys: None,
            ..all
        };
        let invalid = Some("delegation_signature_invalid".to_string());
        for with_ml in [true, false] {
            let grant = sign(with_ml);
            // A known ML-DSA-44 key makes that proof required: a grant
            // without it is refused, so the proof cannot be stripped.
            if !with_ml {
                assert_eq!(
                    verify_delegation_chain_with(&link(&grant), NOW, 30, &all),
                    invalid
                );
            }
            let all = if with_ml { all } else { slh_only };
            assert_eq!(
                verify_delegation_chain_with(&link(&grant), NOW, 30, &all),
                None
            );
            // Post-quantum required: every post-quantum member needs its key.
            let required = ChainOptions {
                require_pq: true,
                ..all
            };
            assert_eq!(
                verify_delegation_chain_with(&link(&grant), NOW, 30, &required),
                None
            );
            let no_slh = ChainOptions {
                slhdsa_keys: None,
                ..required
            };
            assert_eq!(
                verify_delegation_chain_with(&link(&grant), NOW, 30, &no_slh),
                invalid
            );
            // A broken SLH-DSA member fails once its key is known.
            let mut broken = grant.clone();
            let last = broken["proof"].as_array().unwrap().len() - 1;
            let value = broken["proof"][last]["proofValue"]
                .as_str()
                .unwrap()
                .to_string();
            let flipped = if value.ends_with('A') { "Q" } else { "A" };
            broken["proof"][last]["proofValue"] =
                json!(format!("{}{flipped}", &value[..value.len() - 1]));
            assert_eq!(
                verify_delegation_chain_with(&link(&broken), NOW, 30, &all),
                invalid
            );
        }
    }

    #[test]
    fn a_did_key_grant_issuer_keeps_its_own_key() {
        let (root, leaf, other) = (party(11), party(12), party(13));
        let grant = data_integrity::sign(
            &grant_body(&root, &leaf),
            &root.seed,
            &data_integrity::BuildProofOptions::new(vm(&root), "2026-04-26T09:00:00Z"),
        )
        .unwrap();
        let cred = leaf_credential(
            &leaf,
            json!({"issuer": root.did, "subject": leaf.did, "parentCredential": grant}),
        );
        let roots = vec![root.did.clone()];
        let mut keys = BTreeMap::new();
        keys.insert(
            root.did.clone(),
            crate::keys::Ed25519KeyPair::from_seed(&other.seed)
                .public_key()
                .to_vec(),
        );
        let pinned = ChainOptions {
            trusted_roots: Some(&roots),
            grant_keys: Some(&keys),
            ..Default::default()
        };
        assert_eq!(
            verify_delegation_chain_with(&cred, NOW, 30, &pinned),
            Some("delegation_issuer_key_unresolved".into())
        );
    }

    #[test]
    fn link_fields_are_checked_before_any_key() {
        // A chain from an untrusted start, or with a gap, is refused before the
        // (unresolvable) grant keys are looked at.
        let link = |iss: &str, sub: &str| {
            json!({"issuer": iss, "subject": sub,
                   "parentCredential": {"issuer": iss, "proof": {"type": "DataIntegrityProof"}}})
        };
        let cred = |chain: Value| json!({"issuer": "did:web:c", "credentialSubject": {"delegationChain": chain}});
        let roots = vec!["did:web:root".to_string()];
        assert_eq!(
            verify_delegation_chain_with(
                &cred(json!([link("did:web:other", "did:web:c")])),
                NOW,
                30,
                &opts_with(&roots)
            ),
            Some("untrusted_principal".into())
        );
        assert_eq!(
            verify_delegation_chain_with(
                &cred(json!([
                    link("did:web:root", "did:web:a"),
                    link("did:web:b", "did:web:c")
                ])),
                NOW,
                30,
                &opts_with(&roots)
            ),
            Some("delegation_subject_issuer_mismatch".into())
        );
        // The last link must name the credential's issuer, before any key.
        assert_eq!(
            verify_delegation_chain_with(
                &cred(json!([link("did:web:root", "did:web:other")])),
                NOW,
                30,
                &opts_with(&roots)
            ),
            Some("delegation_subject_issuer_mismatch".into())
        );
        // With a trusted, continuous chain, a bare proof is refused by its own
        // fields before any key is looked up.
        assert_eq!(
            verify_delegation_chain_with(
                &cred(json!([link("did:web:root", "did:web:c")])),
                NOW,
                30,
                &opts_with(&roots)
            ),
            Some("delegation_signature_invalid".into())
        );
        // null and other non-array chains are malformed, never "absent".
        for chain in [Value::Null, json!({}), json!(""), json!(0), json!(false)] {
            assert_eq!(
                verify_delegation_chain_with(&cred(chain.clone()), NOW, 30, &opts_with(&roots)),
                Some("malformed_delegation".into()),
                "{chain}"
            );
        }
        // The size guard runs before the roots check.
        let big =
            cred(json!([{"issuer": "x", "subject": "y", "pad": "a".repeat(MAX_CHAIN_BYTES)}]));
        assert_eq!(
            verify_delegation_chain_with(&big, NOW, 30, &ChainOptions::default()),
            Some(REASON_BUDGET_EXCEEDED.into())
        );
    }

    #[test]
    fn grant_binding_is_checked_before_any_key() {
        // did:web grant issuers with no keys known: anything that reached a key
        // lookup would be delegation_signature_invalid or key_unresolved.
        let grant = |iss: &str, sub: &str, extra: Value| {
            let mut g = json!({"issuer": iss, "proof": {"type": "DataIntegrityProof"},
                "credentialSubject": {"intent": {"delegatee": sub}}});
            for (k, v) in extra.as_object().unwrap() {
                g["credentialSubject"][k] = v.clone();
            }
            g
        };
        let link = |g: &Value| {
            json!({"issuer": g["issuer"], "subject": g["credentialSubject"]["intent"]["delegatee"],
                   "parentCredential": g})
        };
        let cred = |chain: Vec<Value>| json!({"issuer": "did:web:c", "credentialSubject": {"delegationChain": chain}});
        let roots = vec!["did:web:root".to_string()];
        let check = |chain: Vec<Value>| {
            verify_delegation_chain_with(&cred(chain), NOW, 30, &opts_with(&roots))
        };
        let g1 = grant("did:web:root", "did:web:a", json!({}));
        let digest = grant_chain::grant_digest(&g1).unwrap();
        let bound = grant(
            "did:web:a",
            "did:web:c",
            json!({ "parentGrantDigest": digest }),
        );
        let unbound = grant("did:web:a", "did:web:c", json!({}));
        // Bound: the per-link checks run and refuse the bare proof.
        assert_eq!(
            check(vec![link(&g1), link(&bound)]),
            Some("delegation_signature_invalid".into())
        );
        assert_eq!(
            check(vec![link(&g1), link(&unbound)]),
            Some("delegation_parent_mismatch".into())
        );
        // A root grant that names a parent (the chain above it cut off).
        let cut = grant(
            "did:web:root",
            "did:web:c",
            json!({ "parentGrantDigest": "uEiAAAA" }),
        );
        assert_eq!(
            check(vec![link(&cut)]),
            Some("delegation_parent_mismatch".into())
        );
        // A digest of the wrong type, or both bindings: malformed.
        for extra in [
            json!({ "parentGrantDigest": null }),
            json!({ "delegationChain": null }),
            json!({ "parentGrantDigest": digest, "delegationChain": [link(&g1)] }),
        ] {
            let g2 = grant("did:web:a", "did:web:c", extra.clone());
            assert_eq!(
                check(vec![link(&g1), link(&g2)]),
                Some("malformed_delegation".into()),
                "{extra}"
            );
        }
        // The pre-filter's earlier checks still come first.
        assert_eq!(
            verify_delegation_chain_with(
                &cred(vec![link(&g1), link(&unbound)]),
                NOW,
                30,
                &opts_with(&["did:web:other".to_string()])
            ),
            Some("untrusted_principal".into())
        );
        // A link without its grant skips the binding rule (which would call the
        // unbound second grant a mismatch) and is refused as unsigned.
        for missing in [None, Some(json!("grant")), Some(Value::Null)] {
            let mut first = link(&g1);
            match &missing {
                None => {
                    first.as_object_mut().unwrap().remove("parentCredential");
                }
                Some(v) => first["parentCredential"] = v.clone(),
            }
            assert_eq!(
                check(vec![first, link(&unbound)]),
                Some("delegation_link_unsigned".into()),
                "{missing:?}"
            );
        }
    }
}