rpki 0.19.3

A library for validating and creating RPKI data.
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
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
//! Resource certificates.
//!
//! The certificates used in RPKI are called _resource certificates._ They
//! are defined in [RFC 6487] as a profile on regular Internet PKI
//! certificates defined in [RFC 5280]. While they use the format defined
//! for X.509 certificates, the allowed values for various fields are limited
//! making the overall structure more simple and predictable.
//!
//! This module implements raw resource certificates in the type [`Cert`] and
//! validated certificates in the type [`ResourceCert`]. The latter type is
//! used for issuer certificates when validating other certificates.
//!
//! In addition, there are several types for the components of a certificate.
//!
//! [RFC 5280]: https://tools.ietf.org/html/rfc5280
//! [RFC 6487]: https://tools.ietf.org/html/rfc5487

use std::{borrow, fmt, ops};
use std::sync::Arc;
use bcder::{decode, encode};
use bcder::{
    BitString, Captured, ConstOid, Ia5String, Mode, OctetString, Oid, Tag
};
use bcder::decode::{ContentError, DecodeError, IntoSource, Source};
use bcder::encode::{PrimitiveContent, Values};
use bytes::Bytes;
use crate::{oid, uri};
use crate::crypto::{
    KeyIdentifier, PublicKey, RpkiSignatureAlgorithm, SignatureAlgorithm,
    SignatureVerificationError, Signer, SigningError,
};
#[cfg(feature = "serde")] use crate::util::base64;
use super::error::{InspectionError, ValidationError, VerificationError};
use super::resources::{
    AsBlock, AsBlocks, AsBlocksBuilder, AsResources, AsResourcesBuilder,
    IpBlock, IpBlocks, IpBlocksBuilder, IpResources, IpResourcesBuilder
};
use super::tal::TalInfo;
use super::x509::{
    Name, SignedData, Serial, Time, Validity, encode_extension, update_first,
};


//------------ Cert ----------------------------------------------------------

/// A raw resource certificate.
///
/// A value of this type represents a resource certificate. It can be one of
/// three different variants.
///
/// A _CA certificate_ appears in its own file in the repository. Its main
/// use is to sign other certificates.
///
/// An _EE certificate_ is used to sign other objects in the repository, such
/// as manifests or ROAs and is included in the file of these objects. In
/// RPKI, EE certificates are used only once.  Whenever a new object is
/// created, a new EE certificate is created, signed by its CA, used to sign
/// the object, and then the private key is thrown away.
///
/// Finally, _TA certificates_ are the installed trust anchors. These are
/// self-signed.
///
/// If a certificate is stored in a file, you can use the [`decode`] function
/// to parse the entire file. If the certificate is part of some other
/// structure, the [`take_from`] and [`from_constructed`] functions can be
/// used during parsing of that structure.
///
/// Once parsing succeeded, the three methods [`validate_ca`],
/// [`validate_ee`], and [`validate_ta`] can be used to validate the
/// certificate and turn it into a [`ResourceCert`] so it can be used for
/// further processing. In addition, various methods exist to access
/// information contained in the certificate.
///
/// [`decode`]: Cert::decode
/// [`take_from`]: Cert::take_from
/// [`from_constructed`]: Cert::from_constructed
/// [`validate_ca`]: Cert::validate_ca
/// [`validate_ee`]: Cert::validate_ee
/// [`validate_ta`]: Cert::validate_ta
#[derive(Clone, Debug)]
pub struct Cert {
    /// The outer structure of the certificate.
    signed_data: SignedData,

    /// The actual data of the certificate.
    tbs: TbsCert,
}


/// # Decoding and Encoding
///
impl Cert {
    /// Decodes a source as a certificate.
    pub fn decode<S: IntoSource>(
        source: S,
    ) -> Result<Self, DecodeError<<S::Source as Source>::Error>> {
        Mode::Der.decode(source, Self::take_from)
    }

    /// Takes an encoded certificate from the beginning of a value.
    ///
    /// This function assumes that the certificate is encoded in the next
    /// constructed value in `cons` tagged as a sequence.
    pub fn take_from<S: decode::Source>(
        cons: &mut decode::Constructed<S>
    ) -> Result<Self, DecodeError<S::Error>> {
        cons.take_sequence(Self::from_constructed)
    }

    /// Takes an optional certificate from the beginning of a value.
    pub fn take_opt_from<S: decode::Source>(
        cons: &mut decode::Constructed<S>
    ) -> Result<Option<Self>, DecodeError<S::Error>> {
        cons.take_opt_sequence(Self::from_constructed)
    }

    /// Parses the content of a Certificate sequence.
    pub fn from_constructed<S: decode::Source>(
        cons: &mut decode::Constructed<S>
    ) -> Result<Self, DecodeError<S::Error>> {
        let signed_data = SignedData::from_constructed(cons)?;
        let tbs = signed_data.data().clone().decode(
            TbsCert::from_constructed
        ).map_err(DecodeError::convert)?;
        Ok(Self { signed_data, tbs })
    }

    /// Returns a value encoder for a reference to the certificate.
    pub fn encode_ref(&self) -> impl encode::Values + '_ {
        self.signed_data.encode_ref()
    }

    /// Returns a captured encoding of the certificate.
    pub fn to_captured(&self) -> Captured {
        Captured::from_values(Mode::Der, self.encode_ref())
    }
}


/// # Validation
///
/// When validating a certificate, two properties are checked: whether the
/// certificate’s structure and content comply with the specification for
/// resource certificates laid out in [RFC 6487] and whether the certificate
/// has been correctly issued by its CA.
///
/// In some cases it is useful to perform these two steps separately.
/// Therefore, methods are available both for each step and for doing both
/// steps at once. Since we need to name these consistently, we devised the
/// following convention:
///
/// The first step that validates compliance with the specification is called
/// _inspection._ Methods are available to inspect different kinds of
/// certificates. They all have the verb _inspect_ in their name. Only the
/// certificate itself is necessary to perform inspection.
///
/// The second step checking whether the certificate was correctly issued is
/// called _verification._ Methods are available to verify different kinds of
/// certificates. They all have the verb _verify_ in their name and, in
/// most cases, require access to the issuer certificate.
///
/// In addition, methods are available to perform both steps at once for
/// different kinds of certificates. These all have _validate_ in their name.
impl Cert {
    //--- Validation

    /// Validates the certificate as a trust anchor.
    ///
    /// This validates that the certificate “is a current, self-signed RPKI
    /// CA certificate that conforms to the profile as specified in
    /// RFC6487” (RFC7730, section 3, step 2).
    pub fn validate_ta(
        self,
        tal: Arc<TalInfo>,
        strict: bool
    ) -> Result<ResourceCert, ValidationError> {
        self.validate_ta_at(tal, strict, Time::now())
    }

    /// Validates the certificate as a trust anchor at the given time.
    ///
    /// This is identical to [Cert::validate_ta] with an explicitly given
    /// value for the current time.
    pub fn validate_ta_at(
        self,
        tal: Arc<TalInfo>,
        strict: bool,
        now: Time,
    ) -> Result<ResourceCert, ValidationError> {
        self.inspect_ta(strict)?;
        self.verify_ta_at(tal, strict, now).map_err(Into::into)
    }

    /// Validates the certificate as a CA certificate.
    ///
    /// For validation to succeed, the certificate needs to have been signed
    /// by the provided `issuer` certificate.
    ///
    /// Note that this does _not_ check the CRL.
    pub fn validate_ca(
        self,
        issuer: &ResourceCert,
        strict: bool
    ) -> Result<ResourceCert, ValidationError> {
        self.validate_ca_at(issuer, strict, Time::now())
    }

    /// Validates the certificate as a CA certificate at the given time.
    ///
    /// This is identical to [Cert::validate_ca] with an explicitly given
    /// value for the current time.
    pub fn validate_ca_at(
        self,
        issuer: &ResourceCert,
        strict: bool,
        now: Time,
    ) -> Result<ResourceCert, ValidationError> {
        self.inspect_ca(strict)?;
        self.verify_ca_at(issuer, strict, now).map_err(Into::into)
    }

    /// Validates the certificate as an EE RPKI-internal certificate.
    ///
    /// Such a certificate can be found as part of signed objects published
    /// via RPKI repositories.
    ///
    /// For validation to succeed, the certificate needs to have been signed
    /// by the provided `issuer` certificate.
    ///
    /// Note that this does _not_ check the CRL.
    ///
    /// Note further that this method should not be used for router
    /// certificates. Use [`Cert::validate_router]` for those.
    pub fn validate_ee(
        self,
        issuer: &ResourceCert,
        strict: bool
    ) -> Result<ResourceCert, ValidationError>  {
        self.validate_ee_at(issuer, strict, Time::now())
    }

    /// Validates the certificate as an RPKI EE certificate at a time.
    ///
    /// This is identical to [Cert::validate_ee] with an explicitly given
    /// value for the current time.
    pub fn validate_ee_at(
        self,
        issuer: &ResourceCert,
        strict: bool,
        now: Time,
    ) -> Result<ResourceCert, ValidationError>  {
        self.inspect_ee(strict)?;
        self.verify_ee_at(issuer, strict, now).map_err(Into::into)
    }

    /// Validates the certificate as a detached EE certificate.
    ///
    /// Such a certificate is used by signed objects that are not published
    /// through RPKI repositories.
    ///
    /// For validation to succeed, the certificate needs to have been signed
    /// by the provided `issuer` certificate.
    ///
    /// Note that this does _not_ check the CRL.
    pub fn validate_detached_ee(
        self,
        issuer: &ResourceCert,
        strict: bool
    ) -> Result<ResourceCert, ValidationError>  {
        self.validate_detached_ee_at(issuer, strict, Time::now())
    }

    /// Validates the certificate as a detached EE certificate at a given time.
    ///
    /// This is identical to [Cert::validate_detached_ee] with an explicitly
    /// given value for the current time.
    pub fn validate_detached_ee_at(
        self,
        issuer: &ResourceCert,
        strict: bool,
        now: Time,
    ) -> Result<ResourceCert, ValidationError>  {
        self.inspect_detached_ee(strict)?;
        self.verify_ee_at(issuer, strict, now).map_err(Into::into)
    }

    /// Validates the certificate as a BGPsec router certificate.
    ///
    /// For validation to succeed, the certificate needs to have been signed
    /// by the provided `issuer` certificate.
    ///
    /// Note that this does _not_ check the CRL.
    pub fn validate_router(
        &self,
        issuer: &ResourceCert,
        strict: bool
    ) -> Result<(), ValidationError> {
        self.validate_router_at(issuer, strict, Time::now())
    }

    /// Validates the certificate as a BGPsec router certificate at a time.
    ///
    /// This is identical to [Cert::validate_router] with an explicitly
    /// given value for the current time.
    pub fn validate_router_at(
        &self,
        issuer: &ResourceCert,
        strict: bool,
        now: Time,
    ) -> Result<(), ValidationError> {
        self.inspect_router(strict)?;
        self.verify_router_at(issuer, strict, now).map_err(Into::into)
    }


    //--- Inspection

