vouch-core 3.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
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
//! Flat delegation chains: grant digests, grant chains, and the rule that binds
//! every grant to the grant above it.
//!
//! A port of `vouch/grant_chain.py` (Python is the reference). A grant made by
//! a delegatee (a sub-grant) does not copy the chain above it. It names its
//! direct parent grant by digest instead, in
//! `credentialSubject.parentGrantDigest`. The delegatee of a sub-grant is
//! handed a grant chain: a JSON array of grants, root first. A credential
//! signed under a grant chain carries one delegation link per grant
//! (`delegationChain`), so its size grows by one grant per hop and its JSON
//! nesting depth stays the same.
//!
//! The rules, the same in every language:
//!
//! * [`grant_digest`] is `"u"` followed by the base64url (no padding) encoding
//!   of the bytes `0x12 0x20` and the SHA-256 of the JCS form of the whole
//!   grant, proof included: a multibase, multihash SHA-256 value, the shape of
//!   VC 2.0 `digestMultibase`. Digests compare as exact strings.
//! * Binding fields ([`binding_fields_problem`]): a `parentGrantDigest` that is
//!   present must be a string, a `delegationChain` that is present must be a
//!   list, and one credential never carries a digest together with a non-empty
//!   `delegationChain`. Anything else is `malformed_delegation`. This holds for
//!   every grant in a chain, for every credential in a fleet chain, and for the
//!   credential being verified itself.
//! * Binding ([`chain_binding_problem`], checked by verifiers for every
//!   embedded chain and by [`check_grant_chain`] before signing): the first
//!   link's grant is a root grant (no digest, no embedded chain). Every later
//!   link's grant either carries the digest of the grant before it, or (the
//!   older nested form) embeds a chain that is JCS-equal to the links before it
//!   in the credential.
//! * Fleet chains ([`presented_chain_problem`], credentials presented one by
//!   one, root first): credential 0 names no parent. A later credential with a
//!   digest carries the digest of the credential before it; one with a
//!   non-empty `delegationChain` ends that chain with a link whose grant is
//!   JCS-equal to the credential before it.
//! * Signing ([`check_grant_chain`]): before a signer signs under a grant chain
//!   it checks the chain from its link fields: every grant signed and issued by
//!   a DID, each delegatee the next grant's issuer, every grant bound to the one
//!   before it, no grant broader than the one before it (time included), and
//!   every link copied from an older nested grant naming that grant's issuer
//!   and delegatee.
//!
//! The core has no signer, so the signing side is a set of pure functions. To
//! sign under a parent (a grant, or a grant chain): take
//! `grants = parent_grants(parent)`, check them with
//! `links = check_grant_chain(&grants, &intent)`, and check that the new intent
//! stays inside `chain_capability(&grants, false)`. A new grant (its intent
//! names a delegatee, [`is_grant_intent`]) is a bare sub-grant:
//! [`crate::credentials::build_sub_grant`] with the digest of the last grant.
//! Anything else carries `links` as its `delegationChain`. Hand the delegatee
//! of a new sub-grant [`grant_chain`]`(parent, sub_grant)`.

use std::fmt;

use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use serde_json::{Map, Value};
use sha2::{Digest, Sha256};

use crate::attenuation;
use crate::delegation;
use crate::error::CoreError;
use crate::jcs;

/// The reason a grant in a chain is not bound to the grant before it.
pub const REASON_PARENT_MISMATCH: &str = "delegation_parent_mismatch";
/// The reason a binding field is present but malformed, or cannot be hashed.
pub const REASON_MALFORMED: &str = "malformed_delegation";

/// The credentialSubject field where a sub-grant names its direct parent grant.
pub const PARENT_GRANT_DIGEST: &str = "parentGrantDigest";

/// The refusal when a single grant that names a parent grant is passed alone.
pub const NAMES_PARENT_GRANT: &str =
    "this grant names a parent grant; pass the whole grant chain (a list, root first)";

/// The multihash prefix of a SHA-256 digest: code 0x12, length 0x20 (32 bytes).
const MULTIHASH_SHA2_256: [u8; 2] = [0x12, 0x20];

/// A grant has no digest: it is not a JSON object. Verifiers report it as
/// `malformed_delegation`. (A `serde_json::Value` always has a JCS form, so
/// the reference's other cause, a value that is not plain JSON, cannot reach
/// this point: such input is refused when the JSON is parsed.)
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GrantDigestError(pub String);

impl fmt::Display for GrantDigestError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for GrantDigestError {}

impl From<GrantDigestError> for CoreError {
    fn from(e: GrantDigestError) -> Self {
        CoreError::Json(e.0)
    }
}

/// A grant chain refused before signing. The message is the reference's
/// refusal text, byte for byte.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GrantChainError(pub String);

impl fmt::Display for GrantChainError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for GrantChainError {}

impl From<GrantChainError> for CoreError {
    fn from(e: GrantChainError) -> Self {
        CoreError::Json(e.0)
    }
}

fn refused(msg: impl Into<String>) -> GrantChainError {
    GrantChainError(msg.into())
}

/// The digest of a grant, the value a sub-grant puts in
/// `credentialSubject.parentGrantDigest`:
/// `"u" + base64url_nopad(0x12 0x20 || SHA-256(JCS(grant)))`, over the whole
/// grant object, its proof (or proof set) included. The result is "u" and 46
/// base64url characters.
///
/// Errors when the grant is not a JSON object.
pub fn grant_digest(grant: &Value) -> Result<String, GrantDigestError> {
    if !grant.is_object() {
        return Err(GrantDigestError("a grant must be a JSON object".into()));
    }
    let mut multihash = Vec::with_capacity(34);
    multihash.extend_from_slice(&MULTIHASH_SHA2_256);
    multihash.extend_from_slice(&Sha256::digest(jcs::canonicalize(grant)));
    Ok(format!("u{}", URL_SAFE_NO_PAD.encode(multihash)))
}

/// `credentialSubject` when it is an object, else nothing (the reference reads
/// a missing or non-object subject as an empty one).
fn subject_of(grant: &Value) -> Option<&Map<String, Value>> {
    grant.get("credentialSubject").and_then(Value::as_object)
}

/// The shape of a credential's own binding fields, read from its
/// `credentialSubject`: None when they are well formed, otherwise
/// `malformed_delegation`.
///
/// - `parentGrantDigest` present and not a string: `malformed_delegation`;
/// - `delegationChain` present and not a list: `malformed_delegation`;
/// - a digest together with a non-empty `delegationChain`:
///   `malformed_delegation`.
///
/// A present null, number or object is malformed, never absent (D29). An
/// empty `delegationChain` is no chain. The verifiers apply this to the
/// credential they verify ([`crate::delegation::verify_delegation_chain_with`]
/// runs it first, on every verify path), to every grant in an embedded chain
/// and to every credential in a fleet chain.
///
/// `subject` is the credential's `credentialSubject`; anything that is not an
/// object carries no binding fields.
pub fn binding_fields_problem(subject: &Value) -> Option<&'static str> {
    // Anything that is not an object carries no binding fields.
    let subject = subject.as_object()?;
    let digest = subject.get(PARENT_GRANT_DIGEST);
    if digest.is_some_and(|d| !d.is_string()) {
        return Some(REASON_MALFORMED);
    }
    let chain = subject.get("delegationChain");
    if chain.is_some_and(|c| !c.is_array()) {
        return Some(REASON_MALFORMED);
    }
    if digest.is_some()
        && chain
            .and_then(Value::as_array)
            .is_some_and(|c| !c.is_empty())
    {
        return Some(REASON_MALFORMED);
    }
    None
}

/// A credential's `parentGrantDigest` and its `delegationChain` (empty when
/// absent), read once [`binding_fields_problem`] has passed.
fn bindings(cred: &Value) -> (Option<&Value>, &[Value]) {
    let subject = subject_of(cred);
    let digest = subject.and_then(|s| s.get(PARENT_GRANT_DIGEST));
    let embedded = match subject.and_then(|s| s.get("delegationChain")) {
        Some(Value::Array(a)) => a.as_slice(),
        _ => &[],
    };
    (digest, embedded)
}

/// (index of the link, reason) for the first link whose grant is not bound to
/// the grant before it, or None. Links are checked in order; for each one: the
/// binding fields' shape ([`binding_fields_problem`]), then the binding.
fn binding_failure(chain: &[Value]) -> Option<(usize, &'static str)> {
    for (i, link) in chain.iter().enumerate() {
        let Some(grant) = link.get("parentCredential").filter(|g| g.is_object()) else {
            return Some((i, REASON_MALFORMED));
        };
        if let Some(malformed) = binding_fields_problem(&grant["credentialSubject"]) {
            return Some((i, malformed));
        }
        let (digest, embedded) = bindings(grant);
        // An empty embedded chain counts as no embedded chain.
        let has_embedded = !embedded.is_empty();
        if i == 0 {
            // The first grant is a root grant: it names no grant above it.
            if digest.is_some() || has_embedded {
                return Some((i, REASON_PARENT_MISMATCH));
            }
            continue;
        }
        let bound = if let Some(Value::String(d)) = digest {
            match grant_digest(&chain[i - 1]["parentCredential"]) {
                Ok(expected) => *d == expected,
                Err(_) => return Some((i, REASON_MALFORMED)),
            }
        } else if has_embedded {
            // The older nested form: the grant's own copy of the chain above
            // it must be exactly the links before it (JCS-equal).
            embedded.len() == i
                && embedded
                    .iter()
                    .zip(&chain[..i])
                    .all(|(a, b)| jcs::canonicalize(a) == jcs::canonicalize(b))
        } else {
            false
        };
        if !bound {
            return Some((i, REASON_PARENT_MISMATCH));
        }
    }
    None
}

