structured-pkix 0.6.3

Borrowed X.509 certificates and provider-neutral certification path validation
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
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
use super::{Extensions, Recognizer, is_known, read};
use crate::error::{ErrorCode, Result};
use crate::fixtures::{bits, boolean, extension, int, octets, oid as oid_of, seq, tlv};
use crate::oid;
use alloc::vec::Vec;
use structured_asn1::{Oid, Parser};

fn parse<'a>(parser: &'a Parser, der: &'a [u8]) -> Result<Extensions<'a>> {
    let mut reader = parser.read(der, 0).unwrap();
    let element = reader.next_element().unwrap().unwrap();
    read(&reader, &element, "test")
}

#[test]
fn full_extension_iteration_pays_before_exposing_metadata() {
    // The full iterator must not bypass the same metadata admission enforced
    // by criticals/get. A noncritical value still costs one traversal step.
    let execution = crate::fixtures::memory();
    let parser = Parser::der(execution.clone());
    let der = seq(&[extension(oid::BASIC_CONSTRAINTS, false, &seq(&[]))]);
    let extensions = parse(&parser, &der).unwrap();
    let before = execution.work_used();
    let mut entries = extensions.iter(&execution);
    assert_eq!(
        execution.work_used(),
        before,
        "constructor performs no traversal"
    );
    let item = entries.next().unwrap().unwrap();
    assert_eq!(item.kind(), oid::BASIC_CONSTRAINTS);
    assert_eq!(execution.work_used(), before + 1);
    assert!(entries.next().is_none());
    assert!(entries.next().is_none());
    assert_eq!(execution.work_used(), before + 1);
}

#[test]
fn embedded_certificate_extension_catalogue_and_duplicate_index_share_local_work() {
    // CMS carried certificates reuse this parser. Both the retained extension
    // catalogue and temporary hashbrown duplicate index must pay its local
    // ceiling before allocation/hash/probes, not only the aggregate account.
    let der = seq(&[extension(oid::BASIC_CONSTRAINTS, false, &seq(&[]))]);
    let execution = crate::fixtures::memory();
    let parser = Parser::der(execution.clone());
    let extensions = parse(&parser, &der).unwrap();
    let full_work = u64::try_from(execution.work_used()).unwrap();
    drop(extensions);
    assert_eq!(execution.used(), 0);
    let limited = crate::fixtures::memory();
    let parser = Parser::new(
        structured_asn1::Encoding::Der,
        structured_asn1::Limits {
            max_work: full_work - 1,
            ..structured_asn1::Limits::default()
        },
        limited.clone(),
    );
    let error = parse(&parser, &der)
        .expect_err("every extension storage/index operation belongs to the producer");
    assert!(error.is_resource());
    assert_eq!(error.field(), "test");
    assert_eq!(limited.used(), 0);
}

#[test]
fn critical_filter_refuses_unfunded_noncritical_scanning_and_then_stops() {
    // A critical-free answer still visits every metadata entry. Exhaustion
    // before the last noncritical element must not look like an empty result.
    use structured_asn1::memory::{Memory, MemoryAccount};
    let der = seq(&[
        extension(oid::BASIC_CONSTRAINTS, false, &seq(&[])),
        extension(oid::KEY_USAGE, false, &bits(&[0x80])),
    ]);
    let parser = Parser::der(crate::fixtures::memory());
    let items = parse(&parser, &der).unwrap();
    let execution = Memory::new(alloc::sync::Arc::new(MemoryAccount::new(0, 1)));
    let mut criticals = items.criticals(&execution);
    let first = criticals.next();
    assert!(matches!(first, Some(Err(error)) if error.is_resource()));
    assert_eq!(execution.work_used(), 1);
    assert!(criticals.next().is_none());
    assert!(criticals.next().is_none());
    assert_eq!(execution.work_used(), 1);
}

#[test]
fn critical_filter_pays_for_the_visited_prefix_and_a_complete_miss() {
    // First-match admission stops at the critical entry; later metadata
    // needs new work. Empty/end states never scan or charge again.
    use structured_asn1::memory::{Memory, MemoryAccount};
    let der = seq(&[
        extension(oid::BASIC_CONSTRAINTS, false, &seq(&[])),
        extension(oid::KEY_USAGE, true, &bits(&[0x80])),
        extension(oid::SUBJECT_KEY_IDENTIFIER, false, &octets(b"key")),
    ]);
    let parser = Parser::der(crate::fixtures::memory());
    let items = parse(&parser, &der).unwrap();
    let execution = Memory::new(alloc::sync::Arc::new(MemoryAccount::new(0, 2)));
    let mut entries = items.criticals(&execution);
    assert_eq!(entries.next().unwrap().unwrap().kind(), oid::KEY_USAGE);
    assert_eq!(execution.work_used(), 2);
    assert!(entries.next().unwrap().unwrap_err().is_resource());
    assert!(entries.next().is_none());
    assert_eq!(execution.work_used(), 2);
    let full = Memory::new(alloc::sync::Arc::new(MemoryAccount::new(0, 3)));
    let mut entries = items.criticals(&full);
    assert!(entries.next().unwrap().is_ok());
    assert!(entries.next().is_none());
    assert!(entries.next().is_none());
    assert_eq!(full.work_used(), 3);
    let empty = Extensions::empty(parser.memory());
    let denied = Memory::new(alloc::sync::Arc::new(MemoryAccount::new(0, 0)));
    assert!(empty.criticals(&denied).next().is_none());
    assert_eq!(denied.work_used(), 0);
}