    /// Inspects the certificate as a trust anchor.
    ///
    /// Checks that the certificate fulfills the formal requirements of a
    /// RPKI trust anchor certificate.
    pub fn inspect_ta(
        &self, strict: bool,
    ) -> Result<(), InspectionError> {
        self.inspect_basics(strict)?;
        self.inspect_ca_basics(strict)?;

        // 4.8.3. Authority Key Identifier. May be present, if so, must be
        // equal to the subject key identifier.
        if let Some(ref aki) = self.authority_key_identifier {
            if *aki != self.subject_key_identifier {
                return Err(InspectionError::new(
                    "Authority Key Identifier doesn't match \
                    Subject Key Identifier"
                ));
            }
        }

        // 4.8.6. CRL Distribution Points. There mustn’t be one.
        if self.crl_uri.is_some() {
            return Err(InspectionError::new(
                "CRL Distribution Points extension \
                 not allowed in trust anchor certificate"
            ))
        }

        // 4.8.7. Authority Information Access. Must not be present.
        if self.ca_issuer.is_some() {
            return Err(InspectionError::new(
                "Authority Information Access extension \
                 not allowed in trust anchor certificate"
            ))
        }

        // 4.8.10. IP Resources.
        // 4.8.11. AS Resources.
        //
        // Are checked as part of verification.

        Ok(())
    }

    /// Inspects the certificate as a CA certificate.
    ///
    /// Checks that the certificate fulfills the formal requirements of a
    /// CA certificate.
    pub fn inspect_ca(&self, strict: bool) -> Result<(), InspectionError> {
        self.inspect_basics(strict)?;
        self.inspect_ca_basics(strict)?;
        self.inspect_issued(strict)
    }

    /// Validates the certificate as an EE RPKI-internal certificate.
    ///
    /// Checks that the certificate fulfills all formal requirements of such
    /// a certificate.
    pub fn inspect_ee(&self, strict: bool) -> Result<(), InspectionError> {
        self.inspect_basics(strict)?;
        self.inspect_issued(strict)?;

        // 4.8.1. Basic Constraints: Must not be present.
        if self.basic_ca.is_some(){
            return Err(InspectionError::new(
                "Basic Constraints extension \
                 not allowed in end entity certificate"
            ))
        }

        // 4.8.4. Key Usage. Bits for CA or not CA have been checked during
        // parsing already.
        if self.key_usage != KeyUsage::Ee {
            return Err(InspectionError::new(
                "invalid Key Usage extension \
                 for end entity certificate"
            ))
        }

        // 4.8.8.  Subject Information Access. We need the signed object
        // but not the other ones.
        if self.ca_repository.is_some() {
            return Err(InspectionError::new(
                "id-ad-caRepository SIA instance \
                 not allowed in end entity certificate"
            ))
        }
        if self.rpki_manifest.is_some() {
            return Err(InspectionError::new(
                "id-ad-rpkiManifest SIA instance \
                 not allowed in end entity certificate"
            ))
        }
        if self.signed_object.is_none() {
            return Err(InspectionError::new(
                "missing id-ad-signedObject SIA instance \
                 in signed object end entity certificate"
            ))
        }

        Ok(())
    }

    /// Inspects the certificate as a detached EE certificate.
    ///
    /// Checks that the certificate fulfills all formal requirements of such
    /// a certificate.
    pub fn inspect_detached_ee(
        &self, strict: bool
    ) -> Result<(), InspectionError> {
        self.inspect_basics(strict)?;
        self.inspect_issued(strict)?;

        // 4.8.1. Basic Constraints: Must not be present.
        if self.basic_ca.is_some(){
            return Err(InspectionError::new(
                "Basic Constraints extension \
                 not allowed in end entity certificate"
            ))
        }

        // 4.8.4. Key Usage. Bits for CA or not CA have been checked during
        // parsing already.
        if self.key_usage != KeyUsage::Ee {
            return Err(InspectionError::new(
                "invalid Key Usage extension \
                 for end entity certificate"
            ))
        }

        // 4.8.8.  Subject Information Access. We allow the signed object one
        // but not the other ones.
        if self.ca_repository.is_some() {
            return Err(InspectionError::new(
                "id-ad-caRepository SIA instance \
                 not allowed in end entity certificate"
            ))
        }
        if self.rpki_manifest.is_some() {
            return Err(InspectionError::new(
                "id-ad-rpkiManifest SIA instance \
                 not allowed in end entity certificate"
            ))
        }

        Ok(())
    }

    /// Inspects the certificate as a BGPsec router certificate.
    ///
    /// Checks that the certificate fulfills all formal requirements of such
    /// a certificate.
    pub fn inspect_router(
        &self, strict: bool
    ) -> Result<(), InspectionError> {
        // 4.2 Serial Number: must be unique over the CA. We cannot check
        // here, and -- XXX --- probably don’t care?

        // 4.3 Signature Algorithm: limited to those in RFC 6485. Already
        // checked in parsing.
        //
        // However, RFC 5280 demands that the two mentions of the signature
        // algorithm are the same. So we do that here.
        if self.signature != *self.signed_data.signature().algorithm() {
            return Err(InspectionError::new(
                "signature algorithm mismatch"
            ))
        }

        // 4.4 Issuer: must have certain format.
        Name::inspect_rpki(&self.issuer, strict).map_err(IssuerError)?;

        // 4.5 Subject: same as 4.4.
        Name::inspect_router(&self.subject, strict).map_err(SubjectError)?;

        // 4.6 Validity. Checked during verification.

        // 4.7 Subject Public Key Info: limited algorithms.
        if !self.subject_public_key_info().allow_router_cert() {
            return Err(InspectionError::new(
                "invalid public key algorithm for router certificate"
            ))
        }

        // 4.8.1. Basic Constraints. Must not be present.
        if self.basic_ca.is_some(){
            return Err(InspectionError::new(
                "Basic Constraints extension \
                 not allowed in end entity certificate"
            ))
        }

        // 4.8.2. Subject Key Identifier. Must be the SHA-1 hash of the octets
        // of the subjectPublicKey.
        if self.subject_key_identifier() !=
            self.subject_public_key_info().key_identifier()
        {
            return Err(InspectionError::new(
                "Subject Key Identifier extension doesn't match \
                 the public key"
            ))
        }

        // 4.8.3. Authority Key Identifier. Will be checked during
        // verification later.

        // 4.8.4. Key Usage. Must be EE.
        if self.key_usage != KeyUsage::Ee {
            return Err(InspectionError::new(
                "invalid Key Usage extension \
                 for end entity certificate"
            ))
        }

        // 4.8.5. Extended Key Usage.
        //
        // Must be present and contain at least the kp-bgpsec-router OID.
        match self.extended_key_usage().as_ref() {
            Some(eku) => eku.inspect_router()?,
            None => {
                return Err(InspectionError::new(
                    "missing Extended Key Usage extension \
                     in router certificate"
                ))
            }
        }

        // 4.8.6. CRL Distribution Points. There must be one.
        if self.crl_uri().is_none() {
            return Err(InspectionError::new(
                "missing CRL Distribution Points extension \
                 in router certificate"
            ))
        }

        // 4.8.7. Authority Information Access. Checked during verification.

        // 4.8.8.  Subject Information Access. There must be none.
        if self.ca_repository().is_some() || self.rpki_manifest().is_some()
            || self.signed_object().is_some() || self.rpki_notify().is_some()
        {
            return Err(InspectionError::new(
                "Subject Information Access extension \
                 not allowed in router certificate"
            ))
        }

        // 4.8.9.  Certificate Policies. XXX I think this can be ignored.
        // At least for now.

        // 4.8.10.  IP Resources.  Must not be present.
        if self.v4_resources().is_present() || self.v6_resources().is_present()
        {
            return Err(InspectionError::new(
                "IP Resources extension \
                 not allowed in router certificate"
            ))
        }

        // 4.8.11.  AS Resources. Differs between trust anchor and issued
        // certificates.
        if !self.as_resources().is_present() {
            return Err(InspectionError::new(
                "missing AS Resources extension \
                 in router certificate"
            ))
        }
        if self.as_resources().is_inherited() {
            return Err(InspectionError::new(
                "inherited AS Resources in router certificate"
            ))
        }

        Ok(())
    }

    //--- Verification

    /// Verifies a trust anchor certificate. 
    pub fn verify_ta(
        self, tal: Arc<TalInfo>, strict: bool,
    ) -> Result<ResourceCert, VerificationError> {
        self.verify_ta_at(tal, strict, Time::now())
    }

    /// Verifies a trust anchor certificate at the given time. 
    pub fn verify_ta_at(
        self, tal: Arc<TalInfo>, _strict: bool, now: Time,
    ) -> Result<ResourceCert, VerificationError> {
        // 4.6 Validity.
        self.verify_validity(now)?;
        
        // 4.8.10. IP Resources. If present, mustn’t be "inherit".
        let v4_resources = IpBlocks::from_resources(
            self.v4_resources.clone()
        ).map_err(|_| {
            VerificationError::new(
                "inherited IPv4 resources not allowed \
                 in trust anchor certificate"
            )
        })?;
        let v6_resources = IpBlocks::from_resources(
            self.v6_resources.clone()
        ).map_err(|_| {
            VerificationError::new(
                "inherited IPv6 resources not allowed \
                 in trust anchor certificate"
            )
        })?;

        // 4.8.11.  AS Resources. If present, mustn’t be "inherit". That
        // IP resources (logical) or AS resources are present has already
        // been checked during parsing.
        let as_resources = AsBlocks::from_resources(
            self.as_resources.clone()
        ).map_err(|_| {
            VerificationError::new(
                "inherited AS resources not allowed \
                 in trust anchor certificate"
            )
        })?;

        self.signed_data.verify_signature(
            &self.subject_public_key_info
        )?;

        Ok(ResourceCert {
            cert: self,
            v4_resources,
            v6_resources,
            as_resources,
            tal
        })
    }

    /// Verify a trust anchor certificate without converting it.
    pub fn verify_ta_ref(
        &self, strict: bool
    ) -> Result<(), VerificationError> {
        self.verify_ta_ref_at(strict, Time::now())
    }

    /// Verify a trust anchor certificate without converting it at a time.
    pub fn verify_ta_ref_at(
        &self, _strict: bool, now: Time,
    ) -> Result<(), VerificationError> {
        // 4.6 Validity.
        self.verify_validity(now)?;

        // 4.8.10. IP Resources. If present, mustn’t be "inherit".
        if self.v4_resources.is_inherited() {
            return Err(VerificationError::new(
                "inherited IPv4 resources not allowed \
                 in trust anchor certificate"
            ))
        }
        if self.v6_resources.is_inherited() {
            return Err(VerificationError::new(
                "inherited IPv6 resources not allowed \
                 in trust anchor certificate"
            ))
        }

        // 4.8.11.  AS Resources. If present, mustn’t be "inherit".
        if self.as_resources.is_inherited() {
            return Err(VerificationError::new(
                "inherited AS resources not allowed \
                 in trust anchor certificate"
            ))
        }

        self.signed_data.verify_signature(
            &self.subject_public_key_info
        )?;

        Ok(())
    }

    /// Verifies the certificate as an issued CA certificate.
    ///
    /// Checks that the certificate has been correctly issued by `issuer` as
    /// a CA certificate.
    pub fn verify_ca(
        self, issuer: &ResourceCert, strict: bool
    ) -> Result<ResourceCert, VerificationError> {
        self.verify_ca_at(issuer, strict, Time::now())
    }

    /// Verifies the certificate as an issued CA certificate at a given time.
    ///
    /// This is identical to [`Cert::verify_ca`] with an explicitly
    /// given value for the current time.
    pub fn verify_ca_at(
        self, issuer: &ResourceCert, strict: bool, now: Time,
    ) -> Result<ResourceCert, VerificationError> {
        self.verify_validity(now)?;
        self.verify_issuer_claim(issuer, strict)?;
        self.verify_signature(issuer, strict)?;
        self.verify_resources(issuer, strict)
    }