/// The binding rule for an embedded delegation chain: None when every link's
/// grant is bound to the grant before it, otherwise the reason.
///
/// For each link, in order (first failure wins):
///
/// - the link carries no grant object: `malformed_delegation`;
/// - `parentGrantDigest` present but not a string, or `delegationChain`
///   present but not a list: `malformed_delegation`;
/// - the grant carries a digest and a non-empty embedded chain
///   ([`binding_fields_problem`]): `malformed_delegation`;
/// - first link: the grant carries a digest or a non-empty embedded chain (it
///   is not a root grant): `delegation_parent_mismatch`;
/// - later links: the digest is the digest of the previous link's grant, or
///   the embedded chain is JCS-equal to the links before this one; neither:
///   `delegation_parent_mismatch`.
///
/// Verifiers run it at the end of the pre-filter, before any key is resolved,
/// and only when every link's `parentCredential` is an object. A link without
/// one is malformed here.
pub fn chain_binding_problem(chain: &[Value]) -> Option<&'static str> {
    binding_failure(chain).map(|(_, reason)| reason)
}

/// The binding rule for credentials presented one by one, root first (a fleet
/// chain): (index, reason) for the first credential that breaks it, or None.
///
/// For each credential, in order (first failure wins):
///
/// - the credential is not an object: `malformed_delegation` (the fleet
///   verifier refuses it before this runs: `"credential {i} is not a JSON
///   object"`);
/// - `parentGrantDigest` present and not a string, `delegationChain` present
///   and not a list, or a digest together with a non-empty `delegationChain`
///   ([`binding_fields_problem`]): `malformed_delegation`;
/// - credential 0 carries a digest or a non-empty `delegationChain` (it is not
///   a root grant): `delegation_parent_mismatch`;
/// - credential i >= 1 carries a digest that is not the digest of credential
///   i-1: `delegation_parent_mismatch`;
/// - credential i >= 1 carries a non-empty `delegationChain` (an older nested
///   sub-grant, or a credential that embeds its chain) whose last link's
///   `parentCredential` is not an object JCS-equal to credential i-1:
///   `delegation_parent_mismatch`.
///
/// A credential with neither binding is read as before (its place in the chain
/// is checked by the issuer and delegatee walk). A fleet verifier runs this
/// before any credential is verified and refuses with
/// `"credential {i}: {reason}"`. (The reference's last rule, a credential with
/// no JCS form, cannot arise here: every `serde_json::Value` has one.)
pub fn presented_chain_problem(credentials: &[Value]) -> Option<(usize, &'static str)> {
    for (i, cred) in credentials.iter().enumerate() {
        if !cred.is_object() {
            return Some((i, REASON_MALFORMED));
        }
        if let Some(malformed) = binding_fields_problem(&cred["credentialSubject"]) {
            return Some((i, malformed));
        }
        let (digest, embedded) = bindings(cred);
        if i == 0 {
            // The first credential is a root grant: it names nothing above it.
            if digest.is_some() || !embedded.is_empty() {
                return Some((i, REASON_PARENT_MISMATCH));
            }
            continue;
        }
        let previous = &credentials[i - 1];
        let bound = if let Some(digest) = digest {
            match grant_digest(previous) {
                Ok(expected) => digest.as_str() == Some(expected.as_str()),
                Err(_) => return Some((i, REASON_MALFORMED)),
            }
        } else if let Some(last) = embedded.last() {
            // The older nested form, or a credential that embeds its chain:
            // the chain it carries ends at the credential before it.
            last.get("parentCredential")
                .filter(|g| g.is_object())
                .is_some_and(|g| jcs::canonicalize(g) == jcs::canonicalize(previous))
        } else {
            continue;
        };
        if !bound {
            return Some((i, REASON_PARENT_MISMATCH));
        }
    }
    None
}

// ---------------------------------------------------------------------------
// Grant chains (the signing side)
// ---------------------------------------------------------------------------

/// A grant's own embedded chain when it is a list, else none.
fn embedded_chain(grant: &Value) -> &[Value] {
    match subject_of(grant).and_then(|s| s.get("delegationChain")) {
        Some(Value::Array(a)) => a.as_slice(),
        _ => &[],
    }
}

/// True when an intent names a delegatee (a non-empty string), so what is
/// signed with it is a grant.
pub fn is_grant_intent(intent: &Value) -> bool {
    intent
        .get("delegatee")
        .and_then(Value::as_str)
        .is_some_and(|d| !d.is_empty())
}

/// The grants a parent stands for, root first.
///
/// A grant chain (an array) is taken as it is. A single grant (an object) is
/// a root grant, or an older grant that embeds the chain above it, whose
/// embedded grants come first. A single grant that names a parent grant by
/// digest is refused ([`NAMES_PARENT_GRANT`]), because the grants above it are
/// missing.
///
/// Errors: the parent is an empty array, holds something other than grants,
/// names a parent grant without its ancestors, embeds a chain that is not a
/// list of links carrying grants, or is neither an object nor an array.
pub fn parent_grants(parent: &Value) -> Result<Vec<Value>, GrantChainError> {
    match parent {
        Value::Object(_) => {
            let subject = subject_of(parent);
            if subject.is_some_and(|s| s.contains_key(PARENT_GRANT_DIGEST)) {
                return Err(refused(NAMES_PARENT_GRANT));
            }
            if subject
                .and_then(|s| s.get("delegationChain"))
                .is_some_and(|c| !c.is_array())
            {
                return Err(refused(
                    "Delegation refused: the parent grant's delegationChain is not a list",
                ));
            }
            let mut grants = Vec::new();
            for link in embedded_chain(parent) {
                let Some(grant) = link.get("parentCredential").filter(|g| g.is_object()) else {
                    return Err(refused(
                        "Delegation refused: a link in the parent grant's delegationChain \
                         carries no signed grant",
                    ));
                };
                grants.push(grant.clone());
            }
            grants.push(parent.clone());
            Ok(grants)
        }
        Value::Array(items) => {
            if items.is_empty() {
                return Err(refused("Delegation refused: the grant chain is empty"));
            }
            if !items.iter().all(Value::is_object) {
                return Err(refused(
                    "Delegation refused: every grant in the grant chain must be an object",
                ));
            }
            Ok(items.clone())
        }
        _ => Err(refused(
            "parent_credential must be a grant (a dict) or a grant chain (a list of grants, \
             root first)",
        )),
    }
}

/// The grant's intent object, or the reference's refusal.
fn intent_of(grant: &Value) -> Result<&Value, GrantChainError> {
    subject_of(grant)
        .and_then(|s| s.get("intent"))
        .filter(|i| i.is_object())
        .ok_or_else(|| refused("Delegation refused: the parent grant carries no intent object"))
}

/// The delegation link for one grant (Specification 9.2), in the shape every
/// verifier reads: the intent is the one signed at the next step.
///
/// The link's issuer is the grant's issuer as a string (the `id` of an issuer
/// object), or "" when it is not one. The intent and the grant are copies, so
/// the link shares nothing with the caller's values.
fn link_for(grant: &Value, intent: &Value) -> Result<Value, GrantChainError> {
    let mut link = Map::new();
    link.insert(
        "issuer".into(),
        Value::String(
            issuer_value(grant)
                .and_then(Value::as_str)
                .unwrap_or_default()
                .to_string(),
        ),
    );
    link.insert(
        "subject".into(),
        intent_of(grant)?
            .get("delegatee")
            .cloned()
            .unwrap_or(Value::Null),
    );
    link.insert("intent".into(), intent.clone());
    for k in ["validFrom", "validUntil"] {
        link.insert(k.into(), grant.get(k).cloned().unwrap_or(Value::Null));
    }
    let bound: String = delegation::parent_proof_binding_value(grant)
        .chars()
        .take(64)
        .collect();
    link.insert("parentProofValue".into(), Value::String(bound));
    link.insert("parentCredential".into(), grant.clone());
    Ok(Value::Object(link))
}