#[test]
fn extension_reader_inherits_container_depth_and_offset() {
    // An attacker must not recover a fresh depth allowance inside extnValue.
    // The borrowed window must also retain its original document offset.
    let value = seq(&[boolean(true)]);
    let der = seq(&[extension(oid::BASIC_CONSTRAINTS, false, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    let item = extensions
        .get(oid::BASIC_CONSTRAINTS, extensions.memory())
        .unwrap()
        .unwrap();
    let mut reader = item.reader(item.parser().memory()).unwrap();
    assert_eq!(reader.depth(), 3);
    let element = reader.next_element().unwrap().unwrap();
    assert_eq!(element.span().start, item.value_span.start);
    assert_eq!(element.as_bytes().as_ptr(), item.value().as_ptr());
}

#[test]
fn extension_lookup_admits_each_oid_comparison_before_matching() {
    // Early matches pay only the visited prefix. A long query cannot obtain
    // a match or absence before its comparison has been admitted.
    use structured_asn1::memory::{Memory, MemoryAccount};
    let der = seq(&[
        extension(oid::BASIC_CONSTRAINTS, false, &seq(&[])),
        extension(oid::KEY_USAGE, false, &bits(&[0x80])),
    ]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    let first_work = 1 + oid::BASIC_CONSTRAINTS.as_bytes().len();
    let execution = Memory::new(alloc::sync::Arc::new(MemoryAccount::new(0, first_work)));
    assert!(
        extensions
            .get(oid::BASIC_CONSTRAINTS, &execution)
            .unwrap()
            .is_some()
    );
    assert_eq!(execution.work_used(), first_work);
    let error = extensions.get(oid::KEY_USAGE, &execution).unwrap_err();
    assert!(error.is_resource());
    assert_eq!(error.offset(), extensions.items[0].span.start);
    assert_eq!(execution.work_used(), first_work);

    let mut encoded = [0x81; 80];
    encoded[79] = 1;
    let long = Oid::from_bytes(&encoded);
    let short = Memory::new(alloc::sync::Arc::new(MemoryAccount::new(0, 80)));
    assert!(extensions.get(long, &short).unwrap_err().is_resource());
    assert_eq!(short.work_used(), 0);
    let full = Memory::new(alloc::sync::Arc::new(MemoryAccount::new(0, 162)));
    assert!(extensions.get(long, &full).unwrap().is_none());
    assert_eq!(full.work_used(), 162);
    assert_eq!(full.used(), 0);
}

#[test]
fn lazy_extension_uses_current_work_and_storage_without_moving_old_charge() {
    // A retained extension collection in A must not finance B's decode.
    // Refusals remain located resource errors; successful nested vectors
    // are stored in B while the original collection remains charged to A.
    use structured_asn1::memory::{Memory, MemoryAccount};
    let value = seq(&[crate::fixtures::implicit(2, b"example.ua")]);
    let der = seq(&[extension(oid::SUBJECT_ALT_NAME, false, &value)]);
    let original = crate::fixtures::memory();
    let parser = Parser::der(original.clone());
    let extensions = parse(&parser, &der).unwrap();
    let item = extensions
        .get(oid::SUBJECT_ALT_NAME, extensions.memory())
        .unwrap()
        .unwrap();
    let before = original.work_used();
    let held = original.used();
    let no_work = Memory::new(alloc::sync::Arc::new(MemoryAccount::new(0, 0)));
    let error = extensions.subject_alt_name(&no_work).unwrap_err();
    assert!(error.is_resource());
    assert_eq!(error.offset(), item.span().start);
    let no_storage = Memory::new(alloc::sync::Arc::new(MemoryAccount::new(0, 10_000)));
    let error = extensions.subject_alt_name(&no_storage).unwrap_err();
    assert!(error.is_resource());
    assert_eq!(
        error.code(),
        ErrorCode::Encoding(structured_asn1::ErrorCode::LimitExceeded(
            structured_asn1::Limit::Memory
        ))
    );
    let execution = crate::fixtures::memory();
    let names = extensions.subject_alt_name(&execution).unwrap().unwrap();
    assert!(names.memory().same_account(&execution));
    assert!(matches!(
        &*names,
        [crate::general_name::GeneralName::Dns("example.ua")]
    ));
    assert_eq!(original.work_used(), before);
    assert_eq!(original.used(), held);
    assert!(execution.used() > 0);
    drop(names);
    assert_eq!(execution.used(), 0);
    drop(extensions);
    assert_eq!(original.used(), 0);
}

/// A scheme that knows one extension of its own.
struct Scheme(Oid<'static>);

impl Recognizer for Scheme {
    type Error = core::convert::Infallible;
    fn recognizes(
        &self,
        kind: Oid<'_>,
        _execution: &structured_asn1::memory::Memory,
    ) -> core::result::Result<bool, Self::Error> {
        Ok(kind == self.0)
    }
}

/// A scheme that can interpret one other-name type of its own.
struct NameScheme(Oid<'static>);

impl Recognizer for NameScheme {
    type Error = core::convert::Infallible;
    fn recognizes(
        &self,
        _kind: Oid<'_>,
        _execution: &structured_asn1::memory::Memory,
    ) -> core::result::Result<bool, Self::Error> {
        Ok(false)
    }

    fn recognizes_other_name(
        &self,
        type_id: Oid<'_>,
        _execution: &structured_asn1::memory::Memory,
    ) -> core::result::Result<bool, Self::Error> {
        Ok(type_id == self.0)
    }
}

/// A scheme that states the containment rule for one other-name type, and
/// reads none.
struct ConstraintScheme(Oid<'static>);

impl Recognizer for ConstraintScheme {
    type Error = core::convert::Infallible;
    fn recognizes(
        &self,
        _kind: Oid<'_>,
        _execution: &structured_asn1::memory::Memory,
    ) -> core::result::Result<bool, Self::Error> {
        Ok(false)
    }

    fn recognizes_name_constraint(
        &self,
        type_id: Oid<'_>,
        _execution: &structured_asn1::memory::Memory,
    ) -> core::result::Result<bool, Self::Error> {
        Ok(type_id == self.0)
    }
}

/// A scheme that understands one access method of its own, other-name
/// locations of the same identifier included.
struct AccessScheme(Oid<'static>);

impl Recognizer for AccessScheme {
    type Error = core::convert::Infallible;
    fn recognizes(
        &self,
        _kind: Oid<'_>,
        _execution: &structured_asn1::memory::Memory,
    ) -> core::result::Result<bool, Self::Error> {
        Ok(false)
    }

    fn recognizes_other_name(
        &self,
        type_id: Oid<'_>,
        _execution: &structured_asn1::memory::Memory,
    ) -> core::result::Result<bool, Self::Error> {
        Ok(type_id == self.0)
    }

    fn recognizes_access_method(
        &self,
        method: Oid<'_>,
        _execution: &structured_asn1::memory::Memory,
    ) -> core::result::Result<bool, Self::Error> {
        Ok(method == self.0)
    }
}

#[test]
fn an_extension_keeps_its_value_encoded() {
    let value = seq(&[boolean(true), int(3)]);
    let der = seq(&[extension(oid::BASIC_CONSTRAINTS, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();

    let found = extensions
        .get(oid::BASIC_CONSTRAINTS, extensions.memory())
        .unwrap()
        .unwrap();
    assert!(found.is_critical());
    // The octet string is a wrapper: what it holds is a structure of its own,
    // and it is handed on as it arrived rather than decoded here.
    assert_eq!(found.value(), &value[..]);
    assert_eq!(found.span().start, 2);
}

#[test]
fn what_this_crate_reads_needs_no_scheme_to_recognize_it() {
    assert!(is_known(oid::BASIC_CONSTRAINTS));
    assert!(is_known(oid::QC_STATEMENTS));
    // Named here, and not read into a structure of its own, so a scheme that
    // needs it must say it knows it.
    assert!(!is_known(oid::PRIVATE_KEY_USAGE_PERIOD));
}

#[test]
fn a_scheme_says_which_of_its_own_extensions_it_knows() {
    let mine = Oid::from_bytes(&[0x2a, 0x86, 0x24, 0x02, 0x01]);
    let other = Oid::from_bytes(&[0x2a, 0x86, 0x24, 0x02, 0x02]);
    let der = seq(&[
        extension(mine, true, &octets(&[0x01])),
        extension(other, true, &octets(&[0x02])),
    ]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();

    let scheme = Scheme(mine);
    let blocked: Vec<_> = extensions
        .unhandled_critical(&scheme, parser.memory())
        .unwrap()
        .iter()
        .map(|extension| extension.kind())
        .collect();
    assert_eq!(blocked, [other]);

    // Both are still there to be reported, whether or not anything knows them.
    assert_eq!(extensions.len(), 2);
    for extension in extensions.iter(parser.memory()) {
        assert!(extension.unwrap().is_critical());
    }
}

#[test]
fn extensions_that_say_nothing_or_say_it_twice_are_refused() {
    // Nothing at all, where the schema requires at least one.
    let parser = Parser::der(crate::fixtures::memory());
    let empty = seq(&[]);
    let error = parse(&parser, &empty).unwrap_err();
    assert_eq!(error.code(), ErrorCode::EmptySequence);

    // The same extension twice, with different values: which of them applies
    // would have no answer.
    let parser = Parser::der(crate::fixtures::memory());
    let twice = seq(&[
        extension(oid::KEY_USAGE, false, &bits(&[0x80])),
        extension(oid::KEY_USAGE, false, &bits(&[0x04])),
    ]);
    let error = parse(&parser, &twice).unwrap_err();
    assert_eq!(error.code(), ErrorCode::DuplicateExtension);
}

#[test]
fn an_extension_that_is_not_shaped_like_one_is_refused() {
    // A value that is not wrapped in an octet string.
    let parser = Parser::der(crate::fixtures::memory());
    let der = seq(&[seq(&[oid_of(oid::KEY_USAGE), bits(&[0x80])])]);
    let error = parse(&parser, &der).unwrap_err();
    assert_eq!(
        error.code(),
        ErrorCode::Encoding(structured_asn1::ErrorCode::UnexpectedTag)
    );

    // No value at all.
    let parser = Parser::der(crate::fixtures::memory());
    let der = seq(&[seq(&[oid_of(oid::KEY_USAGE)])]);
    let error = parse(&parser, &der).unwrap_err();
    assert_eq!(error.code(), ErrorCode::MissingField);

    // Something after the value.
    let parser = Parser::der(crate::fixtures::memory());
    let der = seq(&[seq(&[
        oid_of(oid::KEY_USAGE),
        octets(&bits(&[0x80])),
        int(1),
    ])]);
    let error = parse(&parser, &der).unwrap_err();
    assert_eq!(error.code(), ErrorCode::TrailingData);
}

#[test]
fn a_default_written_out_is_refused_under_der_and_read_under_ber() {
    // DER requires a DEFAULT component to be omitted, so a flag written out
    // as FALSE is a second spelling of the absent flag and not DER at all.
    let der = seq(&[seq(&[
        oid_of(oid::SUBJECT_KEY_IDENTIFIER),
        boolean(false),
        octets(&octets(&[0x01, 0x02])),
    ])]);

    let strict = Parser::der(crate::fixtures::memory());
    let error = parse(&strict, &der).unwrap_err();
    assert_eq!(error.code(), ErrorCode::MalformedValue);

    // BER has no such rule, and both spellings say the extension may be
    // ignored by a reader that does not know it.
    let lenient = Parser::ber(crate::fixtures::memory());
    let extensions = parse(&lenient, &der).unwrap();
    assert!(
        !extensions
            .get(oid::SUBJECT_KEY_IDENTIFIER, extensions.memory())
            .unwrap()
            .unwrap()
            .is_critical()
    );
}

#[test]
fn a_malformed_known_critical_extension_still_blocks() {
    // A critical key usage whose value is an integer: the identifier is
    // known, the value never parsed, and nothing here understood what the
    // certificate demanded be understood. Filtering it out by identifier
    // alone would leave a validator seeing no blocker.
    let der = seq(&[extension(oid::KEY_USAGE, true, &int(3))]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();

    let blocked: Vec<_> = extensions
        .unhandled_critical(&(), parser.memory())
        .unwrap()
        .iter()
        .map(|item| item.kind())
        .collect();
    assert_eq!(blocked, [oid::KEY_USAGE]);

    // The same identifier with a value that parses blocks nothing:
    // digitalSignature in the minimal spelling, one data bit and seven of
    // padding.
    let der = seq(&[extension(oid::KEY_USAGE, true, &tlv(0x03, &[0x07, 0x80]))]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        0
    );
}

#[test]
fn extension_values_decode_as_der_whatever_parser_is_passed() {
    // The lazy accessors take the caller's parser for its budget, and a
    // caller that read a CMS envelope naturally passes a BER one. The
    // extension value lives inside the DER certificate, so a spelled-out
    // default the BER leniency would accept must still be refused, and the
    // malformed critical extension must still block.
    let der = seq(&[extension(
        oid::BASIC_CONSTRAINTS,
        true,
        &seq(&[boolean(false)]),
    )]);
    let parser = Parser::ber(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();

    let error = extensions
        .basic_constraints(extensions.memory())
        .unwrap_err();
    assert_eq!(error.code(), ErrorCode::MalformedValue);
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        1
    );
}

#[test]
fn an_unknown_other_name_type_in_a_critical_name_extension_blocks() {
    use crate::fixtures::{context, seq as fseq, utf8};

    // An otherName's value means what its type identifier says, and this
    // crate names no such types itself: a critical name extension carrying
    // one nobody claims was not understood, though it still reads for the
    // report.
    let other = fseq(&[context(
        0,
        &[oid_of(oid::USER_ID), context(0, &[utf8("uid")])],
    )]);
    let der = seq(&[extension(oid::SUBJECT_ALT_NAME, true, &other)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        1
    );
    // The names still read: the answer above is about understanding.
    assert!(
        extensions
            .subject_alt_name(extensions.memory())
            .unwrap()
            .is_some()
    );

    // A scheme that claims the type, in the other-name role, stops it
    // blocking.
    let scheme = NameScheme(oid::USER_ID);
    assert_eq!(
        extensions
            .unhandled_critical(&scheme, parser.memory())
            .unwrap()
            .len(),
        0
    );
}

#[test]
fn a_scheme_clears_a_critical_extension_only_where_its_value_is_der() {
    // "the corresponding ASN.1 DER encoded structure is the value of the
    // octet string extnValue" (RFC 5280 4.1.2.9), one structure and nothing
    // beside it. A scheme says which identifiers are its to decode, not that
    // any bytes under one are readable, and it never sees the value: a claim
    // over a payload that is not a value of any type would clear a critical
    // demand nobody decoded.
    let mine = Oid::from_bytes(&[0x2a, 0x86, 0x24, 0x02, 0x03]);
    let scheme = Scheme(mine);
    for value in [
        // Nothing at all.
        Vec::new(),
        // An integer written a byte longer than it needs, which is a second
        // spelling of the same value.
        tlv(0x02, &[0x00, 0x01]),
        // The same one level down, under a container the scheme would enter.
        seq(&[tlv(0x02, &[0x00, 0x01])]),
        // A complete value and then bytes after it.
        [int(1), int(2)].concat(),
        // A header whose length runs past the payload.
        tlv(0x02, &[0x01]).into_iter().take(2).collect(),
    ] {
        let der = seq(&[extension(mine, true, &value)]);
        let parser = Parser::der(crate::fixtures::memory());
        let extensions = parse(&parser, &der).unwrap();
        assert_eq!(
            extensions
                .unhandled_critical(&scheme, parser.memory())
                .unwrap()
                .len(),
            1,
            "{value:02x?}"
        );
    }

    // One complete value is the scheme's to read, and its claim clears it.
    let der = seq(&[extension(mine, true, &seq(&[int(1), octets(&[0x02])]))]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&scheme, parser.memory())
            .unwrap()
            .len(),
        0
    );
}

#[test]
fn an_unknown_access_method_in_a_critical_extension_blocks() {
    use crate::fixtures::{implicit, seq as fseq};

    // An access description's meaning is its method identifier: one nobody
    // claims is a critical access demand this run cannot interpret, though
    // it still reads for the report.
    let mine = Oid::from_bytes(&[0x2a, 0x86, 0x24, 0x06, 0x01]);
    let value = fseq(&[fseq(&[oid_of(mine), implicit(6, b"https://x.example.ua")])]);
    let der = seq(&[extension(oid::AUTHORITY_INFO_ACCESS, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        1
    );
    let scheme = AccessScheme(mine);
    assert_eq!(
        extensions
            .unhandled_critical(&scheme, parser.memory())
            .unwrap()
            .len(),
        0
    );

    // A method this crate names stays handled.
    let value = fseq(&[fseq(&[
        oid_of(oid::OCSP),
        implicit(6, b"https://ocsp.example.ua"),
    ])]);
    let der = seq(&[extension(oid::AUTHORITY_INFO_ACCESS, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        0
    );
}

#[test]
fn a_currency_code_that_is_not_alphabetic_blocks() {
    use crate::fixtures::{printable, seq as fseq};

    // The alphabetic ISO 4217 choice is three uppercase letters: a digit or
    // punctuation in the triple names no currency.
    for code in ["A1?", "uah", "U-H"] {
        let value = fseq(&[fseq(&[
            oid_of(oid::QC_LIMIT_VALUE),
            fseq(&[printable(code), int(1000), int(0)]),
        ])]);
        let der = seq(&[extension(oid::QC_STATEMENTS, true, &value)]);
        let parser = Parser::der(crate::fixtures::memory());
        let extensions = parse(&parser, &der).unwrap();
        assert_eq!(
            extensions
                .unhandled_critical(&(), parser.memory())
                .unwrap()
                .len(),
            1,
            "{code}"
        );
    }
}

#[test]
fn a_cps_pointer_that_is_not_a_uri_blocks() {
    use crate::fixtures::{ia5, seq as fseq};
    let policy = structured_asn1::Oid::from_bytes(&[0x2a, 0x86, 0x24, 0x03, 0x01]);

    // The pointer's type is a URI: non-empty IA5 text without a scheme, or
    // outside the URI alphabet, points at nothing.
    for pointer in [&b"not-a-uri"[..], b"/relative", b"https:%"] {
        let mut ia5_pointer = alloc::vec![0x16, u8::try_from(pointer.len()).unwrap()];
        ia5_pointer.extend_from_slice(pointer);
        let value = fseq(&[fseq(&[
            oid_of(policy),
            fseq(&[fseq(&[oid_of(oid::CPS_QUALIFIER), ia5_pointer])]),
        ])]);
        let der = seq(&[extension(oid::CERTIFICATE_POLICIES, true, &value)]);
        let parser = Parser::der(crate::fixtures::memory());
        let extensions = parse(&parser, &der).unwrap();
        assert_eq!(
            extensions
                .unhandled_critical(&(), parser.memory())
                .unwrap()
                .len(),
            1,
            "{pointer:02x?}"
        );
    }

    // A genuine pointer stays interpreted. The pointer is a URI, and that
    // production carries an optional fragment (RFC 3986 3), which is how a
    // statement points at the section that applies: reading it as the
    // fragment-free form would block a policy over the part of the pointer
    // that says which practice it means.
    for pointer in [
        "https://cps.example.ua",
        "https://cps.example.ua/text#signing",
        "https://cps.example.ua/text?v=2#signing",
        "https://cps.example.ua/text#",
    ] {
        let value = fseq(&[fseq(&[
            oid_of(policy),
            fseq(&[fseq(&[oid_of(oid::CPS_QUALIFIER), ia5(pointer)])]),
        ])]);
        let der = seq(&[extension(oid::CERTIFICATE_POLICIES, true, &value)]);
        let parser = Parser::der(crate::fixtures::memory());
        let extensions = parse(&parser, &der).unwrap();
        assert_eq!(
            extensions
                .unhandled_critical(&(), parser.memory())
                .unwrap()
                .len(),
            0,
            "{pointer}"
        );
    }

    // A second fragment delimiter is outside the production either way.
    let value = fseq(&[fseq(&[
        oid_of(policy),
        fseq(&[fseq(&[
            oid_of(oid::CPS_QUALIFIER),
            ia5("https://cps.example.ua/text#a#b"),
        ])]),
    ])]);
    let der = seq(&[extension(oid::CERTIFICATE_POLICIES, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        1
    );
}

#[test]
fn recognizing_an_extension_does_not_vouch_for_an_other_name_of_the_same_oid() {
    use crate::fixtures::{context, seq as fseq, utf8};

    // The recognizer answers by role: claiming an extension with an
    // identifier says nothing about interpreting an other-name whose type
    // reuses it.
    let mine = Oid::from_bytes(&[0x2a, 0x86, 0x24, 0x07, 0x01]);
    let other = fseq(&[context(0, &[oid_of(mine), context(0, &[utf8("v")])])]);
    let der = seq(&[extension(oid::SUBJECT_ALT_NAME, true, &other)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    let scheme = Scheme(mine);
    assert_eq!(
        extensions
            .unhandled_critical(&scheme, parser.memory())
            .unwrap()
            .len(),
        1
    );
}

#[test]
fn a_mailbox_location_for_a_publication_method_blocks() {
    use crate::fixtures::{implicit, seq as fseq};

    // The issuing-certificate and repository methods publish over transfer
    // protocols or the directory (RFC 5280 4.2.2.1, 4.2.2.2): a mailbox
    // identifies no publication location for them.
    for method in [oid::CA_ISSUERS, oid::CA_REPOSITORY] {
        let value = fseq(&[fseq(&[oid_of(method), implicit(1, b"ca@example.ua")])]);
        let der = seq(&[extension(oid::AUTHORITY_INFO_ACCESS, true, &value)]);
        let parser = Parser::der(crate::fixtures::memory());
        let extensions = parse(&parser, &der).unwrap();
        assert_eq!(
            extensions
                .unhandled_critical(&(), parser.memory())
                .unwrap()
                .len(),
            1,
            "{method:?}"
        );
    }
}

#[test]
fn an_attribute_outside_its_size_bounds_in_a_critical_name_blocks() {
    use crate::fixtures::{context, printable, seq as fseq, set as fset};

    // A country of three characters wears the type while naming no country:
    // the attribute is exactly two (RFC 5280 appendix A). The same appendix
    // bounds a common name at sixty-four.
    let long_country = fseq(&[context(
        4,
        &[fseq(&[fset(&[fseq(&[
            oid_of(oid::COUNTRY),
            printable("USA"),
        ])])])],
    )]);
    let der = seq(&[extension(oid::SUBJECT_ALT_NAME, true, &long_country)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        1
    );

    let oversized = "a".repeat(65);
    let long_common = fseq(&[context(
        4,
        &[fseq(&[fset(&[fseq(&[
            oid_of(oid::COMMON_NAME),
            crate::fixtures::utf8(&oversized),
        ])])])],
    )]);
    let der = seq(&[extension(oid::SUBJECT_ALT_NAME, true, &long_common)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        1
    );
}

#[test]
fn an_unknown_other_name_in_a_critical_authority_key_identifier_blocks() {
    use crate::fixtures::{context, implicit, seq as fseq, set as fset, utf8};
    let unknown = Oid::from_bytes(&[0x2a, 0x86, 0x24, 0x06, 0x03]);

    // The issuer names inside the identifier are the identity it points at:
    // an other-name nobody claims there was never interpreted. A directory
    // name rides beside it so the pair itself stays validly formed.
    let other = context(0, &[oid_of(unknown), context(0, &[int(1)])]);
    let root = fseq(&[fset(&[fseq(&[oid_of(oid::COMMON_NAME), utf8("Root")])])]);
    let value = fseq(&[
        implicit(0, &[0xab]),
        context(1, &[other, context(4, &[root])]),
        implicit(2, &[0x05]),
    ]);
    let der = seq(&[extension(oid::AUTHORITY_KEY_IDENTIFIER, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        1
    );
    let scheme = NameScheme(unknown);
    assert_eq!(
        extensions
            .unhandled_critical(&scheme, parser.memory())
            .unwrap()
            .len(),
        0
    );
}

#[test]
fn an_unknown_other_name_in_a_critical_distribution_point_blocks() {
    use crate::fixtures::{context, seq as fseq};
    let unknown = Oid::from_bytes(&[0x2a, 0x86, 0x24, 0x06, 0x04]);

    // The point's names say where the revocation evidence is: an other-name
    // nobody claims identifies nothing this run can use.
    let other = context(0, &[oid_of(unknown), context(0, &[int(1)])]);
    let point = fseq(&[context(0, &[context(0, &[other])])]);
    let der = seq(&[extension(
        oid::CRL_DISTRIBUTION_POINTS,
        true,
        &fseq(&[point]),
    )]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        1
    );
    let scheme = NameScheme(unknown);
    assert_eq!(
        extensions
            .unhandled_critical(&scheme, parser.memory())
            .unwrap()
            .len(),
        0
    );
}

#[test]
fn a_pds_location_that_is_not_a_url_blocks() {
    use crate::fixtures::{printable, seq as fseq, tlv as ftlv};

    // The disclosure location is a URL: IA5 text without a scheme names no
    // place to disclose at.
    let value = fseq(&[fseq(&[
        oid_of(oid::QC_PDS),
        fseq(&[fseq(&[ftlv(0x16, b"not-a-url"), printable("en")])]),
    ])]);
    let der = seq(&[extension(oid::QC_STATEMENTS, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        1
    );
}

#[test]
fn an_unknown_other_name_registration_authority_blocks() {
    use crate::fixtures::{context, seq as fseq};
    let unknown = Oid::from_bytes(&[0x2a, 0x86, 0x24, 0x06, 0x05]);

    // With no semantics identifier, the authorities are the statement's only
    // content: an other-name nobody claims there was never interpreted.
    let other = context(0, &[oid_of(unknown), context(0, &[int(1)])]);
    let information = fseq(&[fseq(&[other])]);
    let value = fseq(&[fseq(&[oid_of(oid::PKIX_QC_SYNTAX_V2), information])]);
    let der = seq(&[extension(oid::QC_STATEMENTS, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        1
    );
    let scheme = NameScheme(unknown);
    assert_eq!(
        extensions
            .unhandled_critical(&scheme, parser.memory())
            .unwrap()
            .len(),
        0
    );
}

#[test]
fn an_access_location_outside_its_methods_forms_blocks() {
    use crate::fixtures::{context, implicit, seq as fseq};

    // Each built-in method names the forms its location may take (RFC 5280
    // 4.2.2.1 and 4.2.2.2): the status responder is reached by a URI, and a
    // domain name there is an endpoint this run cannot use.
    let value = fseq(&[fseq(&[oid_of(oid::OCSP), implicit(2, b"ocsp.example.ua")])]);
    let der = seq(&[extension(oid::AUTHORITY_INFO_ACCESS, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        1
    );

    // The issuing-certificate method names the directory form among its own.
    let root = fseq(&[crate::fixtures::set(&[fseq(&[
        oid_of(oid::COMMON_NAME),
        crate::fixtures::utf8("Root"),
    ])])]);
    let value = fseq(&[fseq(&[oid_of(oid::CA_ISSUERS), context(4, &[root])])]);
    let der = seq(&[extension(oid::AUTHORITY_INFO_ACCESS, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        0
    );
}

#[test]
fn an_unknown_other_name_location_in_a_critical_access_extension_blocks() {
    use crate::fixtures::{context, seq as fseq, utf8};

    // A known method does not vouch for its location: an other-name whose
    // type nobody claims is a location this run never interpreted. Under a
    // named method the other-name blocks even when a scheme claims its
    // type, since the method's own forms do not include it; a method the
    // scheme claims keeps its own forms.
    let unknown = Oid::from_bytes(&[0x2a, 0x86, 0x24, 0x06, 0x02]);
    let other = context(0, &[oid_of(unknown), context(0, &[utf8("loc")])]);
    let value = fseq(&[fseq(&[oid_of(oid::OCSP), other.clone()])]);
    let der = seq(&[extension(oid::AUTHORITY_INFO_ACCESS, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        1
    );

    let value = fseq(&[fseq(&[oid_of(unknown), other])]);
    let der = seq(&[extension(oid::AUTHORITY_INFO_ACCESS, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    let scheme = AccessScheme(unknown);
    assert_eq!(
        extensions
            .unhandled_critical(&scheme, parser.memory())
            .unwrap()
            .len(),
        0
    );
}

#[test]
fn a_pds_language_that_is_not_a_language_code_blocks() {
    use crate::fixtures::{printable, seq as fseq};

    // The language beside a disclosure location is an ISO 639-1 code, two
    // lowercase letters: a digit or an uppercase pair names no language.
    for language in ["A1", "EN", "1a"] {
        let value = fseq(&[fseq(&[
            oid_of(oid::QC_PDS),
            fseq(&[fseq(&[
                crate::fixtures::ia5("https://pds.example.ua/en"),
                printable(language),
            ])]),
        ])]);
        let der = seq(&[extension(oid::QC_STATEMENTS, true, &value)]);
        let parser = Parser::der(crate::fixtures::memory());
        let extensions = parse(&parser, &der).unwrap();
        assert_eq!(
            extensions
                .unhandled_critical(&(), parser.memory())
                .unwrap()
                .len(),
            1,
            "{language}"
        );
    }
}

#[test]
fn a_legislation_code_that_is_not_a_country_blocks() {
    use crate::fixtures::{printable, seq as fseq};

    // The legislation entries are ISO 3166-1 alpha-2 codes, two uppercase
    // letters: a digit or punctuation in the pair names no country.
    for code in ["A1", "??", "ua"] {
        let value = fseq(&[fseq(&[
            oid_of(oid::QC_CC_LEGISLATION),
            fseq(&[printable(code)]),
        ])]);
        let der = seq(&[extension(oid::QC_STATEMENTS, true, &value)]);
        let parser = Parser::der(crate::fixtures::memory());
        let extensions = parse(&parser, &der).unwrap();
        assert_eq!(
            extensions
                .unhandled_critical(&(), parser.memory())
                .unwrap()
                .len(),
            1,
            "{code}"
        );
    }
}

#[test]
fn a_duplicate_key_purpose_reads_once() {
    use crate::fixtures::seq as fseq;

    // The list is a SEQUENCE OF with no uniqueness constraint, and a
    // repeated purpose permits exactly what one occurrence permits:
    // refusing it would block a valid certificate. The repeat is folded
    // away instead, so the list reads and holds each purpose once.
    let value = fseq(&[oid_of(oid::EMAIL_PROTECTION), oid_of(oid::EMAIL_PROTECTION)]);
    let der = seq(&[extension(oid::EXT_KEY_USAGE, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        0
    );
    let purposes = extensions
        .extended_key_usage(extensions.memory())
        .unwrap()
        .unwrap();
    assert_eq!(purposes.purposes().len(), 1);
    assert!(
        purposes
            .has(oid::EMAIL_PROTECTION, extensions.memory())
            .unwrap()
    );
}

#[test]
fn encipher_bits_without_key_agreement_block() {
    // RFC 5280 4.2.1.3: the meaning of encipherOnly and decipherOnly is
    // undefined in the absence of the keyAgreement bit, and a critical bit
    // with no defined meaning was not understood. digitalSignature +
    // encipherOnly here; keyAgreement clear.
    let der = seq(&[extension(oid::KEY_USAGE, true, &tlv(0x03, &[0x00, 0x81]))]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        1
    );

    // With keyAgreement set beside it, the bit means what it says.
    let der = seq(&[extension(oid::KEY_USAGE, true, &tlv(0x03, &[0x00, 0x89]))]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        0
    );
}

#[test]
fn a_path_length_without_the_authority_flag_blocks() {
    // RFC 5280 4.2.1.9: the path length must not be present unless the
    // authority flag is asserted. Present without it, the value constrains a
    // path below a certificate that says it heads none.
    let der = seq(&[extension(oid::BASIC_CONSTRAINTS, true, &seq(&[int(2)]))]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        1
    );
}

#[test]
fn a_critical_statement_list_this_run_did_not_understand_blocks() {
    use crate::fixtures::null;
    // The outer list parses, but the kind statement's information is a NULL
    // where a sequence of types belongs: nothing here understood what the
    // certificate demanded be understood.
    let garbled_kind = seq(&[seq(&[oid_of(oid::QC_TYPE), null()])]);
    // And a statement identifier nobody here knows is exactly an unknown
    // critical demand, one level down.
    let unknown_kind = seq(&[seq(&[oid_of(structured_asn1::Oid::from_bytes(&[
        0x2b, 0x06, 0x01, 0x04, 0x01, 0x7e,
    ]))])]);

    for value in [garbled_kind, unknown_kind] {
        let der = seq(&[extension(oid::QC_STATEMENTS, true, &value)]);
        let parser = Parser::der(crate::fixtures::memory());
        let extensions = parse(&parser, &der).unwrap();
        assert_eq!(
            extensions
                .unhandled_critical(&(), parser.memory())
                .unwrap()
                .len(),
            1
        );
    }

    // A list of statements this crate does read stays handled.
    let understood = seq(&[
        seq(&[oid_of(oid::QC_COMPLIANCE)]),
        seq(&[oid_of(oid::QC_TYPE), seq(&[oid_of(oid::QCT_ESEAL)])]),
    ]);
    let der = seq(&[extension(oid::QC_STATEMENTS, true, &understood)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        0
    );
}

#[test]
fn a_critical_policy_with_uninterpreted_qualifiers_blocks() {
    use crate::fixtures::{ia5, null, seq as fseq};
    let policy = structured_asn1::Oid::from_bytes(&[0x2a, 0x86, 0x24, 0x03, 0x01]);

    // A qualifier kind nobody here knows, and a practice-statement qualifier
    // whose payload is a NULL where a location belongs: either way the
    // critical qualifier was never interpreted.
    let unknown_kind = fseq(&[fseq(&[
        oid_of(policy),
        fseq(&[fseq(&[
            oid_of(structured_asn1::Oid::from_bytes(&[
                0x2a, 0x86, 0x24, 0x03, 0x02,
            ])),
            ia5("x"),
        ])]),
    ])]);
    let garbled_cps = fseq(&[fseq(&[
        oid_of(policy),
        fseq(&[fseq(&[oid_of(oid::CPS_QUALIFIER), null()])]),
    ])]);
    for value in [unknown_kind, garbled_cps] {
        let der = seq(&[extension(oid::CERTIFICATE_POLICIES, true, &value)]);
        let parser = Parser::der(crate::fixtures::memory());
        let extensions = parse(&parser, &der).unwrap();
        assert_eq!(
            extensions
                .unhandled_critical(&(), parser.memory())
                .unwrap()
                .len(),
            1
        );
    }

    // A policy without qualifiers, and one with a genuine practice statement,
    // both stay handled.
    let plain = fseq(&[fseq(&[oid_of(policy)])]);
    let with_cps = fseq(&[fseq(&[
        oid_of(policy),
        fseq(&[fseq(&[
            oid_of(oid::CPS_QUALIFIER),
            ia5("https://cps.example.ua"),
        ])]),
    ])]);
    for value in [plain, with_cps] {
        let der = seq(&[extension(oid::CERTIFICATE_POLICIES, true, &value)]);
        let parser = Parser::der(crate::fixtures::memory());
        let extensions = parse(&parser, &der).unwrap();
        assert_eq!(
            extensions
                .unhandled_critical(&(), parser.memory())
                .unwrap()
                .len(),
            0
        );
    }
}

#[test]
fn a_critical_statement_payload_without_its_shape_blocks() {
    use crate::fixtures::{ia5, null, printable, seq as fseq};

    // The limit-value, disclosure-location and legislation statements carry
    // structured payloads; a NULL in any of them is a critical claim this
    // run never understood.
    for kind in [oid::QC_LIMIT_VALUE, oid::QC_PDS, oid::QC_CC_LEGISLATION] {
        let value = fseq(&[fseq(&[oid_of(kind), null()])]);
        let der = seq(&[extension(oid::QC_STATEMENTS, true, &value)]);
        let parser = Parser::der(crate::fixtures::memory());
        let extensions = parse(&parser, &der).unwrap();
        assert_eq!(
            extensions
                .unhandled_critical(&(), parser.memory())
                .unwrap()
                .len(),
            1,
            "{kind:?}"
        );
    }

    // The genuine shapes stay handled: a monetary limit, one disclosure
    // location, one legislation country.
    let limit = fseq(&[fseq(&[
        oid_of(oid::QC_LIMIT_VALUE),
        fseq(&[printable("UAH"), int(1000), int(0)]),
    ])]);
    let locations = fseq(&[fseq(&[
        oid_of(oid::QC_PDS),
        fseq(&[fseq(&[ia5("https://pds.example.ua/en"), printable("en")])]),
    ])]);
    let legislation = fseq(&[fseq(&[
        oid_of(oid::QC_CC_LEGISLATION),
        fseq(&[printable("UA")]),
    ])]);
    for value in [limit, locations, legislation] {
        let der = seq(&[extension(oid::QC_STATEMENTS, true, &value)]);
        let parser = Parser::der(crate::fixtures::memory());
        let extensions = parse(&parser, &der).unwrap();
        assert_eq!(
            extensions
                .unhandled_critical(&(), parser.memory())
                .unwrap()
                .len(),
            0
        );
    }
}

/// Reads the list and asks what blocked under one element budget, or `None`
/// where the budget did not even let the list be read.
fn blocked_under_budget(der: &[u8], budget: u64) -> Option<Result<usize>> {
    let limits = structured_asn1::Limits {
        max_elements: budget,
        ..structured_asn1::Limits::default()
    };
    let parser = Parser::new(
        structured_asn1::Encoding::Der,
        limits,
        crate::fixtures::memory(),
    );
    let mut reader = parser.read(der, 0).ok()?;
    let element = reader.next_element().ok()??;
    let extensions = read(&reader, &element, "test").ok()?;
    Some(
        extensions
            .unhandled_critical(&(), parser.memory())
            .map(|blocked| blocked.len())
            .map_err(processing),
    )
}

#[test]
fn a_limit_error_inside_a_qualifier_points_into_the_document() {
    use crate::fixtures::{ia5, seq as fseq};
    let policy = structured_asn1::Oid::from_bytes(&[0x2a, 0x86, 0x24, 0x03, 0x01]);
    let pointer = ia5("https://cps.example.ua");
    let value = fseq(&[fseq(&[
        oid_of(policy),
        fseq(&[fseq(&[oid_of(oid::CPS_QUALIFIER), pointer.clone()])]),
    ])]);
    let der = seq(&[extension(oid::CERTIFICATE_POLICIES, true, &value)]);
    let qualifier_at = u64::try_from(
        der.windows(pointer.len())
            .position(|window| window == &pointer[..])
            .unwrap(),
    )
    .unwrap();

    // The last budget that still fails runs out at the deepest point of the
    // work, inside the qualifier re-parse. Its offset must be an offset in
    // the document, at or past the qualifier, never one counted from the
    // start of the re-read slice: the error type promises document offsets.
    let mut deepest = None;
    for budget in 1..512 {
        match blocked_under_budget(&der, budget) {
            Some(Ok(_)) => break,
            Some(Err(error)) => deepest = Some(error),
            None => {}
        }
    }
    let error = deepest.unwrap();
    assert!(error.is_limit());
    assert!(
        error.offset() >= qualifier_at,
        "offset {} points before the qualifier at {qualifier_at}",
        error.offset()
    );
}

#[test]
fn a_spent_budget_is_not_an_unhandled_extension() {
    // A well-formed critical key usage, and the smallest element budget that
    // lets the list be read. The gate's re-decode then runs out of budget,
    // which says the device gave up, not that the certificate demanded
    // something nobody understood: the answer is the spent budget itself,
    // never a blocker in the report.
    let der = seq(&[extension(oid::KEY_USAGE, true, &tlv(0x03, &[0x07, 0x80]))]);
    let outcome = (1..64)
        .find_map(|budget| blocked_under_budget(&der, budget))
        .unwrap();
    assert!(outcome.unwrap_err().is_limit());
}

#[test]
fn a_notice_number_not_wearing_the_integer_tag_blocks() {
    use crate::fixtures::{ia5, seq as fseq};
    let policy = structured_asn1::Oid::from_bytes(&[0x2a, 0x86, 0x24, 0x03, 0x01]);

    // noticeNumbers is SEQUENCE OF INTEGER (RFC 5280 4.2.1.4): an OCTET
    // STRING whose contents happen to spell a minimal integer is not that,
    // and the reader's decoding helper is deliberately tag-agnostic for
    // implicitly tagged fields, so the schema layer must require the tag.
    let reference = fseq(&[ia5("org"), fseq(&[tlv(0x04, &[0x01])])]);
    let value = fseq(&[fseq(&[
        oid_of(policy),
        fseq(&[fseq(&[
            oid_of(oid::USER_NOTICE_QUALIFIER),
            fseq(&[reference]),
        ])]),
    ])]);
    let der = seq(&[extension(oid::CERTIFICATE_POLICIES, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        1
    );
}

#[test]
fn a_cps_pointer_outside_the_ia5_alphabet_blocks() {
    use crate::fixtures::seq as fseq;
    let policy = structured_asn1::Oid::from_bytes(&[0x2a, 0x86, 0x24, 0x03, 0x01]);

    // The pointer is an IA5String, the 128-character IRV (X.680, 41.4): a
    // byte above 0x7f wears the tag but is not the type, and the critical
    // qualifier holding it was never interpreted.
    let value = fseq(&[fseq(&[
        oid_of(policy),
        fseq(&[fseq(&[
            oid_of(oid::CPS_QUALIFIER),
            tlv(0x16, b"https://cps.example.ua/\xff"),
        ])]),
    ])]);
    let der = seq(&[extension(oid::CERTIFICATE_POLICIES, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        1
    );
}

#[test]
fn display_text_that_does_not_decode_or_overruns_its_size_blocks() {
    use crate::fixtures::seq as fseq;
    let policy = structured_asn1::Oid::from_bytes(&[0x2a, 0x86, 0x24, 0x03, 0x01]);
    let notice = |text: Vec<u8>| {
        fseq(&[fseq(&[
            oid_of(policy),
            fseq(&[fseq(&[oid_of(oid::USER_NOTICE_QUALIFIER), fseq(&[text])])]),
        ])])
    };

    // Display text is a choice of four string types, each SIZE (1..200)
    // (RFC 5280 4.2.1.4): bytes that do not decode under the declared type,
    // or a decoded text longer than 200 characters, wear the tag without
    // being the type, and the critical qualifier was never interpreted.
    let undecodable_utf8 = notice(tlv(0x0c, b"\xff\xfe"));
    let odd_bmp = notice(tlv(0x1e, &[0x00, 0x04, 0x10]));
    // A surrogate pair is UTF-16, not the one-unit-a-character UCS-2 that
    // BMPString is (X.680, 41.16): a character outside the basic plane has
    // no spelling here, and combining the pair would accept one.
    let surrogate_bmp = notice(tlv(0x1e, &[0xd8, 0x01, 0xdc, 0x00]));
    let too_long = notice(tlv(0x0c, &[b'a'; 201]));
    for value in [undecodable_utf8, odd_bmp, surrogate_bmp, too_long] {
        let der = seq(&[extension(oid::CERTIFICATE_POLICIES, true, &value)]);
        let parser = Parser::der(crate::fixtures::memory());
        let extensions = parse(&parser, &der).unwrap();
        assert_eq!(
            extensions
                .unhandled_critical(&(), parser.memory())
                .unwrap()
                .len(),
            1
        );
    }

    // Exactly two hundred characters is inside the size, and a two-byte
    // basic-plane character counts as one character rather than two bytes.
    let at_limit = notice(tlv(0x0c, &[b'a'; 200]));
    let cyrillic_bmp = notice(tlv(0x1e, &[0x04, 0x23, 0x04, 0x32]));
    for value in [at_limit, cyrillic_bmp] {
        let der = seq(&[extension(oid::CERTIFICATE_POLICIES, true, &value)]);
        let parser = Parser::der(crate::fixtures::memory());
        let extensions = parse(&parser, &der).unwrap();
        assert_eq!(
            extensions
                .unhandled_critical(&(), parser.memory())
                .unwrap()
                .len(),
            0
        );
    }
}

#[test]
fn a_numeric_currency_not_wearing_the_integer_tag_blocks() {
    use crate::fixtures::seq as fseq;

    // The numeric currency choice is an INTEGER; an OCTET STRING whose
    // contents spell a minimal integer wears a different type, and the
    // reader's decoding helper is deliberately tag-agnostic for implicitly
    // tagged fields, so the schema layer must require the tag.
    let value = fseq(&[fseq(&[
        oid_of(oid::QC_LIMIT_VALUE),
        fseq(&[tlv(0x04, &[0x01]), int(1000), int(0)]),
    ])]);
    let der = seq(&[extension(oid::QC_STATEMENTS, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        1
    );
}

#[test]
fn qc_strings_outside_their_declared_alphabets_block() {
    use crate::fixtures::{printable, seq as fseq};

    // Each narrow string type declares an alphabet (X.680, 41.4): an
    // IA5String is the 128-character IRV, and PrintableString is a short
    // closed list. A byte outside the alphabet wears the tag but is not the
    // type, and a critical statement built on one was never understood.
    let bad_url = fseq(&[fseq(&[
        oid_of(oid::QC_PDS),
        fseq(&[fseq(&[
            tlv(0x16, b"https://pds.example.ua/\xff"),
            printable("en"),
        ])]),
    ])]);
    let bad_language = fseq(&[fseq(&[
        oid_of(oid::QC_PDS),
        fseq(&[fseq(&[
            tlv(0x16, b"https://pds.example.ua/en"),
            tlv(0x13, b"e@"),
        ])]),
    ])]);
    let bad_country = fseq(&[fseq(&[
        oid_of(oid::QC_CC_LEGISLATION),
        fseq(&[tlv(0x13, b"U@")]),
    ])]);
    let bad_currency = fseq(&[fseq(&[
        oid_of(oid::QC_LIMIT_VALUE),
        fseq(&[tlv(0x13, b"U@H"), int(1000), int(0)]),
    ])]);
    for value in [bad_url, bad_language, bad_country, bad_currency] {
        let der = seq(&[extension(oid::QC_STATEMENTS, true, &value)]);
        let parser = Parser::der(crate::fixtures::memory());
        let extensions = parse(&parser, &der).unwrap();
        assert_eq!(
            extensions
                .unhandled_critical(&(), parser.memory())
                .unwrap()
                .len(),
            1
        );
    }
}

#[test]
fn an_empty_type_list_in_a_critical_statement_blocks() {
    use crate::fixtures::seq as fseq;

    // The type statement declares which purpose the certificate is issued
    // for (ETSI EN 319 412-5, clause 4.2.3); a list of zero purposes wears
    // the statement while declaring nothing, and a critical list carrying it
    // was never understood.
    let value = fseq(&[fseq(&[oid_of(oid::QC_TYPE), fseq(&[])])]);
    let der = seq(&[extension(oid::QC_STATEMENTS, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        1
    );
}

#[test]
fn a_type_identifier_not_wearing_the_oid_tag_blocks() {
    use crate::fixtures::seq as fseq;

    // An OCTET STRING whose contents happen to be the bytes of a known
    // identifier is not an OBJECT IDENTIFIER: the schema says SEQUENCE OF
    // OBJECT IDENTIFIER, and the reader's decoding helpers are deliberately
    // tag-agnostic for implicitly tagged fields, so the schema layer is the
    // one that must require the universal tag.
    let full = oid_of(oid::QCT_ESIGN);
    let value = fseq(&[fseq(&[
        oid_of(oid::QC_TYPE),
        fseq(&[tlv(0x04, &full[2..])]),
    ])]);
    let der = seq(&[extension(oid::QC_STATEMENTS, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        1
    );
}

#[test]
fn an_unknown_type_inside_a_critical_type_statement_blocks() {
    use crate::fixtures::seq as fseq;

    // The type statement's payload is what carries the meaning: a type
    // identifier nobody here knows is a certificate purpose this run cannot
    // name, and a critical list demanding it be understood blocks.
    let unknown = structured_asn1::Oid::from_bytes(&[0x2b, 0x06, 0x01, 0x04, 0x01, 0x7d]);
    let value = fseq(&[fseq(&[
        oid_of(oid::QC_TYPE),
        fseq(&[oid_of(oid::QCT_ESIGN), oid_of(unknown)]),
    ])]);
    let der = seq(&[extension(oid::QC_STATEMENTS, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        1
    );
}

#[test]
fn a_numeric_currency_outside_the_iso_4217_range_blocks() {
    use crate::fixtures::seq as fseq;

    // The numeric currency choice is INTEGER (1..999); zero, a negative
    // number and a four-digit number wear the type but name no currency, so
    // a critical limit carrying one was never understood.
    for code in [int(0), tlv(0x02, &[0xFF]), int(1000)] {
        let value = fseq(&[fseq(&[
            oid_of(oid::QC_LIMIT_VALUE),
            fseq(&[code, int(1000), int(0)]),
        ])]);
        let der = seq(&[extension(oid::QC_STATEMENTS, true, &value)]);
        let parser = Parser::der(crate::fixtures::memory());
        let extensions = parse(&parser, &der).unwrap();
        assert_eq!(
            extensions
                .unhandled_critical(&(), parser.memory())
                .unwrap()
                .len(),
            1
        );
    }

    // A code inside the range stays handled.
    let value = fseq(&[fseq(&[
        oid_of(oid::QC_LIMIT_VALUE),
        fseq(&[int(980), int(1000), int(0)]),
    ])]);
    let der = seq(&[extension(oid::QC_STATEMENTS, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        0
    );
}

#[test]
fn empty_semantics_information_blocks() {
    use crate::fixtures::seq as fseq;

    // The semantics structure requires at least one of its two optional
    // members (RFC 3739, 3.2.6.1): empty it says nothing while wearing the
    // statement, and a critical list carrying it was never understood.
    let value = fseq(&[fseq(&[oid_of(oid::PKIX_QC_SYNTAX_V2), fseq(&[])])]);
    let der = seq(&[extension(oid::QC_STATEMENTS, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        1
    );
}

#[test]
fn an_unknown_semantics_identifier_in_a_critical_statement_blocks() {
    use crate::fixtures::seq as fseq;

    // The identifier decides how the subject's identifiers are read, and
    // this crate names two ways of reading them. One it does not name is a
    // reading this run cannot perform, so a critical statement demanding it
    // was not understood. The accessor still hands the identifier back for
    // the report.
    let unknown = structured_asn1::Oid::from_bytes(&[0x2b, 0x06, 0x01, 0x04, 0x01, 0x7c]);
    let value = fseq(&[fseq(&[
        oid_of(oid::PKIX_QC_SYNTAX_V2),
        fseq(&[oid_of(unknown)]),
    ])]);
    let der = seq(&[extension(oid::QC_STATEMENTS, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        1
    );
}

#[test]
fn every_semantics_statement_is_validated_not_just_the_preferred_one() {
    use crate::fixtures::{null, seq as fseq};

    // Both syntax statements may appear in one list. The accessor prefers
    // the newer one, but a well-formed preferred statement must not vouch
    // for the other: here the older statement's information is a NULL where
    // the semantics structure belongs, and that is a critical claim this run
    // never understood whichever statement stands beside it.
    let value = fseq(&[
        fseq(&[oid_of(oid::PKIX_QC_SYNTAX_V2)]),
        fseq(&[oid_of(oid::PKIX_QC_SYNTAX_V1), null()]),
    ]);
    let der = seq(&[extension(oid::QC_STATEMENTS, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        1
    );

    // Two genuine semantics statements side by side both parse and stay
    // handled. They say the same thing: two that disagree leave the
    // subject's identifiers with two readings, which blocks instead, and is
    // covered where the pair is compared.
    let value = fseq(&[
        fseq(&[
            oid_of(oid::PKIX_QC_SYNTAX_V2),
            fseq(&[oid_of(oid::SEMANTICS_LEGAL_PERSON)]),
        ]),
        fseq(&[
            oid_of(oid::PKIX_QC_SYNTAX_V1),
            fseq(&[oid_of(oid::SEMANTICS_LEGAL_PERSON)]),
        ]),
    ]);
    let der = seq(&[extension(oid::QC_STATEMENTS, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        0
    );
}

#[test]
fn an_access_method_in_the_wrong_extension_blocks() {
    use crate::fixtures::{implicit, seq as fseq};

    // Each extension defines its own methods: the authority side names OCSP
    // and the issuing certificates, the subject side names the repository
    // and the time-stamping service. A method carried by the other
    // extension has no defined meaning there, so a critical list holding
    // one was not understood.
    let crossed = [
        (oid::AUTHORITY_INFO_ACCESS, oid::TIME_STAMPING_ACCESS),
        (oid::AUTHORITY_INFO_ACCESS, oid::CA_REPOSITORY),
        (oid::SUBJECT_INFO_ACCESS, oid::OCSP),
        (oid::SUBJECT_INFO_ACCESS, oid::CA_ISSUERS),
    ];
    for (kind, method) in crossed {
        let value = fseq(&[fseq(&[
            oid_of(method),
            implicit(6, b"https://service.example.ua"),
        ])]);
        let der = seq(&[extension(kind, true, &value)]);
        let parser = Parser::der(crate::fixtures::memory());
        let extensions = parse(&parser, &der).unwrap();
        assert_eq!(
            extensions
                .unhandled_critical(&(), parser.memory())
                .unwrap()
                .len(),
            1
        );
    }

    // Each method in its own extension stays handled.
    let owned = [
        (oid::AUTHORITY_INFO_ACCESS, oid::CA_ISSUERS),
        (oid::SUBJECT_INFO_ACCESS, oid::TIME_STAMPING_ACCESS),
        (oid::SUBJECT_INFO_ACCESS, oid::CA_REPOSITORY),
    ];
    for (kind, method) in owned {
        let value = fseq(&[fseq(&[
            oid_of(method),
            implicit(6, b"https://service.example.ua"),
        ])]);
        let der = seq(&[extension(kind, true, &value)]);
        let parser = Parser::der(crate::fixtures::memory());
        let extensions = parse(&parser, &der).unwrap();
        assert_eq!(
            extensions
                .unhandled_critical(&(), parser.memory())
                .unwrap()
                .len(),
            0
        );
    }
}

#[test]
fn an_opaque_name_form_in_a_constraint_blocks() {
    use crate::fixtures::{context, implicit, seq as fseq, set as fset};
    // A constraint is understood only where a certificate's names can be
    // matched against it. The X.400 form is kept as opaque encoded bytes
    // with no matching rule, so a critical constraint built on one was not
    // understood even though its structure parsed.
    let attribute = fseq(&[implicit(0, &[0x17]), context(1, &[int(1)])]);
    let x400 = context(3, &[fseq(&[]), fset(&[attribute])]);
    let value = fseq(&[context(0, &[fseq(&[x400])])]);
    let der = seq(&[extension(oid::NAME_CONSTRAINTS, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        1
    );

    // A form with a matching rule stays handled.
    let value = fseq(&[context(0, &[fseq(&[implicit(2, b"example.ua")])])]);
    let der = seq(&[extension(oid::NAME_CONSTRAINTS, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        0
    );
}

#[test]
fn decoding_an_other_name_does_not_vouch_for_a_constraint_on_it() {
    use crate::fixtures::{context, seq as fseq, utf8};

    // The two are different questions about the same identifier. Decoding
    // asks what a name of this type says; a constraint asks whether a
    // certificate's names fall inside a subtree of it, and answering that
    // needs a containment rule the decoding side never states. A scheme
    // that reads the name and has no such rule would leave a critical
    // constraint enforced by nobody.
    let mine = Oid::from_bytes(&[0x2a, 0x86, 0x24, 0x07, 0x01]);
    let base = context(0, &[oid_of(mine), context(0, &[utf8("branch")])]);
    let value = fseq(&[context(0, &[fseq(&[base])])]);
    let der = seq(&[extension(oid::NAME_CONSTRAINTS, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();

    // Nobody at all, and a scheme that only reads the name, both leave it
    // blocking.
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        1
    );
    let reader = NameScheme(mine);
    assert_eq!(
        extensions
            .unhandled_critical(&reader, parser.memory())
            .unwrap()
            .len(),
        1
    );

    // A scheme that states the containment rule clears it.
    let matcher = ConstraintScheme(mine);
    assert_eq!(
        extensions
            .unhandled_critical(&matcher, parser.memory())
            .unwrap()
            .len(),
        0
    );

    // And the constraint role says nothing about reading the name itself:
    // the same scheme leaves a critical alternative name blocking.
    let value = fseq(&[context(0, &[oid_of(mine), context(0, &[utf8("branch")])])]);
    let der = seq(&[extension(oid::SUBJECT_ALT_NAME, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&matcher, parser.memory())
            .unwrap()
            .len(),
        1
    );
    assert_eq!(
        extensions
            .unhandled_critical(&reader, parser.memory())
            .unwrap()
            .len(),
        0
    );
}

#[test]
fn an_empty_user_notice_is_understood() {
    use crate::fixtures::seq as fseq;
    let policy = structured_asn1::Oid::from_bytes(&[0x2a, 0x86, 0x24, 0x03, 0x01]);

    // Both members of a user notice are optional (RFC 5280 4.2.1.4): the
    // empty sequence says nothing, but it is inside the schema, and
    // refusing it would block an otherwise valid critical policy.
    let value = fseq(&[fseq(&[
        oid_of(policy),
        fseq(&[fseq(&[oid_of(oid::USER_NOTICE_QUALIFIER), fseq(&[])])]),
    ])]);
    let der = seq(&[extension(oid::CERTIFICATE_POLICIES, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        0
    );
}

#[test]
fn content_scans_are_charged_to_the_work_budget() {
    use crate::fixtures::{implicit, seq as fseq, tlv as ftlv};

    // The text and named-bit walks touch every content byte, so a caller
    // bounding work sees them on the meter: a value far past the budget
    // fails on the limit rather than costing an unmetered linear scan. The
    // list borrows the parser, so the accessor runs inside the helper.
    fn scan_error(
        der: &[u8],
        pick: impl FnOnce(&Extensions<'_>) -> crate::error::Error,
    ) -> ErrorCode {
        let limits = structured_asn1::Limits {
            max_work: 4096,
            ..structured_asn1::Limits::default()
        };
        let parser = Parser::new(
            structured_asn1::Encoding::Der,
            limits,
            crate::fixtures::memory(),
        );
        let mut reader = parser.read(der, 0).unwrap();
        let element = reader.next_element().unwrap().unwrap();
        let extensions = read(&reader, &element, "test").unwrap();
        pick(&extensions).code()
    }

    let big = alloc::vec![b'a'; 100_000];
    let der = seq(&[extension(
        oid::SUBJECT_ALT_NAME,
        true,
        &fseq(&[implicit(2, &big)]),
    )]);
    assert_eq!(
        scan_error(&der, |list| list
            .subject_alt_name(list.memory())
            .unwrap_err()),
        ErrorCode::Encoding(structured_asn1::ErrorCode::LimitExceeded(
            structured_asn1::Limit::Work
        ))
    );

    let zeros = alloc::vec![0x00; 100_001];
    let der = seq(&[extension(oid::KEY_USAGE, true, &ftlv(0x03, &zeros))]);
    assert_eq!(
        scan_error(&der, |list| list.key_usage(list.memory()).unwrap_err()),
        ErrorCode::Encoding(structured_asn1::ErrorCode::LimitExceeded(
            structured_asn1::Limit::Work
        ))
    );
}

#[test]
fn a_registered_id_constraint_base_blocks() {
    use crate::fixtures::{context, seq as fseq, tlv as ftlv};
    // A registered identifier has no constraint-matching rule here either:
    // a critical constraint built on one was not understood.
    let base = ftlv(0x88, oid::OCSP.as_bytes());
    let value = fseq(&[context(0, &[fseq(&[base])])]);
    let der = seq(&[extension(oid::NAME_CONSTRAINTS, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        1
    );
}

#[test]
fn the_cps_uri_scan_is_charged_to_the_work_budget() {
    use crate::fixtures::{ia5, seq as fseq};
    // A CPS URI has no local size ceiling, and deciding whether a critical
    // policies extension is handled scans every byte of it for IA5, UTF-8
    // and URI shape, so the scan rides on the shared work meter.
    let mut url = alloc::string::String::from("https://cps.example.ua/");
    url.push_str(&"a".repeat(100_000));
    let policy = Oid::from_bytes(&[0x2a, 0x86, 0x24, 0x01, 0x02]);
    let value = fseq(&[fseq(&[
        oid_of(policy),
        fseq(&[fseq(&[oid_of(oid::CPS_QUALIFIER), ia5(&url)])]),
    ])]);
    let der = seq(&[extension(oid::CERTIFICATE_POLICIES, true, &value)]);

    let limits = structured_asn1::Limits {
        max_work: 8192,
        ..structured_asn1::Limits::default()
    };
    let parser = Parser::new(
        structured_asn1::Encoding::Der,
        limits,
        crate::fixtures::memory(),
    );
    let extensions = parse(&parser, &der).unwrap();
    let error = processing(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap_err(),
    );
    assert_eq!(
        error.code(),
        ErrorCode::Encoding(structured_asn1::ErrorCode::LimitExceeded(
            structured_asn1::Limit::Work
        ))
    );
}

#[test]
fn the_disclosure_url_scan_is_charged_to_the_work_budget() {
    use crate::fixtures::{ia5, printable, seq as fseq};
    // Same meter as the CPS URI: a PDS URL is certificate-controlled text
    // with no local bound, scanned to decide whether the critical statements
    // extension is handled.
    let mut url = alloc::string::String::from("https://pds.example.ua/");
    url.push_str(&"a".repeat(100_000));
    let value = fseq(&[fseq(&[
        oid_of(oid::QC_PDS),
        fseq(&[fseq(&[ia5(&url), printable("en")])]),
    ])]);
    let der = seq(&[extension(oid::QC_STATEMENTS, true, &value)]);

    let limits = structured_asn1::Limits {
        max_work: 8192,
        ..structured_asn1::Limits::default()
    };
    let parser = Parser::new(
        structured_asn1::Encoding::Der,
        limits,
        crate::fixtures::memory(),
    );
    let extensions = parse(&parser, &der).unwrap();
    let error = processing(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap_err(),
    );
    assert_eq!(
        error.code(),
        ErrorCode::Encoding(structured_asn1::ErrorCode::LimitExceeded(
            structured_asn1::Limit::Work
        ))
    );
}

#[test]
fn an_empty_notice_number_sequence_is_understood() {
    use crate::fixtures::{ia5, seq as fseq};
    let policy = structured_asn1::Oid::from_bytes(&[0x2a, 0x86, 0x24, 0x03, 0x01]);

    // noticeNumbers is SEQUENCE OF INTEGER with no minimum size
    // (RFC 5280 4.2.1.4): the empty sequence sits inside the schema, and a
    // critical policies extension carrying it was read entirely.
    let reference = fseq(&[ia5("org"), fseq(&[])]);
    let value = fseq(&[fseq(&[
        oid_of(policy),
        fseq(&[fseq(&[
            oid_of(oid::USER_NOTICE_QUALIFIER),
            fseq(&[reference]),
        ])]),
    ])]);
    let der = seq(&[extension(oid::CERTIFICATE_POLICIES, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        0
    );
}

#[test]
fn a_scheme_recognized_qualified_statement_is_understood() {
    use crate::fixtures::{octets, seq as fseq};

    /// A scheme that knows one qualified statement of its own.
    struct Statements(Oid<'static>);
    impl Recognizer for Statements {
        type Error = core::convert::Infallible;
        fn recognizes(
            &self,
            _kind: Oid<'_>,
            _execution: &structured_asn1::memory::Memory,
        ) -> core::result::Result<bool, Self::Error> {
            Ok(false)
        }
        fn recognizes_statement(
            &self,
            kind: Oid<'_>,
            _execution: &structured_asn1::memory::Memory,
        ) -> core::result::Result<bool, Self::Error> {
            Ok(kind == self.0)
        }
    }

    // A national statement is knowledge a scheme carries: the built-in
    // identifiers cannot name it, but a caller whose recognizer claims it
    // has read the critical extension entirely.
    let national = Oid::from_bytes(&[0x2a, 0x86, 0x24, 0x07, 0x01]);
    let value = fseq(&[fseq(&[oid_of(national), octets(&[0x01])])]);
    let der = seq(&[extension(oid::QC_STATEMENTS, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());

    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&Statements(national), parser.memory())
            .unwrap()
            .len(),
        0
    );
    // Without that knowledge the same extension still blocks.
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        1
    );
}

#[test]
fn a_recognizer_reached_by_reference_answers_for_every_role() {
    use crate::fixtures::{octets, seq as fseq};

    /// A scheme that knows one statement and one other-name of its own.
    struct Scheme(Oid<'static>);
    impl Recognizer for Scheme {
        type Error = core::convert::Infallible;
        fn recognizes(
            &self,
            _kind: Oid<'_>,
            _execution: &structured_asn1::memory::Memory,
        ) -> core::result::Result<bool, Self::Error> {
            Ok(false)
        }
        fn recognizes_statement(
            &self,
            kind: Oid<'_>,
            _execution: &structured_asn1::memory::Memory,
        ) -> core::result::Result<bool, Self::Error> {
            Ok(kind == self.0)
        }
    }

    // A generic caller may hold its scheme behind a reference, and the
    // blanket implementation for one must forward every role: a role it
    // drops answers the default no, and the scheme's knowledge is lost
    // exactly where a certificate depends on it.
    let national = Oid::from_bytes(&[0x2a, 0x86, 0x24, 0x07, 0x01]);
    let value = fseq(&[fseq(&[oid_of(national), octets(&[0x01])])]);
    let der = seq(&[extension(oid::QC_STATEMENTS, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());

    let scheme = Scheme(national);
    let by_reference: &dyn Recognizer<Error = core::convert::Infallible> = &scheme;
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&by_reference, parser.memory())
            .unwrap()
            .len(),
        0
    );
}

#[test]
fn the_display_text_scan_is_charged_to_the_work_budget() {
    use crate::fixtures::{seq as fseq, utf8};
    let policy = structured_asn1::Oid::from_bytes(&[0x2a, 0x86, 0x24, 0x03, 0x01]);

    // Each display text is bounded at 200 characters, but the number of
    // notices is not, so the aggregate scan is certificate-controlled: forty
    // maximum-sized notices walk far more content than a small budget
    // allows, and deciding whether the critical extension is handled must
    // see that walk on the meter.
    let text = utf8(&"a".repeat(200));
    let notice = fseq(&[
        oid_of(oid::USER_NOTICE_QUALIFIER),
        fseq(core::slice::from_ref(&text)),
    ]);
    let qualifiers: Vec<Vec<u8>> = core::iter::repeat_n(notice, 40).collect();
    let value = fseq(&[fseq(&[oid_of(policy), fseq(&qualifiers)])]);
    let der = seq(&[extension(oid::CERTIFICATE_POLICIES, true, &value)]);

    let limits = structured_asn1::Limits {
        max_work: 8192,
        ..structured_asn1::Limits::default()
    };
    let parser = Parser::new(
        structured_asn1::Encoding::Der,
        limits,
        crate::fixtures::memory(),
    );
    let extensions = parse(&parser, &der).unwrap();
    let error = processing(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap_err(),
    );
    assert_eq!(
        error.code(),
        ErrorCode::Encoding(structured_asn1::ErrorCode::LimitExceeded(
            structured_asn1::Limit::Work
        ))
    );
}

#[test]
fn a_path_length_past_any_path_does_not_block() {
    use crate::fixtures::{boolean, seq as fseq};

    // pathLenConstraint is INTEGER (0..MAX) (RFC 5280 4.2.1.9), so a count
    // wider than any path that could be built is inside the schema: it is a
    // constraint nothing reaches, not a malformed one, and a critical
    // extension carrying it was read entirely.
    let huge = tlv(0x02, &[0x01, 0x00, 0x00, 0x00, 0x00, 0x00]);
    let value = fseq(&[boolean(true), huge]);
    let der = seq(&[extension(oid::BASIC_CONSTRAINTS, true, &value)]);
    let parser = Parser::der(crate::fixtures::memory());
    let extensions = parse(&parser, &der).unwrap();
    assert_eq!(
        extensions
            .unhandled_critical(&(), parser.memory())
            .unwrap()
            .len(),
        0
    );
}

// An infallible test recognizer cannot create a callback failure; retain the
// exact processing error for the existing code/offset budget assertions.
fn processing(error: crate::error::CallbackError<core::convert::Infallible>) -> crate::Error {
    match error {
        crate::error::CallbackError::Processing(error) => error,
        crate::error::CallbackError::Callback(never) => match never {},
    }
}