    /// Verifies the certificate as an RPKI EE certificate.
    ///
    /// Checks that the certificate has been correctly issued by `issuer` as
    /// an RPKI EE certificate.
    pub fn verify_ee(
        self, issuer: &ResourceCert, strict: bool,
    ) -> Result<ResourceCert, VerificationError> {
        self.verify_ee_at(issuer, strict, Time::now())
    }

    /// Verifies the certificate as an RPKI EE certificate at a time.
    ///
    /// This is identical to [`Cert::verify_ee`] with an explicitly
    /// given value for the current time.
    pub fn verify_ee_at(
        self, issuer: &ResourceCert, strict: bool, now: Time,
    ) -> Result<ResourceCert, VerificationError> {
        self.verify_validity(now)?;
        self.verify_issuer_claim(issuer, strict)?;
        self.verify_signature(issuer, strict)?;
        self.verify_resources(issuer, strict)
    }

    /// Verifies the certificate as a BGPsec router certificate.
    ///
    /// Checks that the certificate has been correctly issued by `issuer` as
    /// an router certificate.
    pub fn verify_router(
        &self, issuer: &ResourceCert, strict: bool,
    ) -> Result<(), VerificationError> {
        self.verify_router_at(issuer, strict, Time::now())
    }

    /// Verifies the certificate as a router certificate at a given time.
    ///
    /// This is identical to [`Cert::verify_router`] with an explicitly
    /// given value for the current time.
    pub fn verify_router_at(
        &self, issuer: &ResourceCert, strict: bool, now: Time,
    ) -> Result<(), VerificationError> {
        self.verify_validity(now)?;
        self.verify_issuer_claim(issuer, strict)?;
        self.verify_signature(issuer, strict)?;
        self.verify_as_resources(issuer, strict)
    }


    //--- Validation Components

    /// Inspects basic compliance with section 4 of RFC 6487.
    fn inspect_basics(
        &self,
        strict: bool,
    ) -> Result<(), InspectionError> {
        // The following lists all such constraints in the RFC, noting those
        // that we cannot check here.

        // 4.2 Serial Number: must be unique over the CA. We cannot check
        // here, and -- XXX --- probably don’t care?

        // 4.3 Signature Algorithm: limited to those in RFC 6485. Already
        // checked in parsing.
        //
        // However, RFC 5280 demands that the two mentions of the signature
        // algorithm are the same. So we do that here.
        if self.signature != *self.signed_data.signature().algorithm() {
            return Err(InspectionError::new(
                "signature algorithm mismatch in certificate"
            ))
        }

        // 4.4 Issuer: must have certain format.
        Name::inspect_rpki(&self.issuer, strict).map_err(IssuerError)?;

        // 4.5 Subject: same as 4.4.
        Name::inspect_rpki(&self.subject, strict).map_err(SubjectError)?;

        // 4.6 Validity. Checked during verification.

        // 4.7 Subject Public Key Info: limited algorithms.
        if !self.subject_public_key_info().allow_rpki_cert() {
            return Err(InspectionError::new(
                "public key algorithm not allowed for RPKI certificates"
            ))
        }

        // 4.8.1. Basic Constraints. Differing requirements for CA and EE
        // certificates.

        // 4.8.2. Subject Key Identifier. Must be the SHA-1 hash of the octets
        // of the subjectPublicKey.
        if self.subject_key_identifier()
            != self.subject_public_key_info().key_identifier()
        {
            return Err(InspectionError::new(
                "Subject Key Identifier extension \
                 doesn't match public key"
            ))
        }

        // 4.8.3. Authority Key Identifier. Differing requirements of TA and
        // other certificates.

        // 4.8.4. Key Usage. Differs between CA and EE certificates.

        // 4.8.5. Extended Key Usage. Must not be present for the kind of
        // certificates we use here.
        if self.extended_key_usage().is_some() {
            return Err(InspectionError::new(
                "Extended Key Usage extension \
                 not allowed in RPKI certificates"
            ))
        }

        // 4.8.6. CRL Distribution Points. Differs between TA and other
        // certificates.

        // 4.8.7. Authority Information Access. Differs between TA and other
        // certificates.

        // 4.8.8.  Subject Information Access. Differs between CA and EE
        // certificates.

        // 4.8.9.  Certificate Policies. XXX I think this can be ignored.
        // At least for now.

        // 4.8.10.  IP Resources. Differs between trust anchor and issued
        // certificates.

        // 4.8.11.  AS Resources. Differs between trust anchor and issued
        // certificates.

        Ok(())
    }

    fn inspect_issued(&self, _strict: bool) -> Result<(), InspectionError> {
        // 4.8.6. CRL Distribution Points. There must be one.
        if self.crl_uri().is_none() {
            return Err(InspectionError::new(
                "missing CRL Distribution Points extension in certificate"
            ))
        }

        Ok(())
    }

    /// Validates that the certificate is a valid CA certificate.
    ///
    /// Checks the parts that are common in normal and trust anchor CA
    /// certificates.
    fn inspect_ca_basics(
        &self,
        _strict: bool
    ) -> Result<(), InspectionError> {
        // 4.8.1. Basic Constraints: For a CA it must be present (RFC6487)
        // und the “cA” flag must be set (RFC5280).
        match self.basic_ca() {
            Some(true) => { }
            Some(false) => {
                return Err(InspectionError::new(
                    "cA flag in Basic Constraints extension set to false"
                ))
            }
            None => {
                return Err(InspectionError::new(
                    "missing Basic Constraints extension \
                     in CA certificate"
                ))
            }
        }

        // 4.8.4. Key Usage. Bits for CA or not CA have been checked during
        // parsing already.
        if self.key_usage() != KeyUsage::Ca {
            return Err(InspectionError::new(
                "invalid Key Usage in CA certificate"
            ))
        }

        // 4.8.8.  Subject Information Access.
        if self.ca_repository().is_none() {
            return Err(InspectionError::new(
                "missing id-ad-caRepository SIA instance in CA certificate"
            ))
        }
        if self.rpki_manifest().is_none() {
            return Err(InspectionError::new(
                "missing id-ad-rpkiManifest SIA instance in CA certificate"
            ))
        }
        if self.signed_object().is_some() {
            return Err(InspectionError::new(
                "id-ad-signedObject SIA instance not allowed \
                 in CA certificate"
            ))
        }

        Ok(())
    }

    /// Verifies that the certificate is valid at the given time.
    pub fn verify_validity(
        &self, now: Time,
    ) -> Result<(), VerificationError> {
        self.validity.verify_at(now).map_err(Into::into)
    }

    /// Verifies that the certificate claims to have been issued by `issuer`.
    ///
    /// This is only the first part of verification. You _must_ call
    /// `verified_signature`, too.
    pub fn verify_issuer_claim(
        &self,
        issuer: &ResourceCert,
        _strict: bool,
    ) -> Result<(), VerificationError> {
        // 4.8.3. Authority Key Identifier. Must be present and match the
        // subject key ID of `issuer`.
        match self.authority_key_identifier() {
            Some(aki) => {
                if aki != issuer.cert.subject_key_identifier() {
                    return Err(VerificationError::new(
                        "certificate's Authority Key Identifier doesn't \
                         match issuer's Subject Key Identifier"
                    ))
                }
            }
            None => {
                return Err(VerificationError::new(
                    "missing Authority Key Identifier extension \
                     on certificate"
                ))
            }
        }

        // 4.8.7. Authority Information Access. Must be present and contain
        // the URI of the issuer certificate. Since we do top-down validation,
        // we don’t really need that URI so – XXX – leave it unchecked for
        // now.
        if self.ca_issuer().is_none() {
            return Err(VerificationError::new(
                "missing Authority Information Access extension \
                 on certificate"
            ))
        }

        Ok(())
    }

    /// Validates the certificate’s signature.
    pub fn verify_signature(
        &self,
        issuer: &Cert,
        _strict: bool
    ) -> Result<(), SignatureVerificationError> {
        self.signed_data.verify_signature(
            issuer.subject_public_key_info()
        )
    }

    /// Validates and extracts the IP and AS resources.
    ///
    /// Upon success, this converts the certificate into a `ResourceCert`.
    fn verify_resources(
        self,
        issuer: &ResourceCert,
        _strict: bool
    ) -> Result<ResourceCert, VerificationError> {
        Ok(ResourceCert {
            // 4.8.10.  IP Resources. If present, must be encompassed by or
            // trimmed down to the issuer certificate.
            v4_resources: issuer.v4_resources.verify_issued(
                self.v4_resources(), self.overclaim
            ).map_err(|_| {
                VerificationError::new(
                    "certificate is overclaiming IPv4 resources"
                )
            })?,
            v6_resources: issuer.v6_resources.verify_issued(
                self.v6_resources(), self.overclaim
            ).map_err(|_| {
                VerificationError::new(
                    "certificate is overclaiming IPv6 resources"
                )
            })?,
            // 4.8.11.  AS Resources. If present, must be encompassed by or
            // trimmed down to the issuer.
            as_resources: issuer.as_resources.verify_issued(
                self.as_resources(), self.overclaim()
            ).map_err(|_| {
                VerificationError::new(
                    "certificate is overclaiming AS resources"
                )
            })?,
            cert: self,
            tal: issuer.tal.clone(),
        })
    }

    /// Validates the AS resources for router certificates.
    fn verify_as_resources(
        &self,
        issuer: &ResourceCert,
        _strict: bool
    ) -> Result<(), VerificationError> {
        let _ = issuer.as_resources.verify_issued(
            self.as_resources(), self.overclaim()
        ).map_err(|_| {
            VerificationError::new(
                "certificate is overclaiming AS resources"
            )
        })?;
        Ok(())
    }
}


//--- Deref, AsRef, and Borrow

impl ops::Deref for Cert {
    type Target = TbsCert;

    fn deref(&self) -> &Self::Target {
        &self.tbs
    }
}

impl AsRef<Cert> for Cert {
    fn as_ref(&self) -> &Self {
        self
    }
}

impl AsRef<TbsCert> for Cert {
    fn as_ref(&self) -> &TbsCert {
        &self.tbs
    }
}

impl borrow::Borrow<TbsCert> for Cert {
    fn borrow(&self) -> &TbsCert {
        &self.tbs
    }
}


//--- Deserialize and Serialize

#[cfg(feature = "serde")]
impl serde::Serialize for Cert {
    fn serialize<S: serde::Serializer>(
        &self, serializer: S
    ) -> Result<S::Ok, S::Error> {
        let bytes = self.to_captured().into_bytes();
        let b64 = base64::Serde.encode(&bytes);
        b64.serialize(serializer)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Cert {
    fn deserialize<D: serde::Deserializer<'de>>(
        deserializer: D
    ) -> Result<Self, D::Error> {
        use serde::de;

        let s = String::deserialize(deserializer)?;
        let decoded = base64::Serde.decode(&s).map_err(de::Error::custom)?;
        let bytes = Bytes::from(decoded);
        Cert::decode(bytes).map_err(de::Error::custom)
    }
}


//------------ TbsCert -------------------------------------------------------

/// The data of a resource certificate.
#[derive(Clone, Debug)]
pub struct TbsCert {
    /// The serial number.
    serial_number: Serial,

    /// The algorithm used for signing the certificate.
    signature: RpkiSignatureAlgorithm,

    /// The name of the issuer.
    ///
    /// It isn’t really relevant in RPKI.
    issuer: Name,

    /// The validity of the certificate.
    validity: Validity,