/// The delegation links for a credential signed under `grants` (root first)
/// with `intent`: one link per grant. Link j's intent is the intent of grant
/// j+1, and the last link's is `intent`.
///
/// When a grant embeds the chain above it (the older nested form), the links
/// before it are copied from it verbatim, so they stay JCS-equal to what that
/// grant signed. Each copied link must carry grant i of the chain, name grant
/// i's issuer as its issuer, and name grant i's delegatee as its subject.
///
/// Every link is a copy: the result shares no value with `grants`, `intent`
/// or the links a nested grant embeds.
///
/// Errors: a grant is not an object or carries no intent object
/// ("Delegation refused: the parent grant carries no intent object", checked
/// for every grant first), the grants before an older nested grant are not
/// the ones it embeds, or a link it embeds names another issuer or subject
/// than its grant.
pub fn chain_links(grants: &[Value], intent: &Value) -> Result<Vec<Value>, GrantChainError> {
    for grant in grants {
        intent_of(grant)?;
    }
    let mut links: Vec<Value> = Vec::new();
    let mut start = 0;
    for j in (0..grants.len()).rev() {
        let embedded = embedded_chain(&grants[j]);
        if embedded.is_empty() {
            continue;
        }
        let same = embedded.len() == j
            && embedded.iter().enumerate().all(|(i, link)| {
                link.get("parentCredential")
                    .filter(|g| g.is_object())
                    .is_some_and(|g| jcs::canonicalize(g) == jcs::canonicalize(&grants[i]))
            });
        if !same {
            return Err(refused(format!(
                "Delegation refused: grant {} of the grant chain embeds a chain that is not \
                 the grants before it",
                j + 1
            )));
        }
        for (i, link) in embedded.iter().enumerate() {
            if present(link.get("issuer")) != present(issuer_value(&grants[i])) {
                return Err(refused(format!(
                    "Delegation refused: grant {} of the grant chain embeds a link whose issuer \
                     is not the issuer of grant {}",
                    j + 1,
                    i + 1
                )));
            }
            if present(link.get("subject")) != present(intent_of(&grants[i])?.get("delegatee")) {
                return Err(refused(format!(
                    "Delegation refused: grant {} of the grant chain embeds a link whose subject \
                     is not the delegatee of grant {}",
                    j + 1,
                    i + 1
                )));
            }
        }
        links = embedded.to_vec();
        start = j;
        break;
    }
    for j in start..grants.len() {
        let step_intent = if j + 1 < grants.len() {
            intent_of(&grants[j + 1])?
        } else {
            intent
        };
        links.push(link_for(&grants[j], step_intent)?);
    }
    Ok(links)
}

/// The issuer of a grant: the `issuer` value, or the `id` of an issuer object.
fn issuer_value(grant: &Value) -> Option<&Value> {
    match grant.get("issuer") {
        Some(Value::Object(o)) => o.get("id"),
        other => other,
    }
}

/// A field as the reference's `dict.get` reads it: absent and null are both
/// "no value".
fn present(v: Option<&Value>) -> Option<&Value> {
    v.filter(|x| !x.is_null())
}

/// Python truthiness of a JSON value (absent and null are false).
pub(crate) fn truthy(v: Option<&Value>) -> bool {
    match v {
        None | Some(Value::Null) => false,
        Some(Value::Bool(b)) => *b,
        Some(Value::Number(n)) => n.as_f64().is_some_and(|f| f != 0.0),
        Some(Value::String(s)) => !s.is_empty(),
        Some(Value::Array(a)) => !a.is_empty(),
        Some(Value::Object(o)) => !o.is_empty(),
    }
}

/// Python's `repr` of a JSON value, for refusal text that quotes a value the
/// way the reference does (`'did:web:a'`, `None`, `1e-05`).
pub(crate) fn py_repr(v: Option<&Value>) -> String {
    match v {
        None | Some(Value::Null) => "None".into(),
        Some(Value::Bool(true)) => "True".into(),
        Some(Value::Bool(false)) => "False".into(),
        // An integer is written as its digits, a float the way Python does.
        Some(Value::Number(n)) => match n.as_f64() {
            Some(f) if n.is_f64() => py_repr_float(f),
            _ => n.to_string(),
        },
        Some(Value::String(s)) => py_repr_str(s),
        Some(Value::Array(a)) => {
            let items: Vec<String> = a.iter().map(|x| py_repr(Some(x))).collect();
            format!("[{}]", items.join(", "))
        }
        Some(Value::Object(o)) => {
            let items: Vec<String> = o
                .iter()
                .map(|(k, x)| format!("{}: {}", py_repr_str(k), py_repr(Some(x))))
                .collect();
            format!("{{{}}}", items.join(", "))
        }
    }
}

/// The shortest digits that read back as `f` (finite, not negative) and where
/// the decimal point goes: `f` is 0.DIGITS times 10 to the power of the
/// second value. Zero is ("0", 1).
///
/// The digits come from ECMAScript's number to string (ryu-js), which picks
/// the closest of the shortest candidates and, on an exact tie, the even last
/// digit, the same as Python's `repr`. (Rust's own `{:e}` breaks a tie
/// upward, so 588197768793114.25 would end in 3 instead of Python's 2.)
fn shortest_digits(f: f64) -> (String, i32) {
    let mut buf = ryu_js::Buffer::new();
    let text = buf.format(f);
    let (number, exp) = match text.split_once('e') {
        Some((n, e)) => (n, e.parse::<i32>().unwrap_or(0)),
        None => (text, 0),
    };
    let (whole, fraction) = number.split_once('.').unwrap_or((number, ""));
    let all = format!("{whole}{fraction}");
    let significant = all.trim_start_matches('0');
    let point = whole.len() as i32 + exp - (all.len() - significant.len()) as i32;
    let significant = significant.trim_end_matches('0');
    if significant.is_empty() {
        return ("0".into(), 1);
    }
    (significant.to_string(), point)
}

/// Python's `repr` of a float. The digits are the shortest that read back as
/// the same value ([`shortest_digits`]). With the value written as 0.DIGITS
/// times 10 to the power `point`, a `point` from -3 to 16 is written out in
/// full (`0.0001`, `1.5`, `1234.0`, a whole number keeping its `.0`); anything
/// else is written with an exponent that has a sign and at least two digits
/// (`1e-05`, `1e+16`, `1.5e+300`). The sign of `-0.0` is kept. A JSON number
/// is never infinite or NaN, but they are written as Python writes them too.
pub(crate) fn py_repr_float(f: f64) -> String {
    if f.is_nan() {
        return "nan".into();
    }
    if f.is_infinite() {
        return if f > 0.0 { "inf" } else { "-inf" }.into();
    }
    let sign = if f.is_sign_negative() { "-" } else { "" };
    let (digits, point) = shortest_digits(f.abs());
    let exp = point - 1;
    if point <= -4 || point > 16 {
        let (first, rest) = digits.split_at(1);
        let fraction = if rest.is_empty() {
            String::new()
        } else {
            format!(".{rest}")
        };
        let exp_sign = if exp < 0 { '-' } else { '+' };
        return format!(
            "{sign}{first}{fraction}e{exp_sign}{:02}",
            exp.unsigned_abs()
        );
    }
    let len = digits.len() as i32;
    let body = if point <= 0 {
        format!("0.{}{digits}", "0".repeat(point.unsigned_abs() as usize))
    } else if point >= len {
        format!("{digits}{}.0", "0".repeat((point - len) as usize))
    } else {
        let (whole, fraction) = digits.split_at(point as usize);
        format!("{whole}.{fraction}")
    };
    format!("{sign}{body}")
}

/// Python's `repr` of a string: single quotes unless the string holds a single
/// quote and no double quote; backslash and the quote escaped; tab, newline
/// and carriage return as `\t`, `\n`, `\r`; every other character that
/// Python's `str.isprintable()` rejects as `\xhh`, `\uhhhh` or `\Uhhhhhhhh`
/// (lowercase hex, the shortest form that holds it).
pub(crate) fn py_repr_str(s: &str) -> String {
    let quote = if s.contains('\'') && !s.contains('"') {
        '"'
    } else {
        '\''
    };
    let mut out = String::with_capacity(s.len() + 2);
    out.push(quote);
    for c in s.chars() {
        match c {
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if c == quote => {
                out.push('\\');
                out.push(c);
            }
            c if crate::py_printable::is_printable(c) => out.push(c),
            c if (c as u32) <= 0xff => out.push_str(&format!("\\x{:02x}", c as u32)),
            c if (c as u32) <= 0xffff => out.push_str(&format!("\\u{:04x}", c as u32)),
            c => out.push_str(&format!("\\U{:08x}", c as u32)),
        }
    }
    out.push(quote);
    out
}

/// Check a grant chain from its link fields and build the links for `intent`
/// signed under it (see [`chain_links`]).
///
/// The rules, in order (first failure wins):
///
/// - each grant is an object whose subject carries an intent object
///   ("Delegation refused: the parent grant carries no intent object"), is
///   signed, and is issued by a DID string (an issuer object's string `id`
///   counts, and the link carries the string);
/// - each grant's delegatee is the next grant's issuer;
/// - a link copied from an older nested grant names that grant's issuer and
///   delegatee ([`chain_links`]);
/// - every grant is bound to the grant before it ([`chain_binding_problem`]);
/// - with two grants or more: the first grant writes down every dimension in
///   a form that can be compared, time included ("Delegation refused: grant 1
///   of the grant chain has a malformed '{dimension}'",
///   [`attenuation::malformed_dimension`]), and no grant is broader than the
///   grants before it on any dimension, time included
///   ([`attenuation::first_broader_step`] over the grants), so a window
///   clamped to the last grant sits inside every grant above it.
///
/// Who the last delegatee is, and whether `intent` stays inside the chain, are
/// the signer's checks. No signature is checked here: the verifier checks
/// every grant's proof.
///
/// Errors: the first rule the chain breaks.
pub fn check_grant_chain(grants: &[Value], intent: &Value) -> Result<Vec<Value>, GrantChainError> {
    for (j, grant) in grants.iter().enumerate() {
        intent_of(grant)?;
        if !truthy(grant.get("issuer"))
            || !matches!(grant.get("proof"), Some(Value::Object(_) | Value::Array(_)))
        {
            return Err(refused(
                "Delegation refused: the parent grant is not a signed credential",
            ));
        }
        if !issuer_value(grant).is_some_and(Value::is_string) {
            return Err(refused(format!(
                "Delegation refused: grant {} of the grant chain has an issuer that is not a \
                 string or an object with a string id",
                j + 1
            )));
        }
    }
    for j in 0..grants.len().saturating_sub(1) {
        let delegatee = intent_of(&grants[j])?
            .get("delegatee")
            .and_then(Value::as_str)
            .filter(|d| !d.is_empty());
        let Some(delegatee) = delegatee else {
            return Err(refused(format!(
                "Delegation refused: grant {} of the grant chain names no delegatee",
                j + 1
            )));
        };
        let next_issuer = issuer_value(&grants[j + 1]);
        if next_issuer.and_then(Value::as_str) != Some(delegatee) {
            return Err(refused(format!(
                "Delegation refused: grant {} of the grant chain names delegatee {}, but grant \
                 {} is issued by {}",
                j + 1,
                py_repr_str(delegatee),
                j + 2,
                py_repr(next_issuer)
            )));
        }
    }
    let links = chain_links(grants, intent)?;
    if let Some((index, reason)) = binding_failure(&links) {
        return Err(refused(format!(
            "Delegation refused: grant {} of the grant chain is not bound to the grant before \
             it ({reason})",
            index + 1
        )));
    }
    // A single grant has no grant before it; the signer checks the new intent
    // against it.
    if grants.len() > 1 {
        let views: Vec<Value> = grants
            .iter()
            .map(|g| delegation::capability_view(g, true))
            .collect();
        // A malformed bound on the first grant is named as such: nothing in
        // the chain can be shown to sit inside it.
        if let Some(dimension) = attenuation::malformed_dimension(&views[0]) {
            return Err(refused(format!(
                "Delegation refused: grant 1 of the grant chain has a malformed {}",
                py_repr_str(dimension.as_str())
            )));
        }
        if let Err(dimension) = attenuation::first_broader_step(&views) {
            return Err(refused(format!(
                "Delegation refused: a grant in the grant chain is broader than the grant before \
                 it on {}",
                py_repr_str(dimension.as_str())
            )));
        }
    }
    Ok(links)
}

/// The effective capability at the end of a grant chain: the last grant's
/// view, with every dimension it omits inherited from the grants above it (the
/// same fold the verifier does over an embedded chain).
///
/// Errors when `grants` is empty.
pub fn chain_capability(grants: &[Value], include_time: bool) -> Result<Value, GrantChainError> {
    let mut effective: Option<Value> = None;
    for grant in grants {
        let view = delegation::capability_view(grant, include_time);
        effective = Some(match effective {
            None => view,
            Some(e) => attenuation::inherit(&e, &view),
        });
    }
    effective.ok_or_else(|| refused("Delegation refused: the grant chain is empty"))
}