    /// The name of the subject of this certificate.
    ///
    /// This isn’t really relevant in RPKI.
    subject: Name,

    /// Information about the public key of this certificate.
    subject_public_key_info: PublicKey,

    /// Basic Constraints extension.
    ///
    /// The field indicates whether the extension is present and, if so,
    /// whether the "cA" boolean is set. See 4.8.1. of RFC 6487.
    basic_ca: Option<bool>,

    /// Subject Key Identifier extension.
    subject_key_identifier: KeyIdentifier,

    /// Authority Key Identifier extension.
    authority_key_identifier: Option<KeyIdentifier>,

    /// Key Usage.
    ///
    key_usage: KeyUsage,

    /// Extended Key Usage.
    ///
    /// The value is the content of the DER-encoded sequence of object
    /// identifiers.
    extended_key_usage: Option<ExtendedKeyUsage>,

    // The following fields are lists of URIs. Each has to have at least one
    // rsync or HTTPS URI but may contain more. We only support those primary
    // URIs for now, so we don’t keep the full list but only the one URI we
    // need.

    /// CRL Distribution Points.
    crl_uri: Option<uri::Rsync>,

    /// Authority Information Access of type `id-ad-caIssuer`.
    ca_issuer: Option<uri::Rsync>,

    /// Subject Information Access of type `id-ad-caRepository`
    ca_repository: Option<uri::Rsync>,

    /// Subject Information Access of type `id-ad-rpkiManifest`
    rpki_manifest: Option<uri::Rsync>,

    /// Subject Information Access of type `id-ad-signedObject`
    signed_object: Option<uri::Rsync>,

    /// Subject Information Access of type `id-ad-rpkiNotify`
    rpki_notify: Option<uri::Https>,

    /// Certificate Policies
    ///
    /// Must be present and critical. RFC 6484 demands there to be a single
    /// policy with a specific OID and no parameters. RFC 8630 adds a second
    /// OID for a different way of handling overclaim of resources.
    ///
    /// We reflect this choice of policy with an overclaim mode.
    overclaim: Overclaim,

    /// IP Resources for the IPv4 address family.
    v4_resources: IpResources,

    /// IP Resources for the IPv6 address family.
    v6_resources: IpResources,

    /// AS Resources
    as_resources: AsResources,
}


/// # Creation and Conversion
///
impl TbsCert {
    /// Creates a new value from the necessary data.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        serial_number: Serial,
        issuer: Name,
        validity: Validity,
        subject: Option<Name>,
        subject_public_key_info: PublicKey,
        key_usage: KeyUsage,
        overclaim: Overclaim,
    ) -> Self {
        Self {
            serial_number,
            signature: RpkiSignatureAlgorithm::default(),
            issuer,
            validity,
            subject: {
                subject.unwrap_or_else(||
                    subject_public_key_info.to_subject_name()
                )
            },
            subject_key_identifier: subject_public_key_info.key_identifier(),
            subject_public_key_info,
            basic_ca: None,
            authority_key_identifier: None,
            key_usage,
            extended_key_usage: None,
            crl_uri: None,
            ca_issuer: None,
            ca_repository: None,
            rpki_manifest: None,
            signed_object: None,
            rpki_notify: None,
            overclaim,
            v4_resources: IpResources::missing(),
            v6_resources: IpResources::missing(),
            as_resources: AsResources::missing(),
        }
    }

    /// Converts the value into a signed certificate.
    pub fn into_cert<S: Signer>(
        self,
        signer: &S,
        key: &S::KeyId,
    ) -> Result<Cert, SigningError<S::Error>> {
        let data = Captured::from_values(Mode::Der, self.encode_ref());
        let signature = signer.sign(key, self.signature, &data)?;
        Ok(Cert {
            signed_data: SignedData::new(data, signature),
            tbs: self
        })
    }
}


/// # Data Access
///
impl TbsCert {
    /// Returns the serial number of the certificate.
    pub fn serial_number(&self) -> Serial {
        self.serial_number
    }

    /// Set the serial number of the certificate.
    pub fn set_serial_number<S: Into<Serial>>(&mut self, serial: S) {
        self.serial_number = serial.into()
    }

    /// Returns a reference to the issuer.
    pub fn issuer(&self) -> &Name {
        &self.issuer
    }

    /// Sets the issuer.
    pub fn set_issuer(&mut self, name: Name) {
        self.issuer = name
    }

    /// Returns a reference to the validity.
    pub fn validity(&self) -> Validity {
        self.validity
    }

    /// Sets the validity.
    pub fn set_validity(&mut self, validity: Validity) {
        self.validity = validity
    }

    /// Returns a reference to the subject.
    pub fn subject(&self) -> &Name {
        &self.subject
    }

    /// Sets the subject.
    pub fn set_subject(&mut self, subject: Name) {
        self.subject = subject
    }

    /// Returns a reference to the public key.
    pub fn subject_public_key_info(&self) -> &PublicKey {
        &self.subject_public_key_info
    }

    /// Sets the public key.
    ///
    /// This sets both the value of the `subject_public_key_info` field to
    /// the public key itself as well as the `subject_public_key_identifier`
    /// to the identifier of that key.
    pub fn set_subject_public_key(&mut self, key: PublicKey) {
        self.subject_key_identifier = key.key_identifier();
        self.subject_public_key_info = key;
    }

    /// Returns the cA field of the basic constraints extension if present.
    pub fn basic_ca(&self) -> Option<bool> {
        self.basic_ca
    }

    /// Sets the basic constraints extension.
    ///
    /// If `value` is `None`, the extension will be absent. If it is some
    /// value, the boolean is the value of the `cA` field of the extension.
    pub fn set_basic_ca(&mut self, value: Option<bool>) {
        self.basic_ca = value
    }

    /// Returns a reference to the subject key identifier.
    ///
    /// There is no method to set this extension as this happens automatically
    /// when the subject public key is set via [`set_subject_public_key`].
    ///
    /// [`set_subject_public_key`]: #method.set_subject_public_key
    pub fn subject_key_identifier(&self) -> KeyIdentifier {
        self.subject_key_identifier
    }

    /// Returns a reference to the authority key identifier if present.
    pub fn authority_key_identifier(&self) -> Option<KeyIdentifier> {
        self.authority_key_identifier
    }

    /// Sets the authority key identifier extension.
    pub fn set_authority_key_identifier(
        &mut self,
        id: Option<KeyIdentifier>
    ) {
        self.authority_key_identifier = id
    }

    /// Returns the key usage of the certificate.
    pub fn key_usage(&self) -> KeyUsage {
        self.key_usage
    }

    /// Sets the key usage of the certificate.
    pub fn set_key_usage(&mut self, key_usage: KeyUsage) {
        self.key_usage = key_usage
    }

    /// Returns a reference to the extended key usage if present.
    ///
    /// Since this field isn’t allowed in any certificate used for RPKI
    /// objects directly, we do not currently support setting this field.
    pub fn extended_key_usage(&self) -> Option<&ExtendedKeyUsage> {
        self.extended_key_usage.as_ref()
    }

    /// Sets the extended key usage.
    pub fn set_extended_key_usage(&mut self, eku: Option<ExtendedKeyUsage>) {
        self.extended_key_usage = eku
    }

    /// Returns a reference to the certificate’s CRL distribution point.
    pub fn crl_uri(&self) -> Option<&uri::Rsync> {
        self.crl_uri.as_ref()
    }

    /// Sets the CRL distribution point.
    pub fn set_crl_uri(&mut self, uri: Option<uri::Rsync>) {
        self.crl_uri = uri
    }

    /// Returns a reference to *caIssuer* AIA rsync URI if present.
    pub fn ca_issuer(&self) -> Option<&uri::Rsync> {
        self.ca_issuer.as_ref()
    }

    /// Sets the *caIssuer* AIA rsync URI.
    pub fn set_ca_issuer(&mut self, uri: Option<uri::Rsync>) {
        self.ca_issuer= uri
    }

    /// Returns a reference to the *caRepository* SIA rsync URI if present.
    pub fn ca_repository(&self) -> Option<&uri::Rsync> {
        self.ca_repository.as_ref()
    }

    /// Sets the *caRepository* SIA rsync URI.
    pub fn set_ca_repository(&mut self, uri: Option<uri::Rsync>) {
        self.ca_repository = uri
    }

    /// Returns a reference to the *rpkiManifest* SIA rsync URI if present.
    pub fn rpki_manifest(&self) -> Option<&uri::Rsync> {
        self.rpki_manifest.as_ref()
    }

    /// Sets the *rpkiManifest* SIA rsync URI.
    pub fn set_rpki_manifest(&mut self, uri: Option<uri::Rsync>) {
        self.rpki_manifest = uri
    }

    /// Returns a reference to the *signedObject* SIA rsync URI if present.
    pub fn signed_object(&self) -> Option<&uri::Rsync> {
        self.signed_object.as_ref()
    }

    /// Sets the *signedObject* SIA rsync URI.
    pub fn set_signed_object(&mut self, uri: Option<uri::Rsync>) {
        self.signed_object = uri
    }

    /// Returns a reference to the *rpkiNotify* SIA HTTPS URI if present.
    pub fn rpki_notify(&self) -> Option<&uri::Https> {
        self.rpki_notify.as_ref()
    }

    /// Sets the *rpkiNotify* SIA HTTPS URI.
    pub fn set_rpki_notify(&mut self, uri: Option<uri::Https>) {
        self.rpki_notify = uri
    }

    /// Returns the overclaim mode of the certificate.
    pub fn overclaim(&self) -> Overclaim {
        self.overclaim
    }

    /// Sets the overclaim mode of the certificate.
    pub fn set_overclaim(&mut self, overclaim: Overclaim) {
        self.overclaim = overclaim
    }

    /// Returns a reference to the IPv4 address resources if present.
    pub fn v4_resources(&self) -> &IpResources {
        &self.v4_resources
    }

    /// Set the IPv4 address resources.
    pub fn set_v4_resources(&mut self, resources: IpResources) {
        self.v4_resources = resources
    }

    /// Sets the IPv4 address resources to inherit.
    pub fn set_v4_resources_inherit(&mut self) {
        self.set_v4_resources(IpResources::inherit())
    }

    /// Builds the blocks IPv4 address resources.
    pub fn build_v4_resource_blocks<F>(&mut self, op: F)
    where F: FnOnce(&mut IpBlocksBuilder) {
        let mut builder = IpResourcesBuilder::new();
        builder.blocks(op);
        self.set_v4_resources(builder.finalize())
    }

    /// Builds the IPv4 address resources from an iterator over blocks.
    pub fn v4_resources_from_iter<I>(&mut self, iter: I)
    where I: IntoIterator<Item=IpBlock> {
        self.v4_resources = IpResources::blocks(IpBlocks::from_iter(iter))
    }

    /// Returns a reference to the IPv6 address resources if present.
    pub fn v6_resources(&self) -> &IpResources {
        &self.v6_resources
    }

    /// Set the IPv6 address resources.
    pub fn set_v6_resources(&mut self, resources: IpResources) {
        self.v6_resources = resources
    }

    /// Sets the IPv6 address resources to inherit.
    pub fn set_v6_resources_inherit(&mut self) {
        self.set_v6_resources(IpResources::inherit())
    }

    /// Builds the blocks IPv6 address resources.
    pub fn build_v6_resource_blocks<F>(&mut self, op: F)
    where F: FnOnce(&mut IpBlocksBuilder) {
        let mut builder = IpResourcesBuilder::new();
        builder.blocks(op);
        self.set_v6_resources(builder.finalize())
    }