/// The grant chain to hand the delegatee of `grant`: the grants above it, root
/// first, then `grant` itself.
///
/// `parent` is what `grant` was signed under: a root grant, an older grant
/// that embeds its chain, or a grant chain. The delegatee signs with the
/// result as its parent. Every grant in the result is a copy, so it shares
/// nothing with `parent` or `grant`.
///
/// Errors: `grant` is not an object, names no delegatee, is not issued by the
/// delegatee of the last parent grant, or is not bound to it, or the chain
/// itself breaks a rule of [`check_grant_chain`].
pub fn grant_chain(parent: &Value, grant: &Value) -> Result<Vec<Value>, GrantChainError> {
    let mut grants = parent_grants(parent)?;
    if !grant.is_object() {
        return Err(refused("grant must be a signed grant (a dict)"));
    }
    let intent = intent_of(grant)?;
    if !is_grant_intent(intent) {
        return Err(refused(
            "this credential names no delegatee, so nobody can sign under it",
        ));
    }
    grants.push(grant.clone());
    check_grant_chain(&grants, intent)?;
    Ok(grants)
}

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

    fn grant(issuer: &str, delegatee: &str, extra: Value) -> Value {
        let mut subject = json!({
            "id": issuer,
            "intent": {"action": "read", "target": "t", "resource": "https://x/a",
                       "delegatee": delegatee}
        });
        for (k, v) in extra.as_object().unwrap() {
            subject[k] = v.clone();
        }
        json!({
            "issuer": issuer,
            "validFrom": "2026-11-10T00:00:00Z",
            "validUntil": "2026-11-11T00:00:00Z",
            "credentialSubject": subject,
            "proof": {"type": "DataIntegrityProof", "proofValue": format!("z{issuer}")}
        })
    }

    fn link(g: &Value) -> Value {
        json!({"issuer": g["issuer"], "subject": g["credentialSubject"]["intent"]["delegatee"],
               "parentCredential": g})
    }

    /// root -> a -> b, flat: b's grant names a's by digest, a's names root's.
    fn flat3() -> Vec<Value> {
        let g1 = grant("did:web:root", "did:web:a", json!({}));
        let g2 = grant(
            "did:web:a",
            "did:web:b",
            json!({ "parentGrantDigest": grant_digest(&g1).unwrap() }),
        );
        let g3 = grant(
            "did:web:b",
            "did:web:c",
            json!({ "parentGrantDigest": grant_digest(&g2).unwrap() }),
        );
        vec![g1, g2, g3]
    }

    fn links(grants: &[Value]) -> Vec<Value> {
        grants.iter().map(link).collect()
    }

    #[test]
    fn digest_shape_and_exactness() {
        let g = grant("did:web:root", "did:web:a", json!({}));
        let d = grant_digest(&g).unwrap();
        assert!(d.starts_with("uEi"), "{d}");
        assert_eq!(d.len(), 47);
        assert!(!d.contains('=') && !d.contains('+') && !d.contains('/'));
        // Key order does not matter (JCS), any change of content does.
        let reordered: Value = serde_json::from_str(
            &serde_json::to_string(&json!({
                "proof": g["proof"], "credentialSubject": g["credentialSubject"],
                "validUntil": g["validUntil"], "validFrom": g["validFrom"], "issuer": g["issuer"]
            }))
            .unwrap(),
        )
        .unwrap();
        assert_eq!(grant_digest(&reordered).unwrap(), d);
        let mut other = g.clone();
        other["proof"]["proofValue"] = json!("zdifferent");
        assert_ne!(grant_digest(&other).unwrap(), d);
        for bad in [json!([]), json!("x"), Value::Null, json!(1), json!(true)] {
            assert_eq!(
                grant_digest(&bad),
                Err(GrantDigestError("a grant must be a JSON object".into()))
            );
        }
    }

    #[test]
    fn flat_and_nested_chains_bind() {
        assert_eq!(chain_binding_problem(&links(&flat3())), None);
        assert_eq!(chain_binding_problem(&[]), None);
        // The older nested form: the third grant embeds the two links above it.
        let g = flat3();
        let ls = links(&g[..2]);
        let nested = grant(
            "did:web:b",
            "did:web:c",
            json!({ "delegationChain": ls.clone() }),
        );
        let mut chain = ls.clone();
        chain.push(link(&nested));
        assert_eq!(chain_binding_problem(&chain), None);
        // An empty embedded chain is no chain: the digest binds.
        let g = flat3();
        let mut g2 = g[1].clone();
        g2["credentialSubject"]["delegationChain"] = json!([]);
        assert_eq!(chain_binding_problem(&[link(&g[0]), link(&g2)]), None);
    }

    #[test]
    fn binding_refusals() {
        let g = flat3();
        let mismatch = Some(REASON_PARENT_MISMATCH);
        let malformed = Some(REASON_MALFORMED);
        // Truncated: the first grant names a parent.
        assert_eq!(chain_binding_problem(&links(&g[1..])), mismatch);
        // Splice: a's grant presented under a different root grant.
        let other_root = grant("did:web:root", "did:web:a", json!({"note": "other"}));
        assert_eq!(
            chain_binding_problem(&[link(&other_root), link(&g[1]), link(&g[2])]),
            mismatch
        );
        // The digest of the grandparent.
        let skip = grant(
            "did:web:b",
            "did:web:c",
            json!({ "parentGrantDigest": grant_digest(&g[0]).unwrap() }),
        );
        assert_eq!(
            chain_binding_problem(&[link(&g[0]), link(&g[1]), link(&skip)]),
            mismatch
        );
        // No binding at all on a later grant.
        let bare = grant("did:web:a", "did:web:b", json!({}));
        assert_eq!(chain_binding_problem(&[link(&g[0]), link(&bare)]), mismatch);
        // Spelling games: same hash, different text.
        let right = grant_digest(&g[0]).unwrap();
        for spelled in [
            right.to_uppercase(),
            format!("{right}="),
            format!(" {right}"),
            right.replacen('u', "z", 1),
        ] {
            let mut g2 = g[1].clone();
            g2["credentialSubject"][PARENT_GRANT_DIGEST] = json!(spelled);
            assert_eq!(
                chain_binding_problem(&[link(&g[0]), link(&g2)]),
                mismatch,
                "{spelled}"
            );
        }
        // null, a number, an object, an array: present and not a string.
        for v in [Value::Null, json!(5), json!({}), json!([right.clone()])] {
            let mut g2 = g[1].clone();
            g2["credentialSubject"][PARENT_GRANT_DIGEST] = v.clone();
            assert_eq!(
                chain_binding_problem(&[link(&g[0]), link(&g2)]),
                malformed,
                "{v}"
            );
            // On the first link the type check comes first too.
            let mut g1 = g[0].clone();
            g1["credentialSubject"][PARENT_GRANT_DIGEST] = v.clone();
            assert_eq!(chain_binding_problem(&[link(&g1)]), malformed, "{v}");
        }
        // A delegationChain that is not a list.
        for v in [Value::Null, json!({}), json!(""), json!(0)] {
            let mut g2 = g[1].clone();
            g2["credentialSubject"]["delegationChain"] = v.clone();
            assert_eq!(
                chain_binding_problem(&[link(&g[0]), link(&g2)]),
                malformed,
                "{v}"
            );
        }
        // Both bindings on one grant, even when each would hold.
        let mut both = g[1].clone();
        both["credentialSubject"]["delegationChain"] = json!([link(&g[0])]);
        assert_eq!(
            chain_binding_problem(&[link(&g[0]), link(&both)]),
            malformed
        );
        // The first grant embeds a chain.
        assert_eq!(chain_binding_problem(&[link(&both)]), malformed);
        let mut nested_first = g[0].clone();
        nested_first["credentialSubject"]["delegationChain"] = json!([link(&g[0])]);
        assert_eq!(chain_binding_problem(&[link(&nested_first)]), mismatch);
        // An embedded chain that is not the links before it.
        let mut longer = g[1].clone();
        longer["credentialSubject"]
            .as_object_mut()
            .unwrap()
            .remove(PARENT_GRANT_DIGEST);
        longer["credentialSubject"]["delegationChain"] = json!([link(&g[0]), link(&g[0])]);
        assert_eq!(
            chain_binding_problem(&[link(&g[0]), link(&longer)]),
            mismatch
        );
        let mut tampered_link = link(&g[0]);
        tampered_link["note"] = json!("x");
        longer["credentialSubject"]["delegationChain"] = json!([tampered_link]);
        assert_eq!(
            chain_binding_problem(&[link(&g[0]), link(&longer)]),
            mismatch
        );
        // A grant edited after its child named it.
        let mut edited = g[0].clone();
        edited["credentialSubject"]["intent"]["resource"] = json!("https://x");
        assert_eq!(
            chain_binding_problem(&[link(&edited), link(&g[1]), link(&g[2])]),
            mismatch
        );
        // Called directly, a link without its grant is malformed.
        assert_eq!(
            chain_binding_problem(&[json!({"issuer": "did:web:root"})]),
            malformed
        );
        assert_eq!(
            chain_binding_problem(&[link(&g[0]), json!({"parentCredential": "x"})]),
            malformed
        );
        // The first failure wins.
        let mut bad_type = g[2].clone();
        bad_type["credentialSubject"][PARENT_GRANT_DIGEST] = json!(1);
        assert_eq!(
            chain_binding_problem(&[link(&g[0]), link(&bare), link(&bad_type)]),
            mismatch
        );
    }

    #[test]
    fn presented_chain_rule() {
        let g = flat3();
        assert_eq!(presented_chain_problem(&g), None);
        assert_eq!(presented_chain_problem(&[]), None);
        // Credential 0 with a digest.
        assert_eq!(
            presented_chain_problem(&g[1..]),
            Some((0, REASON_PARENT_MISMATCH))
        );
        // A wrong digest further down.
        assert_eq!(
            presented_chain_problem(&[g[0].clone(), g[2].clone()]),
            Some((1, REASON_PARENT_MISMATCH))
        );
        // Not a string, on credential 0 too (the type is checked first).
        let mut bad = g[1].clone();
        bad["credentialSubject"][PARENT_GRANT_DIGEST] = Value::Null;
        assert_eq!(
            presented_chain_problem(&[g[0].clone(), bad.clone()]),
            Some((1, REASON_MALFORMED))
        );
        assert_eq!(
            presented_chain_problem(std::slice::from_ref(&bad)),
            Some((0, REASON_MALFORMED))
        );
        // Credentials without a binding are read as before.
        let plain = grant("did:web:a", "did:web:b", json!({}));
        assert_eq!(
            presented_chain_problem(&[g[0].clone(), plain.clone()]),
            None
        );
        // A credential that is not an object is malformed, wherever it sits
        // (the fleet verifier refuses it before this runs).
        for (position, value) in [(0, json!("{}")), (1, Value::Null), (2, json!(7))] {
            let mut creds = vec![g[0].clone(), plain.clone(), plain.clone()];
            creds[position] = value;
            assert_eq!(
                presented_chain_problem(&creds),
                Some((position, REASON_MALFORMED))
            );
        }
        assert_eq!(
            presented_chain_problem(&[json!("x"), g[1].clone()]),
            Some((0, REASON_MALFORMED))
        );
    }

    /// The older nested chain a delegatee of `parent` embeds when it signs
    /// `intent`: the parent's own embedded links, then a link for the parent.
    fn nested_chain(parent: &Value, intent: &Value) -> Value {
        let mut chain = embedded_chain(parent).to_vec();
        let mut l = link(parent);
        l["intent"] = intent.clone();
        chain.push(l);
        Value::Array(chain)
    }

    fn intent_to(delegatee: &str) -> Value {
        json!({"action": "read", "target": "t", "resource": "https://x/a", "delegatee": delegatee})
    }

    /// An older nested sub-grant by `issuer` to `delegatee` under `parent`.
    fn nested(issuer: &str, delegatee: &str, parent: &Value) -> Value {
        grant(
            issuer,
            delegatee,
            json!({ "delegationChain": nested_chain(parent, &intent_to(delegatee)) }),
        )
    }

    /// An action by `issuer` that embeds `links`.
    fn action(issuer: &str, links: Value) -> Value {
        json!({"issuer": issuer, "proof": {"proofValue": "z"},
               "credentialSubject": {"intent": {"action": "read"}, "delegationChain": links}})
    }

    #[test]
    fn binding_fields_shape() {
        let malformed = Some(REASON_MALFORMED);
        let digest = json!("uEiA");
        for subject in [
            json!({}),
            json!({"parentGrantDigest": digest}),
            json!({"delegationChain": []}),
            json!({"parentGrantDigest": digest, "delegationChain": []}),
            json!({"delegationChain": [{"issuer": "x"}]}),
            // Anything that is not an object carries no binding fields.
            Value::Null,
            json!([{"parentGrantDigest": 5}]),
            json!("parentGrantDigest"),
        ] {
            assert_eq!(binding_fields_problem(&subject), None, "{subject}");
        }
        for subject in [
            json!({"parentGrantDigest": null}),
            json!({"parentGrantDigest": 5}),
            json!({"parentGrantDigest": ["u"]}),
            json!({"parentGrantDigest": {}}),
            json!({"delegationChain": null}),
            json!({"delegationChain": {}}),
            json!({"delegationChain": ""}),
            json!({"delegationChain": 0}),
            json!({"delegationChain": false}),
            json!({"parentGrantDigest": digest, "delegationChain": [{}]}),
            json!({"parentGrantDigest": null, "delegationChain": [{}]}),
        ] {
            assert_eq!(binding_fields_problem(&subject), malformed, "{subject}");
        }
    }

    #[test]
    fn presented_chains_with_embedded_chains() {
        let mismatch = |i| Some((i, REASON_PARENT_MISMATCH));
        let malformed = |i| Some((i, REASON_MALFORMED));
        let g = flat3();
        let (g1, g2) = (g[0].clone(), g[1].clone());
        let g1b = grant("did:web:root2", "did:web:a", json!({}));
        let g2b = grant(
            "did:web:a",
            "did:web:b",
            json!({ "parentGrantDigest": grant_digest(&g1b).unwrap() }),
        );
        let leaf = action("did:web:b", json!([]));
        // a holds grants from two roots: its older nested sub-grant made under
        // root2's grant cannot follow root's grant, only root2's.
        let nested_b = nested("did:web:a", "did:web:b", &g1b);
        assert_eq!(
            presented_chain_problem(&[g1.clone(), nested_b.clone(), leaf.clone()]),
            mismatch(1)
        );
        assert_eq!(
            presented_chain_problem(&[g1b.clone(), nested_b.clone(), leaf.clone()]),
            None
        );
        // An older nested sub-grant (or a flat one) as credential 0.
        let nested_a = nested("did:web:a", "did:web:b", &g1);
        assert_eq!(
            presented_chain_problem(&[nested_a.clone(), leaf.clone()]),
            mismatch(0)
        );
        assert_eq!(
            presented_chain_problem(&[g2.clone(), leaf.clone()]),
            mismatch(0)
        );
        // An action that embeds another chain from the same root.
        let elsewhere = action("did:web:b", json!(links(&[g1b.clone(), g2b])));
        assert_eq!(
            presented_chain_problem(&[g1.clone(), g2.clone(), elsewhere]),
            mismatch(2)
        );
        let here = action("did:web:b", json!(links(&[g1.clone(), g2.clone()])));
        assert_eq!(
            presented_chain_problem(&[g1.clone(), g2.clone(), here]),
            None
        );
        // Binding fields of the wrong shape on credential 1.
        for fields in [
            json!({ "parentGrantDigest": grant_digest(&g1).unwrap(),
                    "delegationChain": nested_chain(&g1, &intent_to("did:web:b")) }),
            json!({"delegationChain": null}),
            json!({"delegationChain": {}}),
            json!({"parentGrantDigest": null}),
        ] {
            let sub = grant("did:web:a", "did:web:b", fields.clone());
            assert_eq!(
                presented_chain_problem(&[g1.clone(), sub, leaf.clone()]),
                malformed(1),
                "{fields}"
            );
        }
        // Older nested chains, and mixed chains, follow on.
        let g2n = nested("did:web:a", "did:web:b", &g1);
        let g3n = nested("did:web:b", "did:web:c", &g2n);
        let leaf_c = action("did:web:c", json!([]));
        assert_eq!(
            presented_chain_problem(&[g1.clone(), g2n.clone(), g3n.clone(), leaf_c.clone()]),
            None
        );
        let nested_leaf = action("did:web:c", nested_chain(&g3n, &json!({"action": "read"})));
        assert_eq!(
            presented_chain_problem(&[g1.clone(), g2n.clone(), g3n.clone(), nested_leaf]),
            None
        );
        let g3 = grant(
            "did:web:b",
            "did:web:c",
            json!({ "parentGrantDigest": grant_digest(&g2n).unwrap() }),
        );
        assert_eq!(
            presented_chain_problem(&[g1.clone(), g2n.clone(), g3, leaf_c.clone()]),
            None
        );
        // The same nested sub-grant one place later does not follow on.
        assert_eq!(
            presented_chain_problem(&[g1.clone(), g2n.clone(), g2n.clone(), g3n, leaf_c]),
            mismatch(2)
        );
    }

    #[test]
    fn the_last_embedded_link_must_carry_the_previous_credential() {
        let g1 = flat3()[0].clone();
        let links = nested_chain(&g1, &intent_to("did:web:b"));
        let mut no_grant = links.clone();
        no_grant[0]
            .as_object_mut()
            .unwrap()
            .remove("parentCredential");
        let mut not_an_object = links.clone();
        not_an_object[0]["parentCredential"] = json!(g1.to_string());
        let mut not_a_link = links.clone();
        not_a_link[0] = json!("link");
        // A link whose grant differs from credential 0 by one field.
        let mut edited = links.clone();
        edited[0]["parentCredential"]["validUntil"] = json!("2026-11-12T00:00:00Z");
        for embedded in [no_grant, not_an_object, not_a_link, edited] {
            let sub = json!({"issuer": "did:web:a",
                             "credentialSubject": {"delegationChain": embedded}});
            assert_eq!(
                presented_chain_problem(&[g1.clone(), sub]),
                Some((1, REASON_PARENT_MISMATCH))
            );
        }
        // JCS-equal is enough: key order does not matter.
        let reordered: Value = serde_json::from_str(&jcs::canonicalize_to_string(&g1)).unwrap();
        let sub = json!({"issuer": "did:web:a",
                         "credentialSubject": {"delegationChain": [{"parentCredential": reordered}]}});
        assert_eq!(presented_chain_problem(&[g1, sub]), None);
    }

    #[test]
    fn grant_chains_for_signing() {
        let g = flat3();
        let leaf_intent = json!({"action": "read", "target": "t", "resource": "https://x/a"});
        let ls = check_grant_chain(&g, &leaf_intent).unwrap();
        assert_eq!(ls.len(), 3);
        assert_eq!(chain_binding_problem(&ls), None);
        // Link j carries grant j+1's intent, and the last the new intent.
        assert_eq!(ls[0]["intent"], g[1]["credentialSubject"]["intent"]);
        assert_eq!(ls[2]["intent"], leaf_intent);
        assert_eq!(ls[1]["subject"], json!("did:web:b"));
        assert_eq!(ls[1]["parentProofValue"], json!("zdid:web:a"));
        let keys: Vec<&str> = ls[0]
            .as_object()
            .unwrap()
            .keys()
            .map(|k| k.as_str())
            .collect();
        assert_eq!(
            keys,
            [
                "issuer",
                "subject",
                "intent",
                "validFrom",
                "validUntil",
                "parentProofValue",
                "parentCredential"
            ]
        );
        // grant_chain: what to hand the delegatee of a new sub-grant.
        let sub = grant(
            "did:web:c",
            "did:web:d",
            json!({ "parentGrantDigest": grant_digest(&g[2]).unwrap() }),
        );
        let handed = grant_chain(&json!(g.clone()), &sub).unwrap();
        assert_eq!(handed.len(), 4);
        assert_eq!(handed[3], sub);
        // A single grant that names a parent is refused alone.
        assert_eq!(grant_chain(&g[1], &sub).unwrap_err().0, NAMES_PARENT_GRANT);
        assert_eq!(parent_grants(&g[2]).unwrap_err().0, NAMES_PARENT_GRANT);
        // An older nested grant stands for its embedded grants and itself.
        let nested = grant(
            "did:web:a",
            "did:web:b",
            json!({ "delegationChain": [link(&g[0])] }),
        );
        let pg = parent_grants(&nested).unwrap();
        assert_eq!(pg, vec![g[0].clone(), nested.clone()]);
        // Its embedded link is copied verbatim.
        let copied = check_grant_chain(&pg, &leaf_intent).unwrap();
        assert_eq!(copied[0], link(&g[0]));
        assert_eq!(chain_binding_problem(&copied), None);
        // A credential (no delegatee) cannot be signed under.
        let action = json!({"issuer": "did:web:c", "proof": {},
            "credentialSubject": {"intent": {"action": "read"}}});
        assert_eq!(
            grant_chain(&json!(g.clone()), &action).unwrap_err().0,
            "this credential names no delegatee, so nobody can sign under it"
        );
        assert_eq!(
            grant_chain(&json!(g.clone()), &json!([])).unwrap_err().0,
            "grant must be a signed grant (a dict)"
        );
        assert!(is_grant_intent(&json!({"delegatee": "did:web:x"})));
        for i in [
            json!({"delegatee": ""}),
            json!({"delegatee": 5}),
            json!({}),
            json!("x"),
        ] {
            assert!(!is_grant_intent(&i), "{i}");
        }
    }

    #[test]
    fn grant_chain_refusals_match_the_reference_text() {
        let g = flat3();
        let intent = json!({"action": "read", "target": "t", "resource": "https://x/a"});
        let err = |grants: &[Value]| check_grant_chain(grants, &intent).unwrap_err().0;
        assert_eq!(
            parent_grants(&json!([])).unwrap_err().0,
            "Delegation refused: the grant chain is empty"
        );
        assert_eq!(
            parent_grants(&json!([g[0].clone(), 5])).unwrap_err().0,
            "Delegation refused: every grant in the grant chain must be an object"
        );
        assert_eq!(
            parent_grants(&json!("x")).unwrap_err().0,
            "parent_credential must be a grant (a dict) or a grant chain (a list of grants, root first)"
        );
        let mut bad_chain = g[0].clone();
        bad_chain["credentialSubject"]["delegationChain"] = json!({});
        assert_eq!(
            parent_grants(&bad_chain).unwrap_err().0,
            "Delegation refused: the parent grant's delegationChain is not a list"
        );
        bad_chain["credentialSubject"]["delegationChain"] = json!([{"issuer": "x"}]);
        assert_eq!(
            parent_grants(&bad_chain).unwrap_err().0,
            "Delegation refused: a link in the parent grant's delegationChain carries no signed grant"
        );
        // Unsigned, no intent, a gap, no delegatee.
        let mut unsigned = g[0].clone();
        unsigned.as_object_mut().unwrap().remove("proof");
        assert_eq!(
            err(&[unsigned]),
            "Delegation refused: the parent grant is not a signed credential"
        );
        let mut no_issuer = g[0].clone();
        no_issuer["issuer"] = json!("");
        assert_eq!(
            err(&[no_issuer]),
            "Delegation refused: the parent grant is not a signed credential"
        );
        let mut no_intent = g[0].clone();
        no_intent["credentialSubject"]["intent"] = json!("read");
        assert_eq!(
            err(&[no_intent]),
            "Delegation refused: the parent grant carries no intent object"
        );
        assert_eq!(
            err(&[g[0].clone(), g[2].clone()]),
            "Delegation refused: grant 1 of the grant chain names delegatee 'did:web:a', but grant 2 is issued by 'did:web:b'"
        );
        // An issuer that is not a DID string is refused before the walk.
        let mut no_issuer2 = g[1].clone();
        no_issuer2["issuer"] = json!({"name": "x"});
        assert_eq!(
            err(&[g[0].clone(), no_issuer2]),
            "Delegation refused: grant 2 of the grant chain has an issuer that is not a string or an object with a string id"
        );
        let mut no_delegatee = g[0].clone();
        no_delegatee["credentialSubject"]["intent"]
            .as_object_mut()
            .unwrap()
            .remove("delegatee");
        assert_eq!(
            err(&[no_delegatee, g[1].clone()]),
            "Delegation refused: grant 1 of the grant chain names no delegatee"
        );
        // An issuer object with the right id follows on.
        let mut object_issuer = g[1].clone();
        object_issuer["issuer"] = json!({"id": "did:web:a"});
        assert!(check_grant_chain(&[g[0].clone(), object_issuer], &intent).is_ok());
        // Unbound grants.
        let bare = grant("did:web:a", "did:web:b", json!({}));
        assert_eq!(
            err(&[g[0].clone(), bare]),
            "Delegation refused: grant 2 of the grant chain is not bound to the grant before it (delegation_parent_mismatch)"
        );
        let mut bad_digest = g[1].clone();
        bad_digest["credentialSubject"][PARENT_GRANT_DIGEST] = json!(7);
        assert_eq!(
            err(&[g[0].clone(), bad_digest]),
            "Delegation refused: grant 2 of the grant chain is not bound to the grant before it (malformed_delegation)"
        );
        // An older nested grant whose embedded chain is not the grants before it.
        let nested = grant(
            "did:web:a",
            "did:web:b",
            json!({ "delegationChain": [link(&g[0])] }),
        );
        let other_root = grant("did:web:root", "did:web:a", json!({"note": "other"}));
        assert_eq!(
            err(&[other_root, nested]),
            "Delegation refused: grant 2 of the grant chain embeds a chain that is not the grants before it"
        );
        assert_eq!(
            chain_capability(&[], false).unwrap_err().0,
            "Delegation refused: the grant chain is empty"
        );
    }

    const BROADER: &str =
        "Delegation refused: a grant in the grant chain is broader than the grant before it on ";

    #[test]
    fn an_intermediate_grant_broader_than_the_grant_above_it_is_refused() {
        let g = flat3();
        let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
        let digest = json!(grant_digest(&g[0]).unwrap());
        let mut broad = g[1].clone();
        broad["credentialSubject"]["intent"]["action"] = json!(["read", "write"]);
        broad["credentialSubject"][PARENT_GRANT_DIGEST] = digest.clone();
        let chain = [g[0].clone(), broad.clone()];
        assert_eq!(
            check_grant_chain(&chain, &leaf).unwrap_err().0,
            format!("{BROADER}'action'")
        );
        // The same for the grant chain handed on with it.
        assert_eq!(
            grant_chain(&g[0], &broad).unwrap_err().0,
            format!("{BROADER}'action'")
        );
        // A grant that outlives (or starts before) the grant above it.
        for (k, v) in [
            ("validUntil", "2026-11-12T00:00:00Z"),
            ("validFrom", "2026-11-09T00:00:00Z"),
        ] {
            let mut long = g[1].clone();
            long[k] = json!(v);
            assert_eq!(
                check_grant_chain(&[g[0].clone(), long.clone()], &leaf)
                    .unwrap_err()
                    .0,
                format!("{BROADER}'time'"),
                "{k}"
            );
            assert_eq!(
                grant_chain(&g[0], &long).unwrap_err().0,
                format!("{BROADER}'time'")
            );
        }
        // Further down the chain, against the effective capability so far.
        let mut wide = g[2].clone();
        wide["credentialSubject"]["intent"]["resource"] = json!("https://x");
        let mut chain = g.clone();
        chain[2] = wide;
        assert_eq!(
            check_grant_chain(&chain, &leaf).unwrap_err().0,
            format!("{BROADER}'resource'")
        );
        // A narrower grant is fine, and a single grant has nothing above it.
        let mut narrow = g[1].clone();
        narrow["credentialSubject"]["intent"]["resource"] = json!("https://x/a/b");
        narrow["validUntil"] = json!("2026-11-10T12:00:00Z");
        assert!(check_grant_chain(&[g[0].clone(), narrow], &leaf).is_ok());
        let mut alone = g[0].clone();
        alone["credentialSubject"]["intent"]["action"] = json!(["read", "write"]);
        assert!(check_grant_chain(&[alone], &leaf).is_ok());
        // The binding rule comes before the breadth rule.
        let mut unbound = g[1].clone();
        unbound["credentialSubject"]
            .as_object_mut()
            .unwrap()
            .remove(PARENT_GRANT_DIGEST);
        unbound["credentialSubject"]["intent"]["action"] = json!("write");
        assert_eq!(
            check_grant_chain(&[g[0].clone(), unbound], &leaf)
                .unwrap_err()
                .0,
            "Delegation refused: grant 2 of the grant chain is not bound to the grant before it (delegation_parent_mismatch)"
        );
    }

    #[test]
    fn a_malformed_first_grant_is_named_as_malformed() {
        let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
        for (dimension, value) in [
            ("rate", json!("lots")),
            ("policy", json!(["not", "an", "object"])),
            ("action", json!(7)),
            ("target", json!([1])),
            ("resource", json!(7)),
            ("time", json!("soon")),
        ] {
            let mut g1 = grant("did:web:root", "did:web:a", json!({}));
            if dimension == "time" {
                g1["validUntil"] = value;
            } else {
                g1["credentialSubject"]["intent"][dimension] = value;
            }
            let g2 = grant(
                "did:web:a",
                "did:web:b",
                json!({ "parentGrantDigest": grant_digest(&g1).unwrap() }),
            );
            let message = format!(
                "Delegation refused: grant 1 of the grant chain has a malformed '{dimension}'"
            );
            assert_eq!(
                check_grant_chain(&[g1.clone(), g2.clone()], &leaf)
                    .unwrap_err()
                    .0,
                message
            );
            // The same for the grant chain handed on with it.
            assert_eq!(grant_chain(&g1, &g2).unwrap_err().0, message);
            // A single grant has no grant before it: the signer checks it.
            assert!(check_grant_chain(&[g1], &leaf).is_ok(), "{dimension}");
        }
        // A malformed later grant is still a broader one.
        let g = flat3();
        let mut g2 = g[1].clone();
        g2["credentialSubject"]["intent"]["rate"] = json!("lots");
        assert_eq!(
            check_grant_chain(&[g[0].clone(), g2], &leaf).unwrap_err().0,
            format!("{BROADER}'rate'")
        );
    }

    #[test]
    fn the_helpers_refuse_a_grant_that_is_not_an_object() {
        let g = flat3();
        let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
        let no_intent = "Delegation refused: the parent grant carries no intent object";
        let mut no_subject = g[1].clone();
        no_subject["credentialSubject"] = json!("subject");
        let mut no_intent_member = g[1].clone();
        no_intent_member["credentialSubject"]
            .as_object_mut()
            .unwrap()
            .remove("intent");
        // An older nested grant after a bad one: every grant's intent is read
        // before any embedded chain is compared.
        let nested_after = nested("did:web:a", "did:web:b", &g[0]);
        for bad in [
            json!("x"),
            Value::Null,
            json!(5),
            json!(["nested"]),
            no_subject,
            no_intent_member,
        ] {
            for grants in [
                vec![bad.clone()],
                vec![g[0].clone(), bad.clone()],
                vec![bad.clone(), g[0].clone()],
                vec![bad.clone(), nested_after.clone()],
            ] {
                assert_eq!(
                    check_grant_chain(&grants, &leaf).unwrap_err().0,
                    no_intent,
                    "{bad}"
                );
                assert_eq!(
                    chain_links(&grants, &leaf).unwrap_err().0,
                    no_intent,
                    "{bad}"
                );
            }
        }
    }

    #[test]
    fn a_nested_grant_whose_embedded_link_lies_is_refused() {
        let g = flat3();
        let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
        for (field, message) in [
            (
                "subject",
                "Delegation refused: grant 2 of the grant chain embeds a link whose subject is not the delegatee of grant 1",
            ),
            (
                "issuer",
                "Delegation refused: grant 2 of the grant chain embeds a link whose issuer is not the issuer of grant 1",
            ),
        ] {
            let mut links = nested_chain(&g[0], &intent_to("did:web:b"));
            links[0][field] = json!("did:web:x");
            let lying = grant("did:web:a", "did:web:b", json!({ "delegationChain": links }));
            let grants = parent_grants(&lying).unwrap();
            assert_eq!(check_grant_chain(&grants, &leaf).unwrap_err().0, message);
            assert_eq!(
                check_grant_chain(&[g[0].clone(), lying.clone()], &leaf)
                    .unwrap_err()
                    .0,
                message
            );
            assert_eq!(chain_links(&grants, &leaf).unwrap_err().0, message);
            // A missing field lies too; null reads as missing.
            let mut links = nested_chain(&g[0], &intent_to("did:web:b"));
            links[0].as_object_mut().unwrap().remove(field);
            let missing = grant("did:web:a", "did:web:b", json!({ "delegationChain": links }));
            assert_eq!(
                check_grant_chain(&[g[0].clone(), missing], &leaf)
                    .unwrap_err()
                    .0,
                message
            );
        }
        // The chain equality is checked first, then each link's issuer, then
        // its subject.
        let mut links = nested_chain(&g[0], &intent_to("did:web:b"));
        links[0]["issuer"] = json!("did:web:x");
        links[0]["subject"] = json!("did:web:x");
        let both = grant(
            "did:web:a",
            "did:web:b",
            json!({ "delegationChain": links }),
        );
        assert!(check_grant_chain(&[g[0].clone(), both.clone()], &leaf)
            .unwrap_err()
            .0
            .contains("whose issuer is not"));
        let other_root = grant("did:web:root", "did:web:a", json!({"note": "other"}));
        assert_eq!(
            check_grant_chain(&[other_root, both], &leaf).unwrap_err().0,
            "Delegation refused: grant 2 of the grant chain embeds a chain that is not the grants before it"
        );
        // An honest nested grant: its link is copied as it is.
        let honest = nested("did:web:a", "did:web:b", &g[0]);
        let out = check_grant_chain(&[g[0].clone(), honest.clone()], &leaf).unwrap();
        assert_eq!(out[0], honest["credentialSubject"]["delegationChain"][0]);
        assert_eq!(out[1]["parentCredential"], honest);
    }

    #[test]
    fn an_issuer_object_is_carried_as_its_id() {
        let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
        let mut root = grant("did:web:root", "did:web:a", json!({}));
        root["issuer"] = json!({"id": "did:web:root", "name": "Root"});
        let links = check_grant_chain(std::slice::from_ref(&root), &leaf).unwrap();
        assert_eq!(links[0]["issuer"], json!("did:web:root"));
        assert_eq!(links[0]["parentCredential"], root);
        assert_eq!(chain_binding_problem(&links), None);
        // chain_links on its own: an issuer that is not a string is "".
        let mut odd = root.clone();
        odd["issuer"] = json!(42);
        assert_eq!(
            chain_links(std::slice::from_ref(&odd), &leaf).unwrap()[0]["issuer"],
            json!("")
        );
    }

    #[test]
    fn an_issuer_that_is_not_a_did_string_is_refused() {
        let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
        for issuer in [
            json!(42),
            json!({"id": 5}),
            json!({"name": "Root"}),
            json!(["did:key:z"]),
            json!(true),
        ] {
            let mut root = grant("did:web:root", "did:web:a", json!({}));
            root["issuer"] = issuer.clone();
            assert_eq!(
                check_grant_chain(&[root], &leaf).unwrap_err().0,
                "Delegation refused: grant 1 of the grant chain has an issuer that is not a string or an object with a string id",
                "{issuer}"
            );
        }
        // An empty issuer, or an empty issuer object, is not a signed grant.
        for issuer in [json!(""), json!({}), Value::Null, json!(0), json!([])] {
            let mut root = grant("did:web:root", "did:web:a", json!({}));
            root["issuer"] = issuer.clone();
            assert_eq!(
                check_grant_chain(&[root], &leaf).unwrap_err().0,
                "Delegation refused: the parent grant is not a signed credential",
                "{issuer}"
            );
        }
    }

    #[test]
    fn links_are_copies_of_the_grants() {
        // Owned values: the links equal the grants and intents they came from,
        // and changing one leaves the caller's grants as they were.
        let g = flat3();
        let before = g.clone();
        let leaf = json!({"action": "read", "target": "t", "resource": "https://x/a"});
        let mut links = check_grant_chain(&g, &leaf).unwrap();
        assert_eq!(links[0]["parentCredential"], g[0]);
        assert_eq!(links[0]["intent"], g[1]["credentialSubject"]["intent"]);
        links[0]["intent"]["action"] = json!("write");
        links[1]["parentCredential"]["credentialSubject"]["intent"]["action"] = json!("write");
        assert_eq!(g, before);
    }

    #[test]
    fn chain_capability_inherits_down_the_chain() {
        let mut g = flat3();
        g[0]["credentialSubject"]["intent"]["rate"] = json!("10/hour");
        g[2]["credentialSubject"]["intent"]
            .as_object_mut()
            .unwrap()
            .remove("resource");
        let cap = chain_capability(&g, false).unwrap();
        assert_eq!(cap["intent"]["resource"], json!("https://x/a"));
        assert_eq!(cap["rate"], json!("10/hour"));
        assert_eq!(cap["subject"], json!("did:web:c"));
        assert!(cap.get("validFrom").is_none());
        let timed = chain_capability(&g, true).unwrap();
        assert_eq!(timed["validUntil"], json!("2026-11-11T00:00:00Z"));
    }

    #[test]
    fn python_repr_of_quoted_values() {
        assert_eq!(py_repr_str("did:web:a"), "'did:web:a'");
        assert_eq!(py_repr_str("it's"), "\"it's\"");
        assert_eq!(py_repr_str("a'b\"c"), "'a\\'b\"c'");
        assert_eq!(py_repr_str("a\\b\n\u{1}"), "'a\\\\b\\n\\x01'");
        assert_eq!(py_repr(None), "None");
        assert_eq!(py_repr(Some(&json!(["x", 1]))), "['x', 1]");
        // Every character Python's isprintable() rejects is escaped, in the
        // shortest form that holds it (repr in CPython 3.12).
        assert_eq!(
            py_repr_str(
                "\u{a0}\u{ad}\u{200b}\u{2028}\u{feff}\u{e000}\u{e0001}\u{10ffff} é中😀\u{3000}\u{7f}\u{1b}\u{85}"
            ),
            "'\\xa0\\xad\\u200b\\u2028\\ufeff\\ue000\\U000e0001\\U0010ffff é中😀\\u3000\\x7f\\x1b\\x85'"
        );
        assert_eq!(py_repr_str("it's \u{2029}"), "\"it's \\u2029\"");
        assert_eq!(py_repr_str("a\u{378}b"), "'a\\u0378b'");
        assert_eq!(
            py_repr(Some(&json!({"k\u{0}": ["\u{2066}"]}))),
            "{'k\\x00': ['\\u2066']}"
        );
    }

    #[test]
    fn python_repr_of_numbers() {
        // Each JSON text read the way a verifier reads it, then written the
        // way Python's repr writes json.loads(text) (CPython 3.12).
        for (text, expected) in [
            ("0.0", "0.0"),
            ("-0.0", "-0.0"),
            ("1.0", "1.0"),
            ("-1.5", "-1.5"),
            ("0.1", "0.1"),
            ("0.30000000000000004", "0.30000000000000004"),
            ("100.0", "100.0"),
            ("1e2", "100.0"),
            ("0.0001", "0.0001"),
            ("0.00001", "1e-05"),
            ("1e-5", "1e-05"),
            ("0.000123", "0.000123"),
            ("9.999e-5", "9.999e-05"),
            ("1e-7", "1e-07"),
            ("123.456", "123.456"),
            ("9999999999999998.0", "9999999999999998.0"),
            ("1e16", "1e+16"),
            ("12345678901234567.0", "1.2345678901234568e+16"),
            ("1e21", "1e+21"),
            ("1e22", "1e+22"),
            ("1.5e300", "1.5e+300"),
            ("1.7976931348623157e308", "1.7976931348623157e+308"),
            ("5e-324", "5e-324"),
            ("2.2250738585072014e-308", "2.2250738585072014e-308"),
            // An exact tie between two shortest forms goes to the even digit.
            ("588197768793114.25", "588197768793114.2"),
            ("-164193784243384.125", "-164193784243384.12"),
            ("6.02214076e23", "6.02214076e+23"),
            ("-2.5e-10", "-2.5e-10"),
            ("4.35", "4.35"),
            ("1e100", "1e+100"),
            ("1E-100", "1e-100"),
            ("123e-20", "1.23e-18"),
            ("5", "5"),
            ("-7", "-7"),
            ("0", "0"),
            ("18446744073709551615", "18446744073709551615"),
            ("-9223372036854775808", "-9223372036854775808"),
            (
                "{\"maxSpend\": 1e-05, \"ratio\": [0.5, 1e16, 2]}",
                "{'maxSpend': 1e-05, 'ratio': [0.5, 1e+16, 2]}",
            ),
        ] {
            let value: Value = serde_json::from_str(text).unwrap();
            assert_eq!(py_repr(Some(&value)), expected, "{text}");
        }
        assert_eq!(py_repr_float(f64::INFINITY), "inf");
        assert_eq!(py_repr_float(f64::NEG_INFINITY), "-inf");
        assert_eq!(py_repr_float(f64::NAN), "nan");
    }
}