    /// Builds the IPv6 address resources from an iterator over blocks
    pub fn v6_resources_from_iter<I>(&mut self, iter: I)
    where I: IntoIterator<Item=IpBlock> {
        self.v6_resources = IpResources::blocks(IpBlocks::from_iter(iter))
    }

    /// Returns whether the certificate has any IP resources at all.
    pub fn has_ip_resources(&self) -> bool {
        self.v4_resources.is_present() || self.v6_resources().is_present()
    }

    /// Returns a reference to the AS resources.
    pub fn as_resources(&self) -> &AsResources {
        &self.as_resources
    }

    /// Set the AS resources.
    pub fn set_as_resources(&mut self, resources: AsResources) {
        self.as_resources = resources
    }

    /// Sets the AS resources to inherit.
    pub fn set_as_resources_inherit(&mut self) {
        self.set_as_resources(AsResources::inherit())
    }

    /// Builds the blocks AS resources.
    pub fn build_as_resource_blocks<F>(&mut self, op: F)
    where F: FnOnce(&mut AsBlocksBuilder) {
        let mut builder = AsResourcesBuilder::new();
        builder.blocks(op);
        self.set_as_resources(builder.finalize())
    }

    /// Builds the AS resources from an iterator over blocks.
    pub fn as_resources_from_iter<I>(&mut self, iter: I)
    where I: IntoIterator<Item = AsBlock> {
        self.as_resources = AsResources::blocks(AsBlocks::from_iter(iter))
    }

    /// Returns whether this is a CA certificate if validation succeeds.
    pub fn is_ca(&self) -> bool {
        self.basic_ca.unwrap_or(false)
    }

    /// Returns whether this is a self-signed certificate if valid.
    pub fn is_self_signed(&self) -> bool {
        match self.authority_key_identifier {
            Some(aki) => aki == self.subject_key_identifier,
            None => true
        }
    }
}


/// # Decoding and Encoding
///
impl TbsCert {
    /// Parses the content of a Certificate sequence.
    pub fn from_constructed<S: decode::Source>(
        cons: &mut decode::Constructed<S>
    ) -> Result<Self, DecodeError<S::Error>> {
        cons.take_sequence(|cons| {
            // version [0] EXPLICIT Version DEFAULT v1.
            //  -- we need extensions so apparently, we want v3 which,
            //     confusingly, is 2.
            cons.take_constructed_if(Tag::CTX_0, |c| c.skip_u8_if(2))?;

            let serial_number = Serial::take_from(cons)?;
            let signature = RpkiSignatureAlgorithm::x509_take_from(cons)?;
            let issuer = Name::take_from(cons)?;
            let validity = Validity::take_from(cons)?;
            let subject = Name::take_from(cons)?;
            let subject_public_key_info = PublicKey::take_from(cons)?;


            // issuerUniqueID and subjectUniqueID must not be present in
            // resource certificates. So extension is next.

            let mut basic_ca = None;
            let mut subject_key_id = None;
            let mut authority_key_id = None;
            let mut key_usage = None;
            let mut extended_key_usage = None;
            let mut crl_uri = None;
            let mut ca_issuer = None;
            let mut sia = None;
            let mut overclaim = None;
            let mut ip_resources = None;
            let mut ip_overclaim = None;
            let mut as_resources = None;
            let mut as_overclaim = None;

            cons.take_constructed_if(Tag::CTX_3, |c| c.take_sequence(|cons| {
                while let Some(()) = cons.take_opt_sequence(|cons| {
                    let id = Oid::take_from(cons)?;
                    let critical = cons.take_opt_bool()?.unwrap_or(false);
                    let value = OctetString::take_from(cons)?;
                    Mode::Der.decode(value, |content| {
                        if id == oid::CE_BASIC_CONSTRAINTS {
                            Self::take_basic_constraints_critical(
                                content, critical, &mut basic_ca
                            )
                        } else if id == oid::CE_SUBJECT_KEY_IDENTIFIER {
                            Self::take_subject_key_identifier_critical(
                                content, critical, &mut subject_key_id
                            )
                        } else if id == oid::CE_AUTHORITY_KEY_IDENTIFIER {
                            Self::take_authority_key_identifier_critical(
                                content, critical, &mut authority_key_id
                            )
                        } else if id == oid::CE_KEY_USAGE {
                            Self::take_key_usage_critical(
                                content, critical, &mut key_usage
                            )
                        } else if id == oid::CE_EXTENDED_KEY_USAGE {
                            Self::take_extended_key_usage_critical(
                                content, critical, &mut extended_key_usage
                            )
                        } else if id == oid::CE_CRL_DISTRIBUTION_POINTS {
                            Self::take_crl_distribution_points(
                                content, critical, &mut crl_uri
                            )
                        } else if id == oid::PE_AUTHORITY_INFO_ACCESS {
                            Self::take_authority_info_access(
                                content, critical, &mut ca_issuer
                            )
                        } else if id == oid::PE_SUBJECT_INFO_ACCESS {
                            Self::take_subject_info_access_critical(
                                content, critical, &mut sia
                            )
                        } else if id == oid::CE_CERTIFICATE_POLICIES {
                            Self::take_certificate_policies(
                                content, critical, &mut overclaim
                            )
                        } else if let Some(m) = Overclaim::from_ip_res(&id) {
                            ip_overclaim = Some(m);
                            Self::take_ip_resources(content, &mut ip_resources)
                        } else if let Some(m) = Overclaim::from_as_res(&id) {
                            as_overclaim = Some(m);
                            Self::take_as_resources(content, &mut as_resources)
                        } else if critical {
                            Err(content.content_err(
                                UnexpectedCriticalExtension::new(id)
                            ))
                        } else {
                            // RFC 5280 says we can ignore non-critical
                            // extensions we don’t know of. RFC 6487
                            // agrees. So let’s do that.
                            Ok(())
                        }
                    }).map_err(DecodeError::convert)?;
                    Ok(())
                })? { }
                Ok(())
            }))?;

            if ip_resources.is_none() && as_resources.is_none() {
                return Err(cons.content_err(
                    "both AS and IP resources extensions are missing"
                ))
            }
            if ip_resources.is_some() && ip_overclaim != overclaim {
                return Err(cons.content_err(
                    "wrong IP resources extension for certificate policy"
                ))
            }
            if as_resources.is_some() && as_overclaim != overclaim {
                return Err(cons.content_err(
                    "wrong AS resources extension for certificate policy"
                ))
            }
            let (v4_resources, v6_resources) = ip_resources.unwrap_or_default();
            let (ca_repository, rpki_manifest, signed_object, rpki_notify) = {
                match sia {
                    Some(sia) => (
                        sia.ca_repository, sia.rpki_manifest,
                        sia.signed_object, sia.rpki_notify
                    ),
                    None => (None, None, None, None)
                }
            };

            Ok(Self {
                serial_number,
                signature,
                issuer,
                validity,
                subject,
                subject_public_key_info,
                basic_ca,
                subject_key_identifier: subject_key_id.ok_or_else(|| {
                    cons.content_err(
                        "missing Subject Key Identifier extension"
                    )
                })?,
                authority_key_identifier: authority_key_id,
                key_usage: key_usage.ok_or_else(|| {
                    cons.content_err(
                        "missing Key Usage extension"
                    )
                })?,
                extended_key_usage,
                crl_uri,
                ca_issuer,
                ca_repository,
                rpki_manifest,
                signed_object,
                rpki_notify,
                overclaim: overclaim.ok_or_else(|| {
                    cons.content_err(
                        "missing Certificate Policies extension"
                    )
                })?,
                v4_resources: v4_resources.unwrap_or_else(
                    IpResources::missing
                ),
                v6_resources: v6_resources.unwrap_or_else(
                    IpResources::missing
                ),
                as_resources: as_resources.unwrap_or_else(
                    AsResources::missing
                ),
            })
        })
    }

    // The following functions are re-used by the CA module for parsing
    // certificate signing requests and identity certificates. Neither of
    // the currently check the critical flag and introducing such a check
    // could break interoperability and existing Krill installations.
    //
    // To avoid that, we keep versions that do and do not check the flag for
    // now if they are reused, i.e., are `pub(crate)`.

    /// Parses the Basic Constraints extension.
    ///
    /// ```text
    /// BasicConstraints        ::= SEQUENCE {
    ///     cA                      BOOLEAN DEFAULT FALSE,
    ///     pathLenConstraint       INTEGER (0..MAX) OPTIONAL
    /// }
    /// ```
    ///
    /// For resource certificates, the extension must be critical. It must be
    /// present for CA certificates and must not be present for EE
    /// certificates. RFC 6487 says that the issued decides whether the cA
    /// boolean is to be set or not, but for all CA certificates it must be
    /// set (required indirectly by requiring the keyCertSign bit set in
    /// the key usage extension) so really it must always be true if the
    /// extension is present.
    ///
    /// The pathLenConstraint field must not be present.
    pub(crate) fn take_basic_constraints<S: decode::Source>(
        cons: &mut decode::Constructed<S>,
        basic_ca: &mut Option<bool>,
    ) -> Result<(), DecodeError<S::Error>> {
        if basic_ca.is_some() {
            Err(cons.content_err("duplicate Basic Constraints extension"))
        }
        else {
           cons.take_sequence(|cons| {
                *basic_ca = Some(cons.take_opt_bool()?.unwrap_or(false));
                if cons.take_opt_u64()?.is_some() {
                    Err(cons.content_err(
                        "pathLenConstraint in Basic Constraints extension"
                    ))
                } else {
                    Ok(())
                }
            })
        }
    }

    /// Parses the Basic Constraints extension considering the critical flag.
    ///
    /// The extension is critial for resource certficates.
    pub(crate) fn take_basic_constraints_critical<S: decode::Source>(
        cons: &mut decode::Constructed<S>,
        critical: bool,
        basic_ca: &mut Option<bool>,
    ) -> Result<(), DecodeError<S::Error>> {
        if !critical {
            Err(cons.content_err("non-critical Basic Constraints extension"))
        }
        else {
            Self::take_basic_constraints(cons, basic_ca)
        }
    }

    /// Parses the Subject Key Identifier extension.
    ///
    /// ```text
    /// SubjectKeyIdentifier ::= KeyIdentifier
    /// ```
    ///
    /// The extension must be present and contain the 160 bit SHA-1 hash of
    /// the value of the DER-encoded bit string of the subject public key.
    ///
    /// Conforming CAs MUST mark this extension as non-critical.
    pub(crate) fn take_subject_key_identifier<S: decode::Source>(
        cons: &mut decode::Constructed<S>,
        subject_key_id: &mut Option<KeyIdentifier>,
    ) -> Result<(), DecodeError<S::Error>> {
        if subject_key_id.is_some() {
            Err(cons.content_err(
                "duplicate Subject Key Identifier extension"
            ))
        }
        else {
            *subject_key_id = Some(KeyIdentifier::take_from(cons)?);
            Ok(())
        }
    }

    /// Parses the Subject Key Identifier considering the critical flag.
    ///
    /// Must be non-critical for all Internet certificates.
    fn take_subject_key_identifier_critical<S: decode::Source>(
        cons: &mut decode::Constructed<S>,
        critical: bool,
        basic_ca: &mut Option<KeyIdentifier>,
    ) -> Result<(), DecodeError<S::Error>> {
        if critical {
            Err(cons.content_err(
                "critical Subject Key Identifier extension"
            ))
        }
        else {
            Self::take_subject_key_identifier(cons, basic_ca)
        }
    }

    /// Parses the Authority Key Identifier extension.
    ///
    /// ```text
    /// AuthorityKeyIdentifier ::= SEQUENCE {
    ///   keyIdentifier             [0] KeyIdentifier           OPTIONAL,
    ///   authorityCertIssuer       [1] GeneralNames            OPTIONAL,
    ///   authorityCertSerialNumber [2] CertificateSerialNumber OPTIONAL  }
    /// ```
    ///
    /// Must be present except in self-signed CA certificates where it is
    /// optional. The keyIdentifier field must be present, the other must not
    /// be.
    fn take_authority_key_identifier<S: decode::Source>(
        cons: &mut decode::Constructed<S>,
        authority_key_id: &mut Option<KeyIdentifier>,
    ) -> Result<(), DecodeError<S::Error>> {
        if authority_key_id.is_some() {
            Err(cons.content_err(
                "duplicate Authority Key Identifier extension"
            ))
        }
        else {
            *authority_key_id = Some(
                cons.take_sequence(|cons| {
                    cons.take_value_if(Tag::CTX_0, KeyIdentifier::from_content)
                })?
            );
            Ok(())
        }
    }

    /// Parses the Authority Key Identifier considering the critical flag.
    ///
    /// Must be non-critical for all Internet certificates.
    fn take_authority_key_identifier_critical<S: decode::Source>(
        cons: &mut decode::Constructed<S>,
        critical: bool,
        authority_key_id: &mut Option<KeyIdentifier>,
    ) -> Result<(), DecodeError<S::Error>> {
        if critical {
            Err(cons.content_err(
                "critical Authority Key Identifier extension"
            ))
        }
        else {
            Self::take_authority_key_identifier(cons, authority_key_id)
        }
    }

    /// Parses the Key Usage extension.
    ///
    /// ```text
    /// KeyUsage ::= BIT STRING {
    ///      digitalSignature        (0),
    ///      nonRepudiation          (1), -- recent editions of X.509 have
    ///                           -- renamed this bit to contentCommitment
    ///      keyEncipherment         (2),
    ///      dataEncipherment        (3),
    ///      keyAgreement            (4),
    ///      keyCertSign             (5),
    ///      cRLSign                 (6),
    ///      encipherOnly            (7),
    ///      decipherOnly            (8) }
    /// ```
    ///
    /// Must be present. In CA certificates, keyCertSign and
    /// CRLSign must be set, in EE certificates, digitalSignatures must be
    /// set. All other bits must be zero. DER encoding mandates that all
    /// trailing zeros must be removed.
    pub(crate) fn take_key_usage<S: decode::Source>(
        cons: &mut decode::Constructed<S>,
        key_usage: &mut Option<KeyUsage>
    ) -> Result<(), DecodeError<S::Error>> {
        if key_usage.is_some() {
            Err(cons.content_err("duplicate Key Usage extension"))
        }
        else {
            *key_usage = Some({
                let bits = BitString::take_from(cons)?;
                if bits.bit_len() == 7 && bits.octet(0) == 0b0000_0110 {
                    Ok(KeyUsage::Ca)
                }
                else if bits.bit_len() == 1 && bits.bit(0) {
                    Ok(KeyUsage::Ee)
                }
                else {
                    Err(cons.content_err("invalid Key Usage"))
                }
            }?);
            Ok(())
        }
    }

    /// Parses the Key Usage extension considering the critical flag.
    ///
    /// Should be critical for Internet certificates and must be critical
    /// for resource certificates (although not explicitely a MUST, so you
    /// could argue that non-critical is fine).
    fn take_key_usage_critical<S: decode::Source>(
        cons: &mut decode::Constructed<S>,
        critical: bool,
        key_usage: &mut Option<KeyUsage>
    ) -> Result<(), DecodeError<S::Error>> {
        if !critical {
            Err(cons.content_err("non-critical Key Usage extension"))
        }
        else {
            Self::take_key_usage(cons, key_usage)
        }
    }

    /// Parses the Extended Key Usage extension.
    ///
    /// ```text
    /// ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
    /// KeyPurposeId ::= OBJECT IDENTIFIER
    /// ```
    ///
    /// May only be present in EE certificates issued to devices.
    pub(crate) fn take_extended_key_usage<S: decode::Source>(
        cons: &mut decode::Constructed<S>,
        extended_key_usage: &mut Option<ExtendedKeyUsage>
    ) -> Result<(), DecodeError<S::Error>> {
        if extended_key_usage.is_some() {
            Err(cons.content_err("duplicate Extended Key Usage extension"))
        }
        else {
            *extended_key_usage = Some(ExtendedKeyUsage::take_from(cons)?);
            Ok(())
        }
    }

    /// Parses the Extended Key Usage considering the critical flag.
    ///
    /// Must not be critical for resource certficates.
    fn take_extended_key_usage_critical<S: decode::Source>(
        cons: &mut decode::Constructed<S>,
        critical: bool,
        extended_key_usage: &mut Option<ExtendedKeyUsage>
    ) -> Result<(), DecodeError<S::Error>> {
        if critical {
            Err(cons.content_err("critical Extended Key Usage extension"))
        }
        else {
            Self::take_extended_key_usage(cons, extended_key_usage)
        }
    }

    /// Parses the CRL Distribution Points extension.
    ///
    /// ```text
    /// CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
    ///
    /// DistributionPoint ::= SEQUENCE {
    ///    distributionPoint       [0]     DistributionPointName OPTIONAL,
    ///    reasons                 [1]     ReasonFlags OPTIONAL,
    ///    cRLIssuer               [2]     GeneralNames OPTIONAL }
    ///
    /// DistributionPointName ::= CHOICE {
    ///    fullName                [0]     GeneralNames,
    ///    nameRelativeToCRLIssuer [1]     RelativeDistinguishedName }
    /// ```
    ///
    /// Must be present except in self-signed certificates.
    ///
    /// It must contain exactly one Distribution Point. Only its
    /// distributionPoint field must be present and it must contain
    /// the fullName choice which can be one or more uniformResourceIdentifier
    /// choices.
    ///
    /// This extensions is non-critical for resource certificates.
    fn take_crl_distribution_points<S: decode::Source>(
        cons: &mut decode::Constructed<S>,
        critical: bool,
        crl_uri: &mut Option<uri::Rsync>
    ) -> Result<(), DecodeError<S::Error>> {
        if crl_uri.is_some() {
            Err(cons.content_err(
                "duplicate CRL Distribution Points extension"
            ))
        }
        else if critical {
            Err(cons.content_err(
                "critical CRL Distribution Points extension"
            ))
        }
        else {
            *crl_uri = Some(
                // CRLDistributionPoints
                cons.take_sequence(|cons| {
                    // DistributionPoint
                    cons.take_sequence(|cons| {
                        // distributionPoint
                        cons.take_constructed_if(Tag::CTX_0, |cons| {
                            // fullName
                            cons.take_constructed_if(Tag::CTX_0, |cons| {
                                // GeneralNames content
                                take_general_names_content(
                                    cons,
                                    "invalid CRL Distribution Points \
                                     extension",
                                    uri::Rsync::from_bytes,
                                )
                            })
                        })
                    })
                })?
            );
            Ok(())
        }
    }

    /// Parses the Authority Information Access extension.
    ///
    /// ```text
    /// AuthorityInfoAccessSyntax  ::=
    ///         SEQUENCE SIZE (1..MAX) OF AccessDescription
    ///
    /// AccessDescription  ::=  SEQUENCE {
    ///         accessMethod          OBJECT IDENTIFIER,
    ///         accessLocation        GeneralName  }
    /// ```
    ///
    /// Must be present except in self-signed certificates. Must contain
    /// exactly one entry with accessMethod id-ad-caIssuers and URIs in the
    /// generalName. There must be one rsync URI, there may be more. We only
    /// support the one, though, so we’ll ignore the rest.
    ///
    /// This extensions is non-critical for all internet certificates.
    fn take_authority_info_access<S: decode::Source>(
        cons: &mut decode::Constructed<S>,
        critical: bool,
        ca_issuer: &mut Option<uri::Rsync>
    ) -> Result<(), DecodeError<S::Error>> {
        if ca_issuer.is_some() {
            Err(cons.content_err(
                "duplicate Authority Information Access extension"
            ))
        }
        else if critical {
            Err(cons.content_err(
                "critical Authority Information Access extension"
            ))
        }
        else {
            *ca_issuer = Some(
                cons.take_sequence(|cons| {
                    cons.take_sequence(|cons| {
                        oid::AD_CA_ISSUERS.skip_if(cons)?;
                        take_general_names_content(
                            cons,
                            "invalid Authority Information Access extension",
                            uri::Rsync::from_bytes,
                        )
                    })
                })?
            );
            Ok(())
        }
    }

    /// Parses the Subject Information Access extension.
    ///
    /// ```text
    /// SubjectInfoAccessSyntax  ::=
    ///         SEQUENCE SIZE (1..MAX) OF AccessDescription
    ///
    /// AccessDescription  ::=  SEQUENCE {
    ///         accessMethod          OBJECT IDENTIFIER,
    ///         accessLocation        GeneralName  }
    /// ```
    ///
    /// Must be present.
    ///
    /// For CA certificates, there must be two AccessDescriptions, one with
    /// id-ad-caRepository and one with id-ad-rpkiManifest, both with rsync
    /// URIs. Additional id-ad-rpkiManifest descriptions may be present with
    /// additional access mechanisms for the manifest.
    ///
    /// Additionally, an id-ad-rpkiNotify may be present with a HTTPS URI.
    ///
    /// For EE certificates, there must at least one AccessDescription value
    /// with an id-ad-signedObject access method.
    ///
    /// Since we don’t necessarily know what kind of certificate we have yet,
    /// we may accept the wrong kind here. This needs to be checked later.
    pub(crate) fn take_subject_info_access<S: decode::Source>(
        cons: &mut decode::Constructed<S>,
        sia: &mut Option<Sia>,
    ) -> Result<(), DecodeError<S::Error>> {
        if sia.is_some() {
            Err(cons.content_err(
                "duplicate Subject Key Identifier extension"
            ))
        }
        else {
            *sia = Some(Sia::take_from(cons)?);
            Ok(())
        }
    }

    /// Parses the Subject Information Access considering the critical flag.
    ///
    /// This extensions is non-critical for all internet certificates.
    fn take_subject_info_access_critical<S: decode::Source>(
        cons: &mut decode::Constructed<S>,
        critical: bool,
        sia: &mut Option<Sia>,
    ) -> Result<(), DecodeError<S::Error>> {
        if critical {
            Err(cons.content_err(
                "critical Subject Key Identifier extension"
            ))
        }
        else {
            Self::take_subject_info_access(cons, sia)
        }
    }

    /// Parses the Certificate Policies extension.
    ///
    /// ```text
    /// certificatePolicies ::= SEQUENCE SIZE (1..MAX) OF PolicyInformation
    ///
    /// PolicyInformation ::= SEQUENCE {
    ///     policyIdentifier   CertPolicyId,
    ///     policyQualifiers   SEQUENCE SIZE (1..MAX) OF
    ///                             PolicyQualifierInfo OPTIONAL }
    ///
    /// CertPolicyId ::= OBJECT IDENTIFIER
    ///
    /// [...]
    /// ```
    ///
    /// Must be present. There are two policyIdentifiers for resource
    /// certificates. They define how we deal with overclaim of resources.
    /// The policyQualifiers are not interesting for us.
    ///
    /// Must be critical for resource certificates.
    fn take_certificate_policies<S: decode::Source>(
        cons: &mut decode::Constructed<S>,
        critical: bool,
        overclaim: &mut Option<Overclaim>,
    ) -> Result<(), DecodeError<S::Error>> {
        if overclaim.is_some() {
            Err(cons.content_err("duplicate Certificate Policies extension"))
        }
        else if !critical {
            Err(cons.content_err(
                "non-critical Certificate Policies extension"
            ))
        }
        else {
            *overclaim = Some(
                cons.take_sequence(|cons| {
                    cons.take_sequence(|cons| {
                        let res = Overclaim::from_policy(
                            &Oid::take_from(cons)?
                        ).map_err(|err| cons.content_err(err))?;

                        // policyQualifiers. This is a sequence of sequences
                        // with stuff we don’t really care about. Let’s skip
                        // all the rest.
                        cons.skip_all()?;
                        Ok(res)
                    })
                })?
            );
            Ok(())
        }
    }

    /// Parses the IP Resources extension.
    fn take_ip_resources<S: decode::Source>(
        cons: &mut decode::Constructed<S>,
        ip_resources: &mut Option<(Option<IpResources>, Option<IpResources>)>
    ) -> Result<(), DecodeError<S::Error>> {
        if ip_resources.is_some() {
            Err(cons.content_err("duplicate IP Resources extension"))
        }
        else {
            *ip_resources = Some(IpResources::take_families_from(cons)?);
            Ok(())
        }
    }

    /// Parses the AS Resources extension.
    fn take_as_resources<S: decode::Source>(
        cons: &mut decode::Constructed<S>,
        as_resources: &mut Option<AsResources>
    ) -> Result<(), DecodeError<S::Error>> {
        if as_resources.is_some() {
            Err(cons.content_err("duplicate AS Resources extension"))
        }
        else {
            *as_resources = Some(AsResources::take_from(cons)?);
            Ok(())
        }
    }

    /// Returns an encoder for the value.
    pub fn encode_ref(&self) -> impl encode::Values + '_ {
        encode::sequence((
            encode::sequence_as(Tag::CTX_0, 2.encode()), // version
            self.serial_number.encode(),
            self.signature.x509_encode(),
            self.issuer.encode_ref(),
            self.validity.encode(),
            self.subject.encode_ref(),
            self.subject_public_key_info.encode_ref(),
            // no issuerUniqueID
            // no subjectUniqueID
            // extensions
            encode::sequence_as(Tag::CTX_3, encode::sequence((
                // Basic Constraints
                self.basic_ca.map(|ca| {
                    encode_extension(
                        &oid::CE_BASIC_CONSTRAINTS, true,
                        encode::sequence(
                            if ca {
                                Some(ca.encode())
                            }
                            else {
                                None
                            }
                        )
                    )
                }),

                // Subject Key Identifier
                encode_extension(
                    &oid::CE_SUBJECT_KEY_IDENTIFIER, false,
                    self.subject_key_identifier.encode_ref(),
                ),

                // Authority Key Identifier
                self.authority_key_identifier.as_ref().map(|id| {
                    encode_extension(
                        &oid::CE_AUTHORITY_KEY_IDENTIFIER, false,
                        encode::sequence(id.encode_ref_as(Tag::CTX_0))
                    )
                }),

                // Key Usage
                encode_extension(
                    &oid::CE_KEY_USAGE, true,
                    self.key_usage.encode()
                ),

                // Extended Key Usage
                self.extended_key_usage.as_ref().map(|eku| {
                    encode_extension(
                        &oid::CE_EXTENDED_KEY_USAGE, false,
                        encode::sequence(eku.encode_ref())
                    )
                }),

                // CRL Distribution Points
                self.crl_uri.as_ref().map(|uri| {
                    encode_extension(
                        &oid::CE_CRL_DISTRIBUTION_POINTS, false,
                        encode::sequence( // CRLDistributionPoints
                            encode::sequence( // DistributionPoint
                                encode::sequence_as(Tag::CTX_0, // distrib.Pt.
                                    encode::sequence_as(Tag::CTX_0, // fullName
                                        uri.encode_general_name()
                                    )
                                )
                            )
                        )
                    )
                }),

                // Authority Information Access
                self.ca_issuer.as_ref().map(|uri| {
                    encode_extension(
                    &oid::PE_AUTHORITY_INFO_ACCESS, false,
                        encode::sequence(
                            encode::sequence((
                                oid::AD_CA_ISSUERS.encode(),
                                uri.encode_general_name()
                            ))
                        )
                    )
                }),

                // Subject Information Access
                if self.ca_repository.is_some()
                    || self.rpki_manifest.is_some()
                    || self.signed_object.is_some()
                    || self.rpki_notify.is_some()
                {
                    Some(encode_extension(
                        &oid::PE_SUBJECT_INFO_ACCESS, false,
                        encode::sequence((
                            self.ca_repository.as_ref().map(|uri| {
                                encode::sequence((
                                    oid::AD_CA_REPOSITORY.encode(),
                                    uri.encode_general_name()
                                ))
                            }),
                            self.rpki_manifest.as_ref().map(|uri| {
                                encode::sequence((
                                    oid::AD_RPKI_MANIFEST.encode(),
                                    uri.encode_general_name()
                                ))
                            }),
                            self.signed_object.as_ref().map(|uri| {
                                encode::sequence((
                                    oid::AD_SIGNED_OBJECT.encode(),
                                    uri.encode_general_name()
                                ))
                            }),
                            self.rpki_notify.as_ref().map(|uri| {
                                encode::sequence((
                                    oid::AD_RPKI_NOTIFY.encode(),
                                    uri.encode_general_name()
                                ))
                            })
                        ))
                    ))
                }
                else {
                    None
                },

                // Certificate Policies
                encode_extension(
                    &oid::CE_CERTIFICATE_POLICIES, true,
                    encode::sequence(
                        encode::sequence(
                            self.overclaim.policy_id().encode()
                            // policyQualifiers sequence is optional
                        )
                    )
                ),

                // IP Resources
                IpResources::encode_extension(
                    self.overclaim(),
                    self.v4_resources(),
                    self.v6_resources()
                ),

                // AS Resources
                self.as_resources.encode_extension(self.overclaim)
            )))
        ))
    }
}


//------------ Helpers for Decoding and Encoding -----------------------------

/// Parses a URI from the content of a GeneralNames sequence.
///
/// ```text
/// GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
///
/// GeneralName ::= CHOICE {
///    ...
///    uniformResourceIdentifier       [6]     IA5String,
///    ... }
/// ```
///
/// Takes the first name for which the closure returns successfully. Ignores
/// values where the closure produces an error. If there is more than one case
/// where the closure returns successfully, that’s an error, too.
fn take_general_names_content<S: decode::Source, F, T, E>(
    cons: &mut decode::Constructed<S>,
    error_msg: &'static str,
    mut op: F
) -> Result<T, DecodeError<S::Error>>
where F: FnMut(Bytes) -> Result<T, E> {
    let mut res = None;
    while let Some(()) = cons.take_opt_value_if(Tag::CTX_6, |content| {
        let uri = Ia5String::from_content(content)?;
        if let Ok(uri) = op(uri.into_bytes()) {
            if res.is_some() {
                return Err(content.content_err(error_msg))
            }
            res = Some(uri)
        }
        Ok(())
    })? {}
    match res {
        Some(res) => Ok(res),
        None => Err(cons.content_err(error_msg))
    }
}

fn take_general_name<S: decode::Source, F, T, E>(
    cons: &mut decode::Constructed<S>,
    mut op: F
) -> Result<Option<T>, DecodeError<S::Error>>
where F: FnMut(Bytes) -> Result<T, E> {
    cons.take_value_if(Tag::CTX_6, |content| {
        Ia5String::from_content(content).map(|uri| {
            op(uri.into_bytes()).ok()
        })
    })
}


//------------ Sia -----------------------------------------------------------

/// Internal helper type for parsing Subject Information Access.
#[derive(Clone, Debug, Default)]
pub(crate) struct Sia {
    ca_repository: Option<uri::Rsync>,
    rpki_manifest: Option<uri::Rsync>,
    signed_object: Option<uri::Rsync>,
    rpki_notify: Option<uri::Https>,
}

#[cfg(feature = "ca")]
impl Sia {
    pub(crate) fn ca_repository(&self) -> Option<&uri::Rsync> {
        self.ca_repository.as_ref()
    }
    pub(crate) fn rpki_manifest(&self) -> Option<&uri::Rsync> {
        self.rpki_manifest.as_ref()
    }
    pub(crate) fn rpki_notify(&self) -> Option<&uri::Https> {
        self.rpki_notify.as_ref()
    }
}

impl Sia {
    pub fn take_from<S: decode::Source>(
        cons: &mut decode::Constructed<S>
    ) -> Result<Self, DecodeError<S::Error>> {
        let mut sia = Sia::default();
        let mut any_seen = false;
        cons.take_sequence(|cons| {
            while let Some(()) = cons.take_opt_sequence(|cons| {
                let oid = Oid::take_from(cons)?;
                any_seen = true;
                if oid == oid::AD_CA_REPOSITORY {
                    update_first(&mut sia.ca_repository, || {
                        take_general_name(
                            cons, uri::Rsync::from_bytes
                        )
                    })
                }
                else if oid == oid::AD_RPKI_MANIFEST {
                    update_first(&mut sia.rpki_manifest, || {
                        take_general_name(
                            cons, uri::Rsync::from_bytes
                        )
                    })
                }
                else if oid == oid::AD_SIGNED_OBJECT {
                    update_first(&mut sia.signed_object, || {
                        take_general_name(
                            cons, uri::Rsync::from_bytes
                        )
                    })
                }
                else if oid == oid::AD_RPKI_NOTIFY {
                    update_first(&mut sia.rpki_notify, || {
                        take_general_name(
                            cons, uri::Https::from_bytes
                        )
                    })
                }
                else {
                    // XXX Presumably it is fine to just skip over
                    //     these things. Since this is DER, it can’t
                    //     be tricked into reading forever.
                    cons.skip_all()
                }
            })? { }
            Ok(())
        })?;
        if any_seen {
            Ok(sia)
        }
        else {
            Err(cons.content_err(
                "empty Subject Information Access extension"
            ))
        }
    }
}


//------------ ResourceCert --------------------------------------------------

/// A validated resource certificate.
///
/// This differs from a normal [`Cert`] in that its IP and AS resources are
/// resolved into concrete values.
#[derive(Clone, Debug)]
pub struct ResourceCert {
    /// The underlying resource certificate.
    cert: Cert,

    /// The resolved IPv4 resources.
    v4_resources: IpBlocks,

    /// The resolved IPv6 resources.
    v6_resources: IpBlocks,

    /// The resolved AS resources.
    as_resources: AsBlocks,

    /// The TAL this is based on.
    tal: Arc<TalInfo>,
}

impl ResourceCert {
    /// Returns a reference to the underlying certificate.
    pub fn as_cert(&self) -> &Cert {
        &self.cert
    }

    /// Returns a reference to the IPv4 resources of this certificate.
    pub fn v4_resources(&self) -> &IpBlocks {
        &self.v4_resources
    }

    /// Returns a reference to the IPv6 resources of this certificate.
    pub fn v6_resources(&self) -> &IpBlocks {
        &self.v6_resources
    }

    /// Returns a reference to the AS resources of this certificate.
    pub fn as_resources(&self) -> &AsBlocks {
        &self.as_resources
    }

    /// Returns information about the TAL this certificate is based on.
    pub fn tal(&self) -> &Arc<TalInfo> {
        &self.tal
    }

    /// Converts the certificate into its TAL info.
    pub fn into_tal(self) -> Arc<TalInfo> {
        self.tal
    }
}


//--- Deref and AsRef

impl ops::Deref for ResourceCert {
    type Target = Cert;

    fn deref(&self) -> &Cert {
        self.as_cert()
    }
}

impl AsRef<Cert> for ResourceCert {
    fn as_ref(&self) -> &Cert {
        self.as_cert()
    }
}

impl AsRef<TbsCert> for ResourceCert {
    fn as_ref(&self) -> &TbsCert {
        self.as_cert().as_ref()
    }
}


//------------ KeyUsage ------------------------------------------------------

/// The allowed key usages of a resource certificate.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum KeyUsage {
    /// A CA certificate.
    Ca,

    /// An end-entity certificate.
    Ee,
}

impl KeyUsage {
    /// Returns a value encoder for the key usage.
    pub fn encode(self) -> impl encode::Values {
        let s = match self {
            KeyUsage::Ca => b"\x01\x06", // Bits 5 and 6
            KeyUsage::Ee => b"\x07\x80", // Bit 0
        };
        s.encode_as(Tag::BIT_STRING)
    }
}


//------------ ExtendedKeyUsage ----------------------------------------------

/// The allowed key usages (extended version) of a resource certificate.
#[derive(Clone, Debug)]
pub struct ExtendedKeyUsage {
    content: Captured,
    has_bgpsec_router: bool,
}

impl ExtendedKeyUsage {
    fn take_from<S: decode::Source>(
        cons: &mut decode::Constructed<S>
    ) -> Result<Self, DecodeError<S::Error>> {
        let mut has_bgpsec_router = false;
        let content = cons.take_sequence(|cons| cons.capture(|cons| {
            let mut empty = true;
            while let Some(oid) = Oid::take_opt_from(cons)? {
                if oid == oid::KP_BGPSEC_ROUTER {
                    has_bgpsec_router = true;
                }
                empty = false;
            }
            if empty {
                Err(cons.content_err(
                    "empty Extended key Usage extension"
                ))
            }
            else {
                Ok(())
            }
        }))?;
        Ok(ExtendedKeyUsage { content, has_bgpsec_router })
    }

    fn encode_ref(&self) -> impl encode::Values + '_ {
        &self.content
    }

    pub fn inspect_router(&self) -> Result<(), InspectionError> {
        if self.has_bgpsec_router {
            Ok(())
        }
        else {
            Err(InspectionError::new(
                "Extended Key Usage extension is missing \
                 id-kp-bgpsec-router usage in router certificate"
            ))
        }
    }

    /// Create a BGP Sec Router Extended Key Usage
    pub fn create_router() -> Self {
        ExtendedKeyUsage {
            content: oid::KP_BGPSEC_ROUTER.encode().to_captured(Mode::Der),
            has_bgpsec_router: true
        }
    }
}


//------------ Overclaim -----------------------------------------------------

/// The overclaim mode for resource validation.
///
/// In the original RPKI specification, a certificate becomes valid if it
/// claims more resources than its issuer, a condition known as
/// ‘overclaiming’. [RFC 8360] proposed an alternative approach where in this
/// case the resources of the certificate are simply trimmed back to what the
/// issuer certificate allows. This makes handling cases where a CA loses some
/// resources easier.
///
/// A certificate can choose to use the old or new method by using different
/// OIDs for the certificate policy and the resource extensions.
///
/// This type specifies which mode a certificate uses.
///
/// [RFC 8380]: https://tools.ietf.org/html/rfc8360
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum Overclaim {
    /// A certificate becomes invalid if it overclaims resources.
    Refuse,

    /// Overclaimed resources are trimmed to the by encompassed by the issuer.
    Trim,
}

impl Overclaim {
    fn from_policy(
        oid: &Oid
    ) -> Result<Self, ContentError> {
        if oid == &oid::CP_IPADDR_ASNUMBER {
            Ok(Overclaim::Refuse)
        }
        else if oid == &oid::CP_IPADDR_ASNUMBER_V2 {
            Ok(Overclaim::Trim)
        }
        else {
            Err("invalid Certificate Policy identifier".into())
        }
    }

    fn from_ip_res(oid: &Oid) -> Option<Self> {
        if oid == &oid::PE_IP_ADDR_BLOCK {
            Some(Overclaim::Refuse)
        }
        else if oid == &oid::PE_IP_ADDR_BLOCK_V2 {
            Some(Overclaim::Trim)
        }
        else {
            None
        }
    }

    fn from_as_res(oid: &Oid) -> Option<Self> {
        if oid == &oid::PE_AUTONOMOUS_SYS_IDS {
            Some(Overclaim::Refuse)
        }
        else if oid == &oid::PE_AUTONOMOUS_SYS_IDS_V2 {
            Some(Overclaim::Trim)
        }
        else {
            None
        }
    }

    pub fn policy_id(self) -> &'static ConstOid {
        match self {
            Overclaim::Refuse => &oid::CP_IPADDR_ASNUMBER,
            Overclaim::Trim => &oid::CP_IPADDR_ASNUMBER_V2
        }
    }

    pub fn ip_res_id(self) -> &'static ConstOid {
        match self {
            Overclaim::Refuse => &oid::PE_IP_ADDR_BLOCK,
            Overclaim::Trim => &oid::PE_IP_ADDR_BLOCK_V2
        }
    }

    pub fn as_res_id(self) -> &'static ConstOid {
        match self {
            Overclaim::Refuse => &oid::PE_AUTONOMOUS_SYS_IDS,
            Overclaim::Trim => &oid::PE_AUTONOMOUS_SYS_IDS_V2
        }
    }
}


//============ Error Types ===================================================

//------------ InvalidExtension ----------------------------------------------

/// An invalid certificate extension was encountered.
#[derive(Clone, Debug)]
pub(crate) struct InvalidExtension {
    oid: Oid<Bytes>,
}

impl InvalidExtension {
    #[cfg(feature = "ca")]
    pub(crate) fn new(oid: Oid<Bytes>) -> Self {
        InvalidExtension { oid }
    }
}

impl From<InvalidExtension> for ContentError {
    fn from(err: InvalidExtension) -> Self {
        ContentError::from_boxed(Box::new(err))
    }
}

impl fmt::Display for InvalidExtension {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "invalid extension {}", self.oid)
    }
}


//------------ UnexpectedCriticalExtension -----------------------------------

/// An invalid certificate extension was encountered.
#[derive(Clone, Debug)]
struct UnexpectedCriticalExtension {
    oid: Oid<Bytes>,
}

impl UnexpectedCriticalExtension {
    fn new(oid: Oid<Bytes>) -> Self {
       UnexpectedCriticalExtension { oid }
    }
}

impl From<UnexpectedCriticalExtension> for ContentError {
    fn from(err: UnexpectedCriticalExtension) -> Self {
        ContentError::from_boxed(Box::new(err))
    }
}

impl fmt::Display for UnexpectedCriticalExtension {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "unexpected critical extension {}", self.oid)
    }
}


//------------ IssuerError ---------------------------------------------------

/// An error happened when decoding the certificate’s subject.
#[derive(Debug)]
struct IssuerError(InspectionError);

impl From<IssuerError> for InspectionError {
    fn from(err: IssuerError) -> Self {
        ContentError::from_boxed(Box::new(err)).into()
    }
}

impl fmt::Display for IssuerError{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "invalid subject: {}", self.0)
    }
}


//------------ SubjectError --------------------------------------------------

/// An error happened when decoding the certificate’s subject.
#[derive(Debug)]
struct SubjectError(InspectionError);

impl From<SubjectError> for InspectionError {
    fn from(err: SubjectError) -> Self {
        ContentError::from_boxed(Box::new(err)).into()
    }
}

impl fmt::Display for SubjectError{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "invalid subject: {}", self.0)
    }
}


//============ Tests =========================================================

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

    #[test]
    fn decode_and_inspect_certs() {
        Cert::decode(
            include_bytes!("../../test-data/repository/ta.cer").as_ref()
        ).unwrap().inspect_ta(true).unwrap();
        Cert::decode(
            include_bytes!("../../test-data/repository/ca1.cer").as_ref()
        ).unwrap().inspect_ca(true).unwrap();
        Cert::decode(
            include_bytes!("../../test-data/repository/router.cer").as_ref()
        ).unwrap().inspect_router(true).unwrap();
    }

    /// Tests that inconsistent algorithm encoding fails validation.
    ///
    /// Specifically, tests that a certificate with different encoding of
    /// the signature algorithm parameters (NULL value v. not present) in
    /// the outer certificate structure and inside the TbsCertificate will
    /// be rejected during the inspection step.
    #[test]
    fn signature_algorithm_mismatch() {
        let roa = crate::repository::roa::Roa::decode(
            include_bytes!(
                "../../test-data/repository/example-ripe.roa"
            ).as_ref(),
            false
        ).unwrap();
        assert!(roa.cert().inspect_ee(true).is_ok());

        let mft = crate::repository::manifest::Manifest::decode(
            include_bytes!(
                "../../test-data/repository/signature-alg-mismatch.mft"
            ).as_ref(),
            false
        ).unwrap();
        assert!(mft.cert().inspect_ee(true).is_err());
    }

    #[test]
    #[cfg(feature = "serde")]
    fn serde_cert() {
        let der = include_bytes!("../../test-data/repository/ta.cer");
        let cert = Cert::decode(Bytes::from_static(der)).unwrap();

        let serialize = serde_json::to_string(&cert).unwrap();
        let des_cert: Cert = serde_json::from_str(&serialize).unwrap();

        assert_eq!(
            cert.to_captured().into_bytes(),
            des_cert.to_captured().into_bytes()
        );
    }

    #[test]
    #[cfg(feature = "serde")]
    fn compat_de_cert() {
        serde_json::from_slice::<Cert>(include_bytes!(
            "../../test-data/repository/serde-compat/cert.json"
        )).unwrap();
    }
}

#[cfg(all(test, feature="softkeys"))]
mod signer_test {
    use std::str::FromStr;
    use crate::crypto::PublicKeyFormat;
    use crate::crypto::softsigner::OpenSslSigner;
    use crate::repository::resources::{Asn, Prefix};
    use super::*;


    #[test]
    fn build_ta_cert() {
        let signer = OpenSslSigner::new();
        let key = signer.create_key(PublicKeyFormat::Rsa).unwrap();
        let pubkey = signer.get_key_info(&key).unwrap();
        let uri = uri::Rsync::from_str("rsync://example.com/m/p").unwrap();
        let mut cert = TbsCert::new(
            12u64.into(), pubkey.to_subject_name(),
            Validity::from_secs(86400), None, pubkey, KeyUsage::Ca,
            Overclaim::Trim
        );
        cert.set_basic_ca(Some(true));
        cert.set_ca_repository(Some(uri.clone()));
        cert.set_rpki_manifest(Some(uri));
        cert.build_v4_resource_blocks(|b| b.push(Prefix::new(0, 0)));
        cert.build_v6_resource_blocks(|b| b.push(Prefix::new(0, 0)));
        cert.build_as_resource_blocks(|b| b.push((Asn::MIN, Asn::MAX)));
        let cert = cert.into_cert(&signer, &key).unwrap().to_captured();
        let cert = Cert::decode(cert.as_slice()).unwrap();
        let talinfo = TalInfo::from_name("foo".into()).into_arc();
        cert.validate_ta(talinfo, true).unwrap();
    }